1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
use std::{
    collections::BTreeMap,
    env, fs,
    io::{Read, Write},
    path::PathBuf,
};

use ignore::WalkBuilder;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use regex::Regex;
use serde::{Deserialize, Serialize};

// Name of generator template that should be existing in each starter folder
const GENERATOR_FILE_NAME: &str = "generator.yaml";

#[derive(Debug, Clone, Deserialize, Serialize)]
/// Represents the configuration of a template generator.
pub struct Template {
    /// Description of the template.
    pub description: String,
    /// List of rules for placeholder replacement in the generator.
    pub rules: Option<Vec<TemplateRule>>,
}

#[derive(Debug, Clone)]
/// Represents internal placeholders to be replaced.
pub struct ArgsPlaceholder {
    pub lib_name: String,
}

#[derive(Debug, Clone, Serialize)]
/// Enum representing different kinds of template rules.
pub enum TemplateRuleKind {
    LibName,
    JwtToken,
    Any(String),
}

/// Deserialize [`TemplateRuleKind`] for supporting any string replacements
impl<'de> Deserialize<'de> for TemplateRuleKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value: serde_yaml::Value = Deserialize::deserialize(deserializer)?;

        match &value {
            serde_yaml::Value::String(s) => match s.as_str() {
                "LibName" => Ok(Self::LibName),
                "JwtToken" => Ok(Self::JwtToken),
                _ => Ok(Self::Any(s.clone())),
            },
            _ => Err(serde::de::Error::custom("Invalid TemplateRuleKind value")),
        }
    }
}

