wini_cli/init/
rename.rs

1use {
2    super::{err::InitError, git::first_commit, RepoSummary},
3    std::{fs, io, path::Path},
4};
5
6fn replace_in_file<P: AsRef<Path>>(
7    file_path: P,
8    target: &str,
9    replacement: &str,
10) -> io::Result<()> {
11    let content = std::fs::read_to_string(&file_path)?;
12
13    let new_content = content.replace(target, replacement);
14
15    std::fs::write(&file_path, new_content)?;
16
17    Ok(())
18}
19
20fn replace_in_directory<P: AsRef<Path>>(
21    dir_path: P,
22    target: &str,
23    replacement: &str,
24) -> io::Result<()> {
25    for entry in fs::read_dir(dir_path)? {
26        let entry = entry?;
27        let path = entry.path();
28
29        if path.is_file() {
30            replace_in_file(&path, target, replacement)?;
31        } else if path.is_dir() {
32            replace_in_directory(&path, target, replacement)?;
33        }
34    }
35
36    Ok(())
37}
38
39pub fn rename_fields(repo_summary: &RepoSummary) -> Result<(), InitError> {
40    for (from, to) in [
41        ("HASH_TO_RESOLVE", repo_summary.last_commit_hash.as_str()),
42        (
43            "URL_TO_RESOLVE",
44            repo_summary
45                .remote_url
46                .as_ref()
47                .map_or("NONE", |e| e.as_str()),
48        ),
49        ("BRANCH_NAME_TO_RESOLVE", repo_summary.branch.as_str()),
50        ("PROJECT_NAME_TO_RESOLVE", repo_summary.dir.as_str()),
51    ] {
52        replace_in_directory(&repo_summary.dir, from, to).map_err(InitError::IoError)?;
53    }
54
55    first_commit(&repo_summary.dir).map_err(InitError::OtherGitError)?;
56
57    Ok(())
58}