yerba 0.1.2

YAML Editing and Refactoring with Better Accuracy
Documentation
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use rayon::prelude::*;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::{Document, QuoteStyle, YerbaError};

#[derive(Debug, Deserialize)]
pub struct Yerbafile {
  #[serde(default)]
  pub rules: Vec<Rule>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Rule {
  pub files: String,
  #[serde(default)]
  pub path: Option<String>,
  pub pipeline: Vec<PipelineStep>,
}

#[derive(Debug, Clone)]
pub enum PipelineStep {
  Get(GetConfig),
  SortKeys(SortKeysConfig),
  QuoteStyle(QuoteStyleConfig),
  Set(SetConfig),
  Insert(InsertConfig),
  Delete(DeleteConfig),
  Rename(RenameConfig),
  Remove(RemoveConfig),
  BlankLines(BlankLinesConfig),
  Sort(SortConfig),
}

#[derive(Debug, Clone, Deserialize)]
pub struct SortConfig {
  #[serde(default)]
  pub path: Option<String>,
  #[serde(default)]
  pub by: Option<String>,
  #[serde(default)]
  pub case_sensitive: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BlankLinesConfig {
  #[serde(default)]
  pub path: Option<String>,
  pub count: usize,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GetConfig {
  pub path: String,
  #[serde(rename = "as")]
  pub as_name: String,
  #[serde(default)]
  pub file: Option<String>,
}

#[derive(Debug, Clone)]
pub enum Variable {
  Single(String),
  List(Vec<String>),
}

#[derive(Debug, Clone, Deserialize)]
pub struct RenameConfig {
  pub from: String,
  pub to: String,
  #[serde(default)]
  pub condition: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RemoveConfig {
  pub path: String,
  pub value: String,
  #[serde(default)]
  pub condition: Option<String>,
}

impl<'de> Deserialize<'de> for PipelineStep {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    let mapping = serde_yaml::Mapping::deserialize(deserializer)?;

    if let Some(value) = mapping.get(serde_yaml::Value::String("get".to_string())) {
      let config: GetConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::Get(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("sort_keys".to_string())) {
      let config: SortKeysConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::SortKeys(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("quote_style".to_string())) {
      let config: QuoteStyleConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::QuoteStyle(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("set".to_string())) {
      let config: SetConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::Set(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("insert".to_string())) {
      let config: InsertConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::Insert(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("delete".to_string())) {
      let config: DeleteConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::Delete(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("rename".to_string())) {
      let config: RenameConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::Rename(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("remove".to_string())) {
      let config: RemoveConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::Remove(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("blank_lines".to_string())) {
      let config: BlankLinesConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::BlankLines(config));
    }

    if let Some(value) = mapping.get(serde_yaml::Value::String("sort".to_string())) {
      let config: SortConfig = serde_yaml::from_value(value.clone()).map_err(serde::de::Error::custom)?;
      return Ok(PipelineStep::Sort(config));
    }

    Err(serde::de::Error::custom(
      "unknown pipeline step: expected get, sort_keys, quote_style, set, insert, delete, rename, remove, blank_lines, or sort",
    ))
  }
}

#[derive(Debug, Clone, Deserialize)]
pub struct SortKeysConfig {
  #[serde(default)]
  pub path: Option<String>,
  pub order: Vec<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct QuoteStyleConfig {
  #[serde(default = "default_key_style")]
  pub key_style: String,
  pub value_style: String,
  #[serde(default)]
  pub path: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SetConfig {
  pub path: String,
  pub value: String,
  #[serde(default)]
  pub condition: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct InsertConfig {
  pub path: String,
  pub value: String,
  #[serde(default)]
  pub condition: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeleteConfig {
  pub path: String,
  #[serde(default)]
  pub condition: Option<String>,
}

fn default_key_style() -> String {
  "plain".to_string()
}

#[derive(Debug)]
pub struct RuleResult {
  pub file: String,
  pub changed: bool,
  pub error: Option<String>,
}

impl Yerbafile {
  pub fn load(path: impl AsRef<Path>) -> Result<Self, YerbaError> {
    let content = fs::read_to_string(path.as_ref())?;
    let yerbafile: Yerbafile =
      serde_yaml::from_str(&content).map_err(|error| YerbaError::ParseError(format!("{}", error)))?;
    Ok(yerbafile)
  }

  pub fn find() -> Option<PathBuf> {
    let candidates = ["Yerbafile", "Yerbafile.yml", "Yerbafile.yaml", ".yerbafile"];

    let mut directory = std::env::current_dir().ok()?;

    loop {
      for candidate in &candidates {
        let path = directory.join(candidate);

        if path.exists() {
          return Some(path);
        }
      }

      if !directory.pop() {
        return None;
      }
    }
  }

  pub fn sort_order_for(&self, file_path: &str, dot_path: &str) -> Option<Vec<String>> {
    for rule in &self.rules {
      let sort_keys_config = rule.pipeline.iter().find_map(|step| match step {
        PipelineStep::SortKeys(config) => Some(config),
        _ => None,
      });

      if let Some(config) = sort_keys_config {
        let full_path = resolve_step_path(rule.path.as_deref(), config.path.as_deref());
        let normalized = full_path.trim_end_matches("[]").trim_end_matches('.');

        if normalized != dot_path && !normalized.is_empty() && !dot_path.is_empty() {
          continue;
        }

        if let Ok(pattern) = glob::Pattern::new(&rule.files) {
          if pattern.matches(file_path) || pattern.matches_path(Path::new(file_path)) {
            return Some(config.order.clone());
          }
        }
      }
    }

    None
  }

  pub fn apply(&self, write: bool) -> Vec<RuleResult> {
    let mut results = Vec::new();

    for rule in &self.rules {
      let files = match glob::glob(&rule.files) {
        Ok(paths) => paths.filter_map(|entry| entry.ok()).collect::<Vec<_>>(),

        Err(error) => {
          results.push(RuleResult {
            file: rule.files.clone(),
            changed: false,
            error: Some(format!("invalid glob: {}", error)),
          });

          continue;
        }
      };

      let file_strings: Vec<String> = files.iter().map(|path| path.to_string_lossy().to_string()).collect();

      let mut has_validation_error = false;

      for step in &rule.pipeline {
        if let PipelineStep::SortKeys(config) = step {
          let full_path = resolve_step_path(rule.path.as_deref(), config.path.as_deref());
          let key_order: Vec<&str> = config.order.iter().map(|key| key.as_str()).collect();

          let validation_results: Vec<RuleResult> = file_strings
            .par_iter()
            .filter_map(|file| {
              let document = match Document::parse_file(file) {
                Ok(document) => document,
                Err(error) => {
                  return Some(RuleResult {
                    file: file.clone(),
                    changed: false,
                    error: Some(format!("{}", error)),
                  });
                }
              };

              if let Err(error) = document.validate_sort_keys(&full_path, &key_order) {
                Some(RuleResult {
                  file: file.clone(),
                  changed: false,
                  error: Some(format!("{}", error)),
                })
              } else {
                None
              }
            })
            .collect();

          if !validation_results.is_empty() {
            has_validation_error = true;
            results.extend(validation_results);
          }
        }
      }

      if has_validation_error {
        continue;
      }

      let file_results: Vec<RuleResult> = file_strings
        .par_iter()
        .map(|file| self.apply_pipeline_to_file(rule, file, write))
        .collect();

      results.extend(file_results);
    }

    results
  }

  fn apply_pipeline_to_file(&self, rule: &Rule, file: &str, write: bool) -> RuleResult {
    let mut document = match Document::parse_file(file) {
      Ok(document) => document,
      Err(error) => {
        return RuleResult {
          file: file.to_string(),
          changed: false,
          error: Some(format!("{}", error)),
        }
      }
    };

    let original = document.to_string();
    let base_path = rule.path.as_deref();
    let mut variables: HashMap<String, Variable> = HashMap::new();

    for step in &rule.pipeline {
      if let Err(error) = execute_step(&mut document, step, base_path, &mut variables) {
        return RuleResult {
          file: file.to_string(),
          changed: false,
          error: Some(format!("{}", error)),
        };
      }
    }

    let new_content = document.to_string();
    let changed = new_content != original;

    if changed && write {
      if let Err(error) = fs::write(file, &new_content) {
        return RuleResult {
          file: file.to_string(),
          changed,
          error: Some(format!("{}", error)),
        };
      }
    }

    RuleResult {
      file: file.to_string(),
      changed,
      error: None,
    }
  }
}

fn execute_step(
  document: &mut Document,
  step: &PipelineStep,
  base_path: Option<&str>,
  variables: &mut HashMap<String, Variable>,
) -> Result<(), YerbaError> {
  match step {
    PipelineStep::Get(config) => {
      let full_path = resolve_step_path(base_path, Some(&config.path));

      if let Some(file_pattern) = &config.file {
        let mut all_values = Vec::new();

        let files =
          glob::glob(file_pattern).map_err(|error| YerbaError::ParseError(format!("invalid glob: {}", error)))?;

        for entry in files.flatten() {
          let external_document = Document::parse_file(&entry)?;
          all_values.extend(external_document.get_all(&config.path));
        }

        if all_values.len() == 1 && !config.path.contains('[') {
          variables.insert(config.as_name.clone(), Variable::Single(all_values.remove(0)));
        } else {
          variables.insert(config.as_name.clone(), Variable::List(all_values));
        }
      } else if config.path.contains('[') {
        let values = document.get_all(&full_path);

        variables.insert(config.as_name.clone(), Variable::List(values));
      } else {
        let value = document
          .get(&full_path)
          .ok_or_else(|| YerbaError::PathNotFound(full_path.clone()))?;
        variables.insert(config.as_name.clone(), Variable::Single(value));
      }

      Ok(())
    }

    PipelineStep::QuoteStyle(config) => {
      let dot_path = config.path.as_deref();

      let key_style = config.key_style.parse::<QuoteStyle>().map_err(YerbaError::ParseError)?;

      let value_style = config
        .value_style
        .parse::<QuoteStyle>()
        .map_err(YerbaError::ParseError)?;

      document.enforce_key_style(&key_style, dot_path)?;
      document.enforce_quotes_at(&value_style, dot_path)?;

      Ok(())
    }

    PipelineStep::SortKeys(config) => {
      let full_path = resolve_step_path(base_path, config.path.as_deref());
      let key_order: Vec<&str> = config.order.iter().map(|key| key.as_str()).collect();

      document.sort_keys(&full_path, &key_order)
    }

    PipelineStep::Set(config) => {
      let full_path = resolve_step_path(base_path, Some(&config.path));
      let resolved_value = resolve_template(&config.value, document, base_path, variables)?;

      if let Some(condition) = &config.condition {
        let resolved_condition = resolve_template(condition, document, base_path, variables)?;
        let parent_path = full_path.rsplit_once('.').map(|(parent, _)| parent).unwrap_or("");

        if !document.evaluate_condition(parent_path, &resolved_condition) {
          return Ok(());
        }
      }

      document.set(&full_path, &resolved_value)
    }

    PipelineStep::Insert(config) => {
      let full_path = resolve_step_path(base_path, Some(&config.path));
      let resolved_value = resolve_template(&config.value, document, base_path, variables)?;

      if let Some(condition) = &config.condition {
        let resolved_condition = resolve_template(condition, document, base_path, variables)?;
        let parent_path = full_path.rsplit_once('.').map(|(parent, _)| parent).unwrap_or("");

        if !document.evaluate_condition(parent_path, &resolved_condition) {
          return Ok(());
        }
      }

      document.insert_into(&full_path, &resolved_value, crate::InsertPosition::Last)
    }

    PipelineStep::Delete(config) => {
      let full_path = resolve_step_path(base_path, Some(&config.path));

      if let Some(condition) = &config.condition {
        let resolved_condition = resolve_template(condition, document, base_path, variables)?;
        let parent_path = full_path.rsplit_once('.').map(|(parent, _)| parent).unwrap_or("");

        if !document.evaluate_condition(parent_path, &resolved_condition) {
          return Ok(());
        }
      }

      document.delete(&full_path)
    }

    PipelineStep::Rename(config) => {
      let full_path = resolve_step_path(base_path, Some(&config.from));

      if let Some(condition) = &config.condition {
        let resolved_condition = resolve_template(condition, document, base_path, variables)?;
        let parent_path = full_path.rsplit_once('.').map(|(parent, _)| parent).unwrap_or("");

        if !document.evaluate_condition(parent_path, &resolved_condition) {
          return Ok(());
        }
      }

      document.rename(&full_path, &config.to)
    }

    PipelineStep::Remove(config) => {
      let full_path = resolve_step_path(base_path, Some(&config.path));
      let resolved_value = resolve_template(&config.value, document, base_path, variables)?;

      if let Some(condition) = &config.condition {
        let resolved_condition = resolve_template(condition, document, base_path, variables)?;
        let parent_path = full_path.rsplit_once('.').map(|(parent, _)| parent).unwrap_or("");

        if !document.evaluate_condition(parent_path, &resolved_condition) {
          return Ok(());
        }
      }

      document.remove(&full_path, &resolved_value)
    }

    PipelineStep::BlankLines(config) => {
      let full_path = resolve_step_path(base_path, config.path.as_deref());

      document.enforce_blank_lines(&full_path, config.count)
    }

    PipelineStep::Sort(config) => {
      let full_path = resolve_step_path(base_path, config.path.as_deref());
      let sort_fields = config
        .by
        .as_deref()
        .map(crate::SortField::parse_list)
        .unwrap_or_default();

      document.sort_items(&full_path, &sort_fields, config.case_sensitive)
    }
  }
}

pub fn resolve_template(
  template: &str,
  document: &Document,
  base_path: Option<&str>,
  variables: &HashMap<String, Variable>,
) -> Result<String, YerbaError> {
  if !template.contains("${") {
    return Ok(template.to_string());
  }

  let mut result = String::new();
  let mut rest = template;

  while let Some(start) = rest.find("${") {
    result.push_str(&rest[..start]);

    let after_dollar = &rest[start + 2..];

    let end = after_dollar
      .find('}')
      .ok_or_else(|| YerbaError::ParseError("unclosed ${ in template".to_string()))?;

    let reference = &after_dollar[..end];

    let resolved = if let Some(variable) = variables.get(reference) {
      match variable {
        Variable::Single(value) => value.clone(),
        Variable::List(values) => values.join(", "),
      }
    } else {
      let full_path = resolve_step_path(base_path, Some(reference));

      document
        .get(&full_path)
        .ok_or_else(|| YerbaError::ReferenceNotFound(reference.to_string()))?
    };

    result.push_str(&resolved);
    rest = &after_dollar[end + 1..];
  }

  result.push_str(rest);

  Ok(result)
}

fn resolve_step_path(base_path: Option<&str>, step_path: Option<&str>) -> String {
  let base = base_path.unwrap_or("");
  let step = step_path.unwrap_or("");

  match (base.is_empty(), step.is_empty()) {
    (true, true) => String::new(),
    (true, false) => step.to_string(),
    (false, true) => base.to_string(),
    (false, false) => format!("{}.{}", base, step),
  }
}