Skip to content

Commit

Permalink
feat: Support multiline replace
Browse files Browse the repository at this point in the history
  • Loading branch information
attakei committed Mar 20, 2024
1 parent 6df20bc commit d9d8a69
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,14 @@ pub fn update(base_config: &Config, new_version: &Version) -> Result<()> {
replace: "current_version = \\\"{{new_version}}\\\"".to_string(),
});
for f in files {
let search_text = Tera::one_off(&f.search, &ctx, true).unwrap();
let replace_text = Tera::one_off(&f.replace, &ctx, true).unwrap();
let search_text = Tera::one_off(&f.search, &ctx, true)
.unwrap()
.trim_start()
.to_string();
let replace_text = Tera::one_off(&f.replace, &ctx, true)
.unwrap()
.trim_start()
.to_string();
let new_text = build_updates(read_to_string(&f.path).unwrap(), search_text, replace_text);
let mut out = File::create(&f.path)?;
let _ = out.write(new_text.as_bytes());
Expand All @@ -41,11 +47,22 @@ fn make_context(current_version: &Version, new_version: &Version) -> Context {
}

fn build_updates(input: String, seach_text: String, replace_text: String) -> String {
let lines = seach_text.split("\n").count();
println!("{}", lines);
let mut buf: Vec<String> = Vec::new();
let mut output: Vec<String> = Vec::new();
for line in input.split("\n") {
if line == seach_text {
if buf.len() == lines {
output.push(buf.pop().unwrap());
}
buf.push(line.to_string());
if buf.join("\n") == seach_text {
output.push(replace_text.to_string());
} else {
buf.clear();
}
}
if buf.len() > 0 {
for line in buf {
output.push(line.to_string());
}
}
Expand Down
30 changes: 30 additions & 0 deletions tests/test_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,33 @@ def test_valid_conf__single_line(cmd, tmp_path: Path): # noqa: D103
proc = cmd("0.2.0")
assert proc.returncode == 0
assert data_txt.read_text() == "0.2.0"


def test_valid_conf__multi_line(cmd, tmp_path: Path): # noqa: D103
conf_text = textwrap.dedent(
'''\
current_version = "0.0.0"
[[files]]
path = "data.txt"
search = """
Target
======
"""
replace = """
Target
======
v {{new_version}}
-----------------
"""
'''
)
(tmp_path / ".age.toml").write_text(conf_text)
data_txt = tmp_path / "data.txt"
data_txt.write_text("Target\n======\n")

proc = cmd("0.2.0")
print(proc.stdout)
assert proc.returncode == 0
assert len(data_txt.read_text().split("\n")) == 6

0 comments on commit d9d8a69

Please sign in to comment.