Skip to content

Commit

Permalink
Merge pull request #61 from refcell/refcell/optimize-license-templating
Browse files Browse the repository at this point in the history
fix(license): Licensing
  • Loading branch information
refcell authored Oct 27, 2023
2 parents 33db32a + 1de9b66 commit 8c178ec
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
["package"]
name = "amble"
description = "First class, scalable rust project generator with batteries included."
version = "0.1.28"
version = "0.1.29"
edition = "2021"
license = "MIT"
authors = ["refcell"]
Expand Down Expand Up @@ -36,6 +36,7 @@ gitignores = "2.3"
prettytable = "0.10"
image = "0.24"
lice = "0.1"
aho-corasick = "1.1.2"

[dev-dependencies]
tempfile = "3.8"
Expand Down
33 changes: 30 additions & 3 deletions src/license.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use aho_corasick::AhoCorasick;
use anyhow::Result;
use chrono::Datelike;
use ptree::TreeBuilder;
Expand All @@ -10,9 +11,26 @@ pub(crate) const MIT_LICENSE: &str = "MIT License\n\nCopyright (c) [year] [fulln

/// Helper function to build an MIT License with imputed values.
pub(crate) fn build_mit_license() -> String {
MIT_LICENSE
.replace("[year]", &chrono::Utc::now().year().to_string())
.replace("[fullname]", &crate::root::get_current_username(&None))
impute_license(MIT_LICENSE)
}

/// Impute templated license strs with dynamic values.
pub(crate) fn impute_license(haystack: &str) -> String {
let patterns = &["<year>", "[year]", "<fullname>", "[fullname]"];
let ac = AhoCorasick::builder()
.ascii_case_insensitive(true)
.build(patterns)
.unwrap();
let mut result = String::new();
ac.replace_all_with(haystack, &mut result, |mat, _, dst| {
match mat.pattern().as_usize() {
0 | 1 => dst.push_str(&chrono::Utc::now().year().to_string()),
2 | 3 => dst.push_str(&crate::root::get_current_username(&None)),
_ => unreachable!(),
}
true
});
result
}

/// Creates a new license file in the given directory.
Expand Down Expand Up @@ -99,6 +117,15 @@ mod tests {
);
}

#[test]
fn test_impute_license() {
let haystack = r#"MIT License <year> <fullname>"#;
let license = haystack
.replacen("<year>", &chrono::Utc::now().year().to_string(), 1)
.replacen("<fullname>", &crate::root::get_current_username(&None), 1);
assert_eq!(license, impute_license(haystack));
}

#[test]
fn test_create_license() {
let dir = tempdir().unwrap();
Expand Down

0 comments on commit 8c178ec

Please sign in to comment.