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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use std::{
    collections::BTreeMap,
    env,
    io::{Read, Write},
    path::{Path, PathBuf},
};

use clap::ValueEnum;
use fs_err as fs;
use ignore::WalkBuilder;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use regex::Regex;
use serde::{Deserialize, Serialize};
use strum::{Display, EnumIter};

use crate::{
    constants::{CLIENT_BLOCK, OPTION_BACKGROUND_DEFAULT, OPTION_DB_DEFAULT, SERVER_BLOCK},
    env_vars,
};

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

const LIB_NAME_PLACEHOLDER: &str = "{{LibName}}";

#[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>>,
    /// List of option tags
    pub options: Option<Vec<OptionsList>>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum OptionsList {
    #[serde(rename = "db")]
    DB,
    #[serde(rename = "bg")]
    Background,
    #[serde(rename = "assets")]
    Assets,
}

#[derive(
    Debug, Clone, Deserialize, Serialize, EnumIter, Display, Default, PartialEq, Eq, ValueEnum,
)]
pub enum DBOption {
    #[default]
    #[serde(rename = "sqlite")]
    Sqlite,
    #[serde(rename = "pg")]
    Postgres,
}

#[derive(
    Debug, Clone, Deserialize, Serialize, EnumIter, Display, Default, PartialEq, Eq, ValueEnum,
)]
pub enum BackgroundOption {
    #[default]
    #[serde(rename = "async")]
    Async,
    #[serde(rename = "queue")]
    Queue,
    #[serde(rename = "blocking")]
    Blocking,
}

#[derive(
    Debug, Clone, Deserialize, Serialize, EnumIter, Display, Default, PartialEq, Eq, ValueEnum,
)]
pub enum AssetsOption {
    #[default]
    #[serde(rename = "none")]
    None,
    #[serde(rename = "client")]
    Clientside,
    #[serde(rename = "server")]
    Serverside,
}
#[derive(Debug, Clone, Default)]
/// Represents internal placeholders to be replaced.
pub struct ArgsPlaceholder {
    pub lib_name: String,
    pub db: Option<DBOption>,
    pub bg: Option<BackgroundOption>,
    pub assets: Option<AssetsOption>,
    pub template: Option<String>,
}

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

impl ArgsPlaceholder {
    /// replace strings placeholder with cli arguments.
    /// For example, replace any string that contains {{`LibName`}} with the
    /// given lib name.
    #[must_use]
    pub fn replace_placeholders(&self, content: &str) -> String {
        content.replace(LIB_NAME_PLACEHOLDER, &self.lib_name)
    }
}

/// 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) -> crate::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(env_vars::CI_MODE).is_ok() {
                    continue;
                }

                let replace = match rule.kind {
                    TemplateRuleKind::LibName | TemplateRuleKind::JwtToken => {
                        rule.kind.get_val(args)
                    }
                    TemplateRuleKind::Any(_) => args.replace_placeholders(&rule.kind.get_val(args)),
                };
                content = rule.pattern.replace_all(&content, replace).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
    }
}

/// adjust config file based on selected options
///
/// # Errors
///
/// This function will return an error if operation fails
pub fn adjust_options(
    copy_template_to: &Path,
    assetopt: &AssetsOption,
    dbopt: &DBOption,
    bgopt: &BackgroundOption,
) -> crate::Result<()> {
    let dev_file = copy_template_to.join("config/development.yaml");
    let mut development = String::new();
    fs::File::open(&dev_file)?.read_to_string(&mut development)?;

    let test_file = copy_template_to.join("config/test.yaml");
    let mut test = String::new();
    fs::File::open(&test_file)?.read_to_string(&mut test)?;

    adjust_options_for_content(&mut development, &mut test, assetopt, dbopt, bgopt);

    let mut modified_file = fs::File::create(&dev_file)?;
    modified_file.write_all(development.as_bytes())?;

    let mut modified_file = fs::File::create(&test_file)?;
    modified_file.write_all(test.as_bytes())?;
    Ok(())
}

fn adjust_options_for_content(
    development: &mut String,
    test: &mut String,
    assetopt: &AssetsOption,
    dbopt: &DBOption,
    bgopt: &BackgroundOption,
) {
    // in-file default is everything commented
    if assetopt == &AssetsOption::Serverside {
        *development = enable_block(&*development, SERVER_BLOCK);
    } else if assetopt == &AssetsOption::Clientside {
        *development = enable_block(&*development, CLIENT_BLOCK);
    }

    // in-file default is postgres
    if dbopt == &DBOption::Sqlite {
        *development = development.replace(OPTION_DB_DEFAULT, "sqlite://loco_app.sqlite?mode=rwc");
        *test = test.replace(OPTION_DB_DEFAULT, "sqlite://loco_app.sqlite?mode=rwc");
    }

    // in-file default is queue
    if bgopt == &BackgroundOption::Async {
        *development = development.replace(OPTION_BACKGROUND_DEFAULT, "mode: BackgroundAsync");
    } else if bgopt == &BackgroundOption::Blocking {
        *development = development.replace(OPTION_BACKGROUND_DEFAULT, "mode: ForegroundBlocking");
    }
}
fn enable_block(content: &str, block: &str) -> String {
    let mut in_server_block = false;
    let mut processed = Vec::new();
    let lines = content.lines();
    for line in lines {
        if line.contains(&format!("{block}-start")) {
            in_server_block = true;
            continue;
        }
        if line.contains(&format!("{block}-end")) {
            in_server_block = false;
            continue;
        }
        if in_server_block {
            processed.push(line.replace("    #", "   "));
        } else {
            processed.push(line.to_string());
        }
    }
    processed.join("\n")
}

#[cfg(test)]
mod tests {

    use insta::{assert_debug_snapshot, assert_snapshot, with_settings};
    use tree_fs;
    const DEVELOPMENT_YAML: &str = include_str!("fixtures/development.yaml");
    const TEST_YAML: &str = include_str!("fixtures/test.yaml");

    use super::*;

    #[test]
    fn can_adjust_options_in_configuration() {
        let mut development = DEVELOPMENT_YAML.to_string();
        let mut test = TEST_YAML.to_string();
        adjust_options_for_content(
            &mut development,
            &mut test,
            &AssetsOption::Clientside,
            &DBOption::Sqlite,
            &BackgroundOption::Async,
        );
        assert_snapshot!(development);
        assert_snapshot!(test);
    }

    #[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
        - path: any.yaml
          content: | 
            database:
                uri: {{ get_env(name="DATABASE_URL", default="postgres://loco:loco@localhost:5432/loco_app") }}
        "#;
        let tree_res = tree_fs::from_yaml_str(yaml_content).unwrap();

        let template = Template {
            description: "test template".to_string(),
            options: None,
            rules: Some(vec![
                TemplateRule {
                    pattern: Regex::new("loco_starter").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,
                },
                TemplateRule {
                    pattern: Regex::new("postgres://loco:loco@localhost:5432/loco_app").unwrap(),
                    kind: TemplateRuleKind::Any(
                        "postgres://loco:loco@localhost:5432/{{LibName}}_test".to_string(),
                    ),
                    file_patterns: None,
                    skip_in_ci: None,
                },
            ]),
        };

        let args = ArgsPlaceholder {
            lib_name: "lib_name_changed".to_string(),
            ..Default::default()
        };
        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")));
            assert_debug_snapshot!(fs::read_to_string(tree_res.join("any.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(),
            options: None,
            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(),
            ..Default::default()
        };
        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")));
    }
}