yerba 0.5.1

YAML Editing and Refactoring with Better Accuracy
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
pub mod apply;
pub mod blank_lines;
pub mod check;
pub mod delete;
pub mod directives;
pub mod get;
pub mod init;
pub mod insert;
pub mod location;
pub mod mate;
pub mod move_item;
pub mod move_key;
pub mod quote_style;
pub mod remove;
pub mod rename;
pub mod schema;
pub mod selectors;
pub mod set;
pub mod sort;
pub mod sort_keys;
pub mod unique;
pub mod version;

use std::fs;
use std::process;

use clap::Subcommand;

pub(crate) fn is_github_actions() -> bool {
  std::env::var("GITHUB_ACTIONS").is_ok()
}

pub(crate) mod color {
  pub const GREEN: &str = "\x1b[32m";
  pub const RED: &str = "\x1b[31m";
  pub const YELLOW: &str = "\x1b[33m";
  pub const DIM: &str = "\x1b[2m";
  pub const BOLD: &str = "\x1b[1m";
  pub const RESET: &str = "\x1b[0m";
}

// Compile-time ANSI macros for use in concat!() / clap attributes (used in main.rs)
#[allow(unused_macros)]
macro_rules! h {
  () => {
    "\x1b[1;32m"
  };
} // header (bold green)
#[allow(unused_macros)]
macro_rules! b {
  () => {
    "\x1b[1m"
  };
} // bold
#[allow(unused_macros)]
macro_rules! c {
  () => {
    "\x1b[36m"
  };
} // cyan
#[allow(unused_macros)]
macro_rules! d {
  () => {
    "\x1b[2m"
  };
} // dim
#[allow(unused_macros)]
macro_rules! r {
  () => {
    "\x1b[0m"
  };
} // reset
#[allow(unused_imports)]
pub(crate) use {b, c, d, h, r};

pub(crate) fn colorize_examples(input: &str) -> String {
  colorize_help(&format!("Examples:\n{}", input.trim()))
}

pub(crate) fn colorize_help(input: &str) -> String {
  use color::*;

  let mut output = String::new();

  for line in input.lines() {
    let trimmed = line.trim();

    if trimmed.is_empty() {
      output.push('\n');
      continue;
    }

    if trimmed.ends_with(':') && !trimmed.contains(' ') {
      output.push_str(&format!("{GREEN}{BOLD}{trimmed}{RESET}\n"));
      continue;
    }

    if trimmed.starts_with("yerba ") {
      let mut parts = trimmed.splitn(3, ' ');

      match (parts.next(), parts.next(), parts.next()) {
        (Some(cmd), Some(sub), Some(rest)) => {
          output.push_str(&format!("  {BOLD}{cmd}{RESET} \x1b[36m{sub}{RESET} {rest}\n"));
        }

        (Some(cmd), Some(sub), None) => {
          output.push_str(&format!("  {BOLD}{cmd}{RESET} \x1b[36m{sub}{RESET}\n"));
        }

        _ => {
          output.push_str(&format!("  {trimmed}\n"));
        }
      }

      continue;
    }

    let mut columns: Vec<&str> = Vec::new();
    let mut rest = trimmed;

    while !rest.is_empty() {
      let column_end = rest.find("  ").unwrap_or(rest.len());
      let column = rest[..column_end].trim();

      if !column.is_empty() {
        columns.push(column);
      }

      if column_end >= rest.len() {
        break;
      }

      rest = rest[column_end..].trim_start();
    }

    if columns.len() == 3 {
      output.push_str(&format!("  \x1b[36m{:<20}{RESET} {:<21} {DIM}{}{RESET}\n", columns[0], columns[1], columns[2]));
    } else if columns.len() == 2 {
      output.push_str(&format!("  \x1b[36m{:<20}{RESET} {}\n", columns[0], columns[1]));
    } else {
      output.push_str(&format!("  {trimmed}\n"));
    }
  }

  output.trim_end().to_string()
}

