diff options
| author | Federico Igne <git@federicoigne.com> | 2022-05-26 23:46:59 +0100 |
|---|---|---|
| committer | Federico Igne <git@federicoigne.com> | 2022-05-27 00:48:45 +0100 |
| commit | ff6551e0d1124ed54fb02c464b07c6c1aeda6f16 (patch) | |
| tree | ffabc16643def7ed4765720d530de81b18ed8ae6 | |
| parent | 284dd70386059bde248404dfc0b379eec700c9b5 (diff) | |
| download | pangler-ff6551e0d1124ed54fb02c464b07c6c1aeda6f16.tar.gz pangler-ff6551e0d1124ed54fb02c464b07c6c1aeda6f16.zip | |
refactor: block indentation
| -rw-r--r-- | src/main.rs | 34 |
1 files changed, 25 insertions, 9 deletions
diff --git a/src/main.rs b/src/main.rs index 14e3f22..c28914f 100644 --- a/src/main.rs +++ b/src/main.rs | |||
| @@ -24,6 +24,26 @@ fn write_to_file<P: AsRef<Path>>(path: P, content: &str) -> std::io::Result<()> | |||
| 24 | Ok(()) | 24 | Ok(()) |
| 25 | } | 25 | } |
| 26 | 26 | ||
| 27 | /* Indent block of code */ | ||
| 28 | fn indent<'a>(input: Cow<'a,str>, indent: usize) -> Cow<'a,str> { | ||
| 29 | if indent > 0 { | ||
| 30 | let prefix = format!("{:indent$}", ""); | ||
| 31 | let mut output = String::with_capacity(input.len() + indent*input.lines().count()); | ||
| 32 | input.lines().enumerate().for_each(|(i,line)| { | ||
| 33 | if i > 0 { | ||
| 34 | output.push('\n'); | ||
| 35 | } | ||
| 36 | if !line.is_empty() { | ||
| 37 | output.push_str(&prefix); | ||
| 38 | output.push_str(line); | ||
| 39 | } | ||
| 40 | }); | ||
| 41 | Cow::Owned(output) | ||
| 42 | } else { | ||
| 43 | input | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 27 | /* | 47 | /* |
| 28 | * Here are some notes on the following function | 48 | * Here are some notes on the following function |
| 29 | * | 49 | * |
| @@ -68,15 +88,11 @@ fn build(blocks: &Blocks) { | |||
| 68 | // We can use it to recursively build blocks of code until no more substitutions are | 88 | // We can use it to recursively build blocks of code until no more substitutions are |
| 69 | // necessary (i.e., `replace_all` returns a `Borrowed`). | 89 | // necessary (i.e., `replace_all` returns a `Borrowed`). |
| 70 | while let Cow::Owned(step) = MACRO.replace_all(&code, |caps: &Captures| { | 90 | while let Cow::Owned(step) = MACRO.replace_all(&code, |caps: &Captures| { |
| 71 | let indent = caps[1].len(); | 91 | indent( |
| 72 | blocks.get(&caps[2]) | 92 | blocks.get(&caps[2]).expect("Block not present").clone(), |
| 73 | .expect("Block not present") | 93 | caps[1].len() |
| 74 | .lines() | 94 | ) |
| 75 | .map(|l| format!("{:indent$}{}", "", l) ) | 95 | }) { |
| 76 | .collect::<Vec<_>>() | ||
| 77 | .join("\n") | ||
| 78 | } | ||
| 79 | ) { | ||
| 80 | code = Cow::from(step); | 96 | code = Cow::from(step); |
| 81 | } | 97 | } |
| 82 | write_to_file(k, &code).expect("Unable to write to file"); | 98 | write_to_file(k, &code).expect("Unable to write to file"); |
