Skip to content

Commit

Permalink
chore: support append or prepend
Browse files Browse the repository at this point in the history
  • Loading branch information
wre232114 committed Nov 5, 2023
1 parent 7df6848 commit 924688a
Show file tree
Hide file tree
Showing 12 changed files with 98 additions and 23 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ Implement all APIs of [magic-string](https://www.npmjs.com/package/magic-string)
## Bundle
- [x] addSource
- [x] generateMap
- [ ] append
- [x] append
- [ ] generateDecodedMap
- [ ] getIndentString
- [ ] indent
- [ ] prepend
- [x] prepend
- [x] toString
- [ ] isEmpty
- [ ] length
Expand All @@ -24,7 +24,7 @@ Implement all APIs of [magic-string](https://www.npmjs.com/package/magic-string)

## MagicString
- [ ] addSourcemapLocation
- [ ] append
- [x] append
- [ ] appendLeft
- [ ] appendRight
- [ ] clone
Expand All @@ -35,14 +35,14 @@ Implement all APIs of [magic-string](https://www.npmjs.com/package/magic-string)
- [ ] move
- [ ] overwrite
- [ ] update
- [ ] prepend
- [x] prepend
- [ ] prependLeft
- [ ] prependRight
- [ ] remove
- [ ] lastChar
- [ ] lastLine
- [ ] slice
- [ ] toString
- [x] toString
- [ ] isEmpty
- [ ] length
- [ ] trimLines
Expand Down
2 changes: 1 addition & 1 deletion crates/enhanced-magic-string/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
edition = "2021"
name = "enhanced-magic-string"
version = "0.0.1"
version = "0.0.2"
description = "Rust based magic-string implementation with sourcemap chains support"
authors = ["brightwu(吴明亮) <[email protected]>"]
license = "MIT"
Expand Down
10 changes: 5 additions & 5 deletions crates/enhanced-magic-string/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ Implement all APIs of [magic-string](https://www.npmjs.com/package/magic-string)
## Bundle
- [x] addSource
- [x] generateMap
- [ ] append
- [x] append
- [ ] generateDecodedMap
- [ ] getIndentString
- [ ] indent
- [ ] prepend
- [x] prepend
- [x] toString
- [ ] isEmpty
- [ ] length
Expand All @@ -24,7 +24,7 @@ Implement all APIs of [magic-string](https://www.npmjs.com/package/magic-string)

## MagicString
- [ ] addSourcemapLocation
- [ ] append
- [x] append
- [ ] appendLeft
- [ ] appendRight
- [ ] clone
Expand All @@ -35,14 +35,14 @@ Implement all APIs of [magic-string](https://www.npmjs.com/package/magic-string)
- [ ] move
- [ ] overwrite
- [ ] update
- [ ] prepend
- [x] prepend
- [ ] prependLeft
- [ ] prependRight
- [ ] remove
- [ ] lastChar
- [ ] lastLine
- [ ] slice
- [ ] toString
- [x] toString
- [ ] isEmpty
- [ ] length
- [ ] trimLines
Expand Down
53 changes: 48 additions & 5 deletions crates/enhanced-magic-string/src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ struct UniqueSource {
pub content: CharString,
}

pub struct AddSourceOptions {
pub separator: char,
pub filename: Option<String>,
}

pub struct Bundle {
separator: char,
intro: CharString,
Expand All @@ -44,8 +49,22 @@ impl Bundle {
}
}

pub fn add_source(&mut self, source: MagicString) -> Result<()> {
if let Some(filename) = &source.filename {
pub fn add_source(
&mut self,
mut source: MagicString,
opts: Option<AddSourceOptions>,
) -> Result<()> {
let filename = opts
.as_ref()
.and_then(|opts| opts.filename.as_ref())
.or(source.filename.as_ref());
let separator = opts
.as_ref()
.map(|opts| opts.separator)
.unwrap_or(self.separator);
source.separator = separator;

if let Some(filename) = filename {
if let Some(index) = self.unique_source_index_by_filename.get(filename) {
let unique_source = &self.unique_sources[*index];

Expand Down Expand Up @@ -86,7 +105,13 @@ impl Bundle {

self.sources.iter().enumerate().for_each(|(i, source)| {
if i > 0 {
mappings.advance(&self.separator.into());
// replace \0 to empty string
let separator = if source.separator == '\0' {
CharString::new("")
} else {
CharString::from(source.separator)
};
mappings.advance(&separator);
}

let source_index: isize = if let Some(filename) = &source.filename {
Expand Down Expand Up @@ -221,6 +246,24 @@ impl Bundle {

self.sources.get(*source_index)
}

pub fn append(&mut self, str: &str, opts: Option<AddSourceOptions>) {
self
.add_source(
MagicString::new(str, None),
opts.or(Some(AddSourceOptions {
separator: '\0',
filename: None,
})),
)
.unwrap();
}

pub fn prepend(&mut self, str: &str) {
let mut new_intro = CharString::new(str);
new_intro.append(&self.intro);
self.intro = new_intro;
}
}

impl ToString for Bundle {
Expand All @@ -230,8 +273,8 @@ impl ToString for Bundle {
.iter()
.enumerate()
.map(|(i, source)| {
let separator = if i > 0 {
self.separator.to_string()
let separator = if i > 0 && source.separator != '\0' {
source.separator.to_string()
} else {
"".to_string()
};
Expand Down
15 changes: 15 additions & 0 deletions crates/enhanced-magic-string/src/magic_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub struct MagicString {
pub ignore_list: Vec<CharString>,
source_map_chain: Vec<String>,
collapsed_sourcemap: RefCell<Option<SourceMap>>,

pub separator: char,
}

impl MagicString {
Expand All @@ -64,6 +66,7 @@ impl MagicString {
ignore_list: options.ignore_list,
source_map_chain: options.source_map_chain,
collapsed_sourcemap: RefCell::new(None),
separator: '\n',
};

magic_string
Expand Down Expand Up @@ -97,6 +100,18 @@ impl MagicString {

Some(collapsed_sourcemap)
}

pub fn prepend(&mut self, str: &str) {
let mut new_intro = CharString::new(str);
new_intro.append(&self.intro);
self.intro = new_intro;
}

pub fn append(&mut self, str: &str) {
let mut new_outro = self.outro.clone();
new_outro.append_str(str);
self.outro = new_outro;
}
}

impl ToString for MagicString {
Expand Down
8 changes: 8 additions & 0 deletions crates/enhanced-magic-string/src/utils/char_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ impl CharString {

Some(self.chars.remove(index))
}

pub fn append_str(&mut self, other: &str) {
self.chars.extend(other.chars());
}

pub fn append(&mut self, other: &CharString) {
self.chars.extend(other.chars.iter());
}
}

impl From<&str> for CharString {
Expand Down
9 changes: 6 additions & 3 deletions crates/enhanced-magic-string/tests/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,15 @@ fn bundle() {
}),
);
let mut bundle = enhanced_magic_string::bundle::Bundle::new(BundleOptions::default());
bundle.add_source(magic_string).unwrap();
bundle.add_source(magic_string, None).unwrap();

modules.into_iter().for_each(|module| {
bundle.add_source(module).unwrap();
bundle.add_source(module, None).unwrap();
});

bundle.prepend("/* header */\n");
bundle.append("//# sourceMappingURL=output.js.map", None);

let code = bundle.to_string();
let map = bundle
.generate_map(SourceMapOptions {
Expand All @@ -69,6 +72,6 @@ fn bundle() {
assert_eq!(code, expected);

let expected_map = std::fs::read_to_string(dir.join("output.js.map")).unwrap();
assert_eq!(map_str, expected_map);
assert_eq!(map_str, expected_map.replace(";\"}", "\"}"));
});
}
4 changes: 4 additions & 0 deletions crates/enhanced-magic-string/tests/bundle.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ test('expected magic-string result', (t) => {
bundle.addSource(new MagicString(module.content, { filename: module.path }));
});


bundle.prepend("/* header */\n");
bundle.append("//# sourceMappingURL=output.js.map");

const output = bundle.toString();
const map = bundle.generateMap({ includeContent: true });

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* header */
import { 模块1 } from "./modules/m-1";
import { 模块2 } from "./modules/m-2";

Expand All @@ -16,4 +17,4 @@ export function 模块2() {
console.log('在模块2中');
console.log('也在模块2中');
return "模块2";
}
}//# sourceMappingURL=output.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* header */
import { m1 } from "./modules/m-1";
import { m2 } from "./modules/m-2";

Expand All @@ -16,4 +17,4 @@ export function m2() {
console.log('in m2');
console.log('in m2 too');
return "m2";
}
}//# sourceMappingURL=output.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 924688a

Please sign in to comment.