#[derive(Subcommand)]
pub enum Command {
  Get(get::Args),
  Set(set::Args),
  Insert(insert::Args),
  Rename(rename::Args),
  Delete(delete::Args),
  Remove(remove::Args),
  Move(move_item::Args),
  MoveKey(move_key::Args),
  SortKeys(sort_keys::Args),
  Sort(sort::Args),
  QuoteStyle(quote_style::Args),
  BlankLines(blank_lines::Args),
  Directives(directives::Args),
  Unique(unique::Args),
  Location(location::Args),
  Schema(schema::Args),
  Selectors(selectors::Args),
  #[command(about = "Create a new Yerbafile in the current directory")]
  Init,
  Apply(apply::Args),
  Check(check::Args),
  #[command(about = "Print the yerba version")]
  Version,
  #[command(about = "\u{1f9c9}")]
  Mate,
}

impl Command {
  pub fn run(self) {
    match self {
      Command::Get(args) => args.run(),
      Command::Set(args) => args.run(),
      Command::Insert(args) => args.run(),
      Command::Rename(args) => args.run(),
      Command::Delete(args) => args.run(),
      Command::Remove(args) => args.run(),
      Command::Move(args) => args.run(),
      Command::MoveKey(args) => args.run(),
      Command::SortKeys(args) => args.run(),
      Command::Sort(args) => args.run(),
      Command::QuoteStyle(args) => args.run(),
      Command::BlankLines(args) => args.run(),
      Command::Directives(args) => args.run(),
      Command::Unique(args) => args.run(),
      Command::Location(args) => args.run(),
      Command::Schema(args) => args.run(),
      Command::Selectors(args) => args.run(),
      Command::Init => init::run(),
      Command::Apply(args) => args.run(),
      Command::Check(args) => args.run(),
      Command::Version => version::run(),
      Command::Mate => mate::run(),
    }
  }
}

pub(crate) fn run_yerbafile(write: bool, files: Vec<String>) {
  use color::*;

  let yerbafile_path = yerba::Yerbafile::find().unwrap_or_else(|| {
    eprintln!("{RED}No Yerbafile found.{RESET} Run {BOLD}yerba init{RESET} to create one.");
    process::exit(1);
  });

  let yerbafile = yerba::Yerbafile::load(&yerbafile_path).unwrap_or_else(|error| {
    eprintln!("{RED}Error loading {}:{RESET} {}", yerbafile_path.display(), error);
    process::exit(1);
  });

  eprintln!("🧉 {BOLD}Using{RESET} {}", yerbafile_path.display());

  let results = if files.is_empty() {
    yerbafile.apply(write)
  } else {
    files.iter().flat_map(|file| yerbafile.apply_file(file, write)).collect()
  };

  let mut has_changes = false;
  let mut has_errors = false;

  let github = is_github_actions();

  for result in &results {
    if let Some(error) = &result.error {
      eprintln!("  {RED}error:{RESET} {} {DIM}—{RESET} {}", result.file, error);

      if github {
        use yerba::error::GitHubAnnotations;

        for annotation in error.github_annotations(&result.file) {
          eprintln!("{}", annotation);
        }
      }

      has_errors = true;
    } else if result.changed {
      if write {
        eprintln!("  {GREEN}updated:{RESET} {}", result.file);
      } else {
        eprintln!("  {YELLOW}would change:{RESET} {}", result.file);

        if github {
          eprintln!("::error file={}::File does not match Yerbafile rules", result.file);
        }
      }

      has_changes = true;
    }
  }

  if !has_changes && !has_errors {
    eprintln!("\n{BOLD}{GREEN}All files match the rules.{RESET}");
  }

  if !write && has_changes {
    process::exit(1);
  }

  if has_errors {
    process::exit(1);
  }
}

pub(crate) fn resolve_move_indexes(
  document: &yerba::Document,
  path: &str,
  item: &str,
  before: Option<String>,
  after: Option<String>,
  to: Option<usize>,
  resolve: impl Fn(&yerba::Document, &str, &str) -> Result<usize, yerba::YerbaError>,
) -> (usize, usize) {
  use color::*;

  let from_index = resolve(document, path, item).unwrap_or_else(|error| {
    eprintln!("{RED}Error:{RESET} {}", error);
    process::exit(1);
  });

  let to_index = if let Some(index) = to {
    index
  } else if let Some(target) = &before {
    let target_index = resolve(document, path, target).unwrap_or_else(|error| {
      eprintln!("{RED}Error:{RESET} {}", error);
      process::exit(1);
    });

    if from_index < target_index {
      target_index - 1
    } else {
      target_index
    }
  } else if let Some(target) = &after {
    let target_index = resolve(document, path, target).unwrap_or_else(|error| {
      eprintln!("{RED}Error:{RESET} {}", error);
      process::exit(1);
    });

    if from_index <= target_index {
      target_index
    } else {
      target_index + 1
    }
  } else {
    eprintln!("{RED}Error:{RESET} specify --before, --after, or --to");
    process::exit(1);
  };

  (from_index, to_index)
}