impl TemplateRuleKind {
    #[must_use]
    /// Get the value from the rule Kind.
    pub fn get_val(&self, args: &ArgsPlaceholder) -> String {
        match self {
            Self::LibName => args.lib_name.to_string(),
            Self::JwtToken => thread_rng()
                .sample_iter(&Alphanumeric)
                .take(20)
                .map(char::from)
                .collect(),
            Self::Any(s) => s.to_string(),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
/// Represents a placeholder replacement rule.
pub struct TemplateRule {
    #[serde(with = "serde_regex")]
    /// Pattern to search in the file
    pub pattern: Regex,
    /// The replacement kind
    pub kind: TemplateRuleKind,
    #[serde(with = "serde_regex", skip_serializing)]
    /// List of template generator rule for replacement
    pub file_patterns: Option<Vec<Regex>>,
    pub skip_in_ci: Option<bool>,
}

/// Collects template configurations from files named [`GENERATOR_FILE_NAME`]
/// within the root level directories in the provided path. This function
/// gracefully handles any issues related to the existence or format of the
/// generator files, allowing the code to skip problematic starter templates
/// without returning an error. This approach is designed to avoid negatively
/// impacting users due to faulty template configurations.
///
/// # Errors
/// The code should returns an error only when could get folder collections.
pub fn collect_templates(path: &std::path::PathBuf) -> eyre::Result<BTreeMap<String, Template>> {
    tracing::debug!(
        path = path.display().to_string(),
        "collecting starters template"
    );

    let entries = fs::read_dir(path)?;

    let mut templates = BTreeMap::new();

    // Iterate over the entries and filter out directories
    for entry in entries {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            if let Some(starter_folder) = entry.file_name().to_str() {
                let generator_file_path = std::path::Path::new(path)
                    .join(starter_folder)
                    .join(GENERATOR_FILE_NAME);

                let outer_span = tracing::info_span!(
                    "generator",
                    file = generator_file_path.display().to_string()
                );
                let _enter = outer_span.enter();

                tracing::debug!("parsing generator file");

                if !generator_file_path.exists() {
                    tracing::debug!("generator file not found");
                    continue;
                }

                let rdr = match std::fs::File::open(&generator_file_path) {
                    Ok(rdr) => rdr,
                    Err(e) => {
                        tracing::debug!(error = e.to_string(), "could not open generator file");
                        continue;
                    }
                };

                match serde_yaml::from_reader(&rdr) {
                    Ok(t) => templates.insert(starter_folder.to_string(), t),
                    Err(e) => {
                        tracing::debug!(error = e.to_string(), "invalid format");
                        continue;
                    }
                };
            }
        }
    }

    Ok(templates)
}

impl Template {
    /// Generates files based on the given template by recursively applying
    /// template rules to files within the specified path.
    ///
    /// # Description
    /// This method utilizes a parallel file walker to traverse the directory
    /// structure starting from the specified root path (`from`). For each
    /// file encountered, it checks whether the template rules should be
    /// applied based on file patterns. If the rules are applicable and an error
    /// occurs during the application, the error is logged, and the walker
    /// is instructed to quit processing further files in the current
    /// subtree.
    pub fn generate(&self, from: &PathBuf, args: &ArgsPlaceholder) {
        let walker = WalkBuilder::new(from).build();

        let collect_file_patterns = self.get_all_file_patterns();
        for entry in walker.flatten() {
            let path = entry.path();

            if !path.starts_with(from.join("target"))
                && Self::should_run_file(path, Some(&collect_file_patterns))
            {
                if let Err(e) = self.apply_rules(path, args) {
                    tracing::info!(
                        error = e.to_string(),
                        path = path.display().to_string(),
                        "could not run rules placeholder replacement on the file"
                    );
                }
            }
        }

        if let Err(err) = fs::remove_file(from.join(GENERATOR_FILE_NAME)) {
            tracing::debug!(error = err.to_string(), "could not delete generator file");
        }
    }

    fn get_all_file_patterns(&self) -> Vec<Regex> {
        self.rules.as_ref().map_or_else(Vec::new, |rules| {
            rules
                .iter()
                .flat_map(|rule| rule.file_patterns.as_deref().unwrap_or_default())
                .cloned()
                .collect()
        })
    }

    /// Applies the specified rules to the content of a file, updating the file
    /// in-place with the modified content.
    ///
    /// # Description
    /// This method reads the content of the file specified by `file`, applies
    /// each rule from the template to the content, and saves the modified
    /// content back to the same file. The rules are only applied if
    /// the file passes the filtering conditions based on file patterns
    /// associated with each rule. If any rule results in modifications to
    /// the content, the file is updated; otherwise, it remains unchanged.
    fn apply_rules(&self, file: &std::path::Path, args: &ArgsPlaceholder) -> std::io::Result<()> {
        let mut content = String::new();
        fs::File::open(file)?.read_to_string(&mut content)?;

        let mut is_changed = false;
        for rule in &self.rules.clone().unwrap_or_default() {
            if Self::should_run_file(file, rule.file_patterns.as_ref())
                && rule.pattern.is_match(&content)
            {
                if rule.skip_in_ci.unwrap_or(false) && env::var("LOCO_CI_MODE").is_ok() {
                    continue;
                }

                content = rule
                    .pattern
                    .replace_all(&content, rule.kind.get_val(args))
                    .to_string();
                is_changed = true;
            }
        }

        if is_changed {
            let mut modified_file = fs::File::create(file)?;
            modified_file.write_all(content.as_bytes())?;
        }

        Ok(())
    }

    /// Determines whether the template rules should be applied to the given
    /// file path based on a list of regex patterns.
    fn should_run_file(path: &std::path::Path, patterns: Option<&Vec<Regex>>) -> bool {
        if path.is_file() {
            let Some(patterns) = patterns else {
                return true;
            };
            if patterns.is_empty() {
                return true;
            }

            for pattern in patterns {
                if pattern.is_match(&path.display().to_string()) {
                    return true;
                }
            }
        }

        false
    }
}

#[cfg(test)]
mod tests {

    use insta::{assert_debug_snapshot, with_settings};
    use tree_fs;

    use super::*;

    #[test]
    fn can_collect_templates() {
        let yaml_content = r"
        files:
        - path: template-a/generator.yaml
          content: |
            description: template_a
            file_patterns: 
              - rs
              - toml
            rules:
              - pattern: test
                kind: LibName
                file_patterns:
                  - rs
        - path: template-b/generator.yaml
          content: |
            description: template_b
            file_patterns: []
        - path: template-c/generator.yaml
          content: |
            invalid-yaml
        ";

        let tree_res = tree_fs::from_yaml_str(yaml_content).unwrap();

        assert_debug_snapshot!(collect_templates(&tree_res));
    }

    #[allow(clippy::trivial_regex)]
    #[test]
    fn can_generate() {
        let yaml_content = r#"
        files:
        - path: Cargo.toml
          content: | 
            name = "loco_starter"
        - path: test.yaml
          content: | 
            secret = MY_SECRET
        "#;
        let tree_res = tree_fs::from_yaml_str(yaml_content).unwrap();

        let template = Template {
            description: "test template".to_string(),
            rules: Some(vec![
                TemplateRule {
                    pattern: Regex::new("loco.*").unwrap(),
                    kind: TemplateRuleKind::LibName,
                    file_patterns: None,
                    skip_in_ci: None,
                },
                TemplateRule {
                    pattern: Regex::new("MY_SECRET").unwrap(),
                    kind: TemplateRuleKind::JwtToken,
                    file_patterns: None,
                    skip_in_ci: None,
                },
            ]),
        };

        let args = ArgsPlaceholder {
            lib_name: "lib_name_changed".to_string(),
        };
        template.generate(&tree_res, &args);

        assert_debug_snapshot!(fs::read_to_string(tree_res.join("Cargo.toml")));

        with_settings!({
            filters => vec![
            (r"([A-Za-z0-9]){20}", "RAND_SECRET"),
            ]
        }, {
            assert_debug_snapshot!(fs::read_to_string(tree_res.join("test.yaml")));

        });
    }

    #[allow(clippy::trivial_regex)]
    #[test]
    fn can_generate_skip_files() {
        let yaml_content = r#"
        files:
        - path: Cargo.toml
          content: | 
            name = "skip_lib_name_changes"
        - path: test.yaml
          content: | 
            secret = skip_jwt_token
        "#;
        let tree_res = tree_fs::from_yaml_str(yaml_content).unwrap();

        let template = Template {
            description: "test template".to_string(),
            rules: Some(vec![
                TemplateRule {
                    pattern: Regex::new("skip_lib.*").unwrap(),
                    kind: TemplateRuleKind::LibName,
                    file_patterns: None,
                    skip_in_ci: None,
                },
                TemplateRule {
                    pattern: Regex::new("skip_jwt_token").unwrap(),
                    kind: TemplateRuleKind::JwtToken,
                    file_patterns: Some(vec![Regex::new("^*.json").unwrap()]),
                    skip_in_ci: None,
                },
            ]),
        };

        let args = ArgsPlaceholder {
            lib_name: "lib_name_changed".to_string(),
        };
        template.generate(&tree_res, &args);

        assert_debug_snapshot!(fs::read_to_string(tree_res.join("Cargo.toml")));
        assert_debug_snapshot!(fs::read_to_string(tree_res.join("test.yaml")));
    }
}