pub(crate) fn resolve_files(pattern: &str) -> Vec<String> {
  use color::*;

  if pattern.contains('*') || pattern.contains('?') || pattern.contains('[') {
    let paths: Vec<String> = glob::glob(pattern)
      .unwrap_or_else(|error| {
        eprintln!("{RED}Error:{RESET} invalid glob pattern '{}': {}", pattern, error);
        process::exit(1);
      })
      .filter_map(|entry| entry.ok())
      .map(|path| path.to_string_lossy().to_string())
      .collect();

    if paths.is_empty() {
      eprintln!("{RED}Error:{RESET} no files matched pattern: {}", pattern);
      process::exit(1);
    }

    paths
  } else {
    vec![pattern.to_string()]
  }
}

pub(crate) fn parse_file(file: &str) -> yerba::Document {
  use color::*;

  yerba::parse_file(file).unwrap_or_else(|error| {
    match &error {
      yerba::YerbaError::IoError(io_error) => match io_error.kind() {
        std::io::ErrorKind::NotFound => eprintln!("{RED}Error:{RESET} file not found: {}", file),
        std::io::ErrorKind::PermissionDenied => {
          eprintln!("{RED}Error:{RESET} permission denied: {}", file)
        }
        _ => eprintln!("{RED}Error:{RESET} reading {}: {}", file, io_error),
      },
      _ => eprintln!("{RED}Error:{RESET} parsing {}: {}", file, error),
    }

    process::exit(1);
  })
}

pub(crate) fn run_op(display_file: &str, document: &yerba::Document, result: Result<(), yerba::YerbaError>) {
  run_op_with_hint(display_file, document, result, None);
}

pub(crate) fn run_op_with_hint(display_file: &str, document: &yerba::Document, result: Result<(), yerba::YerbaError>, hint: Option<&str>) {
  use color::*;

  if let Err(error) = result {
    if let yerba::YerbaError::SelectorNotFound(selector) = &error {
      eprintln!("{RED}Error:{RESET} selector \"{selector}\" not found in {display_file}");

      show_similar_selectors(display_file, document, selector);
    } else {
      eprintln!("{RED}Error:{RESET} {}", error);
    }

    if let Some(hint) = hint {
      if matches!(error, yerba::YerbaError::SelectorNotFound(_)) {
        eprintln!();
        eprintln!("  {DIM}Hint: {hint}{RESET}");
      }
    }

    process::exit(1);
  }
}

pub(crate) fn show_similar_selectors(file: &str, document: &yerba::Document, invalid_path: &str) {
  use color::*;
  use yerba::didyoumean::didyoumean_ranked;

  let selectors = document.selectors();

  if selectors.is_empty() {
    return;
  }

  let query = invalid_path.split_whitespace().next().unwrap_or(invalid_path);
  let threshold = query.len() / 2 + 3;
  let close = didyoumean_ranked(query, &selectors, threshold);

  eprintln!();

  if close.is_empty() {
    eprintln!("  {BOLD}Available selectors in {file}:{RESET}");

    for selector in selectors.iter().take(10) {
      eprintln!("    {DIM}{selector}{RESET}");
    }

    if selectors.len() > 10 {
      eprintln!("    {DIM}... and {} more{RESET}", selectors.len() - 10);
    }
  } else if close.len() == 1 {
    eprintln!("  {BOLD}Did you mean this selector?{RESET} {}", close[0]);
  } else {
    eprintln!("  {BOLD}Did you mean one of these selectors?{RESET}");

    for selector in close.iter().take(5) {
      eprintln!("    {selector}");
    }
  }

  eprintln!();
  eprintln!("  {BOLD}To see all valid selectors, run:{RESET}");
  eprintln!("    yerba selectors \"{file}\"{RESET}");
}

pub(crate) fn output(file: &str, document: &yerba::Document, dry_run: bool) {
  if dry_run {
    println!("--- {}", file);
    print!("{}", document);
  } else {
    fs::write(file, document.to_string()).unwrap_or_else(|error| {
      eprintln!("Error writing {}: {}", file, error);
      process::exit(1);
    });
  }
}