Skip to main content

yaml_rt_cli/
lib.rs

1//! Command-line querying and editing operations for the `yaml-rt` binary.
2//!
3//! The binary searches YAML documents with `JSONPath`, applies JSON Pointer
4//! operations, and executes transactional YAML or JSON patch documents while
5//! retaining unrelated presentation. File targets can also be directories,
6//! which are searched recursively for YAML files; an omitted target searches
7//! the current directory, while `-` reads standard input. [`run`] is public so
8//! integrations can supply their own argument and I/O streams.
9
10use std::cmp::Ordering as CmpOrdering;
11use std::collections::HashSet;
12use std::ffi::{OsStr, OsString};
13use std::fs::{self, File, OpenOptions};
14use std::io::{self, Read, Write};
15use std::path::{Path, PathBuf};
16use std::sync::atomic::{AtomicU64, Ordering};
17
18use clap::{Args, CommandFactory, Parser, Subcommand, error::ErrorKind};
19use yaml_rt_core::{
20    Diagnostic, DiagnosticColor, DiagnosticKind, JsonPointer, ResourceLimits, Span, YamlDoc,
21    YamlError, YamlFragment, YamlPatch,
22};
23use yaml_rt_rfc9535::{JsonPath, QueryMatches};
24use yaml_rt_schema::{Error as SchemaError, Schema, generate_schema};
25
26mod query;
27
28use query::{query_matches, run_query};
29
30const FAILURE: i32 = 1;
31const USAGE: i32 = 2;
32static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
33
34/// Runs the command-line application against supplied streams.
35pub fn run<I, T>(
36    args: I,
37    stdin: &mut dyn Read,
38    stdout: &mut dyn Write,
39    stderr: &mut dyn Write,
40) -> i32
41where
42    I: IntoIterator<Item = T>,
43    T: Into<OsString> + Clone,
44{
45    run_with_options(args, stdin, stdout, stderr, RunOptions::default())
46}
47
48/// Controls presentation for [`run_with_options`].
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50pub struct RunOptions {
51    /// Whether source-aware YAML diagnostics use ANSI colors.
52    pub color: bool,
53}
54
55/// Runs the command-line application with explicit presentation options.
56pub fn run_with_options<I, T>(
57    args: I,
58    stdin: &mut dyn Read,
59    stdout: &mut dyn Write,
60    stderr: &mut dyn Write,
61    options: RunOptions,
62) -> i32
63where
64    I: IntoIterator<Item = T>,
65    T: Into<OsString> + Clone,
66{
67    let cli = match Cli::try_parse_from(args) {
68        Ok(cli) => cli,
69        Err(error) => {
70            let display_only = matches!(
71                error.kind(),
72                ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
73            );
74            let write_result = if display_only {
75                write!(stdout, "{error}")
76            } else {
77                write!(stderr, "{error}")
78            };
79            if write_result.is_err() {
80                return FAILURE;
81            }
82            return if display_only { 0 } else { USAGE };
83        }
84    };
85    if let Err(message) = cli.operation.validate() {
86        let error = Cli::command().error(ErrorKind::ArgumentConflict, message);
87        if write!(stderr, "{error}").is_err() {
88            return FAILURE;
89        }
90        return USAGE;
91    }
92    match execute(&cli.operation, stdin, stdout, options) {
93        Ok(()) | Err(RunError::BrokenPipe) => 0,
94        Err(RunError::Usage(message)) => {
95            let error = Cli::command().error(ErrorKind::ArgumentConflict, message);
96            if write!(stderr, "{error}").is_err() {
97                return FAILURE;
98            }
99            USAGE
100        }
101        Err(RunError::Batch {
102            diagnostics,
103            summary,
104        }) => {
105            for diagnostic in diagnostics {
106                let _ = writeln!(stderr, "yaml-rt: {diagnostic}");
107            }
108            let _ = writeln!(stderr, "yaml-rt: {summary}");
109            FAILURE
110        }
111        Err(RunError::Message(message)) => {
112            let _ = writeln!(stderr, "yaml-rt: {message}");
113            FAILURE
114        }
115        Err(RunError::Diagnostic(diagnostic)) => {
116            let _ = writeln!(stderr, "{diagnostic}");
117            FAILURE
118        }
119    }
120}
121
122#[derive(Parser)]
123#[command(
124    name = "yaml-rt",
125    version,
126    about = "Query and edit YAML while preserving presentation",
127    subcommand_required = true,
128    arg_required_else_help = true
129)]
130struct Cli {
131    #[command(subcommand)]
132    operation: Operation,
133}
134
135#[derive(Subcommand)]
136enum Operation {
137    /// Validate YAML syntax without producing output.
138    #[command(visible_alias = "v")]
139    Validate(ValidateArgs),
140    /// Generate a permissive JSON Schema from one YAML document.
141    Schema(SchemaArgs),
142    /// Search a YAML document with RFC 9535 `JSONPath`.
143    #[command(visible_alias = "q")]
144    Query(QueryArgs),
145    /// Print a selected YAML node.
146    #[command(visible_alias = "g")]
147    Get(ReadArgs),
148    /// Add or replace a value.
149    #[command(visible_alias = "a")]
150    Add(ValueMutationArgs),
151    /// Remove an existing value.
152    #[command(visible_alias = "d")]
153    Remove(MutationArgs),
154    /// Replace an existing value.
155    #[command(visible_alias = "r")]
156    Replace(ValueMutationArgs),
157    /// Rename one or more mapping keys.
158    #[command(visible_alias = "k")]
159    RenameKey(RenameKeyArgs),
160    /// Move an existing value.
161    #[command(visible_alias = "m")]
162    Move(FromMutationArgs),
163    /// Copy an existing value.
164    #[command(visible_alias = "c")]
165    Copy(FromMutationArgs),
166    /// Test semantic equality at a path.
167    #[command(visible_alias = "t")]
168    Test(ValueArgs),
169    /// Apply a transactional YAML or JSON patch document.
170    #[command(visible_alias = "p")]
171    Patch(PatchArgs),
172}
173
174#[derive(Args)]
175struct ValidateArgs {
176    /// Input YAML file or directory; defaults to the current directory. Use - for stdin.
177    #[arg(value_name = "FILE")]
178    file: Option<PathBuf>,
179    /// Validate each YAML document against a JSON Schema file.
180    #[arg(short, long, value_name = "FILE")]
181    schema: Option<PathBuf>,
182}
183
184#[derive(Args)]
185struct SchemaArgs {
186    /// One YAML input file. Use - for stdin.
187    #[arg(value_name = "FILE")]
188    file: PathBuf,
189    #[command(flatten)]
190    output: OutputArgs,
191}
192
193#[derive(Args)]
194struct TargetArgs {
195    /// Input YAML file or directory; defaults to the current directory. Use - for stdin.
196    #[arg(value_name = "FILE")]
197    file: Option<PathBuf>,
198    /// Zero-based YAML document index.
199    #[arg(long, value_name = "INDEX")]
200    doc: Option<usize>,
201}
202
203#[derive(Args)]
204struct PathArgs {
205    /// JSON Pointer, or the input file when `--query` is used.
206    #[arg(
207        value_name = "PATH_OR_FILE",
208        allow_hyphen_values = true,
209        required_unless_present = "query"
210    )]
211    path_or_file: Option<String>,
212    /// Select operation targets with an RFC 9535 `JSONPath` query.
213    #[arg(long, value_name = "QUERY")]
214    query: Option<String>,
215    #[command(flatten)]
216    target: TargetArgs,
217}
218
219#[derive(Args)]
220struct FromPathArgs {
221    #[arg(value_name = "FROM", allow_hyphen_values = true)]
222    from: String,
223    #[arg(value_name = "PATH", allow_hyphen_values = true)]
224    path: String,
225    #[command(flatten)]
226    target: TargetArgs,
227}
228
229#[derive(Args)]
230struct OutputArgs {
231    /// Write output to a file.
232    #[arg(short, long, value_name = "FILE")]
233    output: Option<PathBuf>,
234}
235
236#[derive(Args)]
237struct MutationOutputArgs {
238    #[command(flatten)]
239    output: OutputArgs,
240    /// Atomically replace the input file.
241    #[arg(short, long, conflicts_with = "output")]
242    in_place: bool,
243}
244
245#[derive(Args)]
246#[group(required = true, multiple = false)]
247struct ValueSourceArgs {
248    /// Complete YAML node.
249    #[arg(long, value_name = "YAML", allow_hyphen_values = true)]
250    value: Option<String>,
251    /// Read the YAML node from a file.
252    #[arg(long, value_name = "FILE")]
253    value_file: Option<PathBuf>,
254}
255
256#[derive(Args)]
257#[group(required = true, multiple = false)]
258struct PatchSourceArgs {
259    /// YAML or JSON patch document.
260    #[arg(long, value_name = "YAML", allow_hyphen_values = true)]
261    patch: Option<String>,
262    /// Read the YAML or JSON patch document from a file.
263    #[arg(long, value_name = "FILE")]
264    patch_file: Option<PathBuf>,
265}
266
267#[derive(Args)]
268struct ReadArgs {
269    #[command(flatten)]
270    path: PathArgs,
271    #[command(flatten)]
272    output: OutputArgs,
273}
274
275#[derive(Args)]
276struct QueryArgs {
277    /// RFC 9535 `JSONPath` query.
278    #[arg(value_name = "QUERY")]
279    query: String,
280    #[command(flatten)]
281    target: TargetArgs,
282    #[command(flatten)]
283    output: OutputArgs,
284}
285
286#[derive(Args)]
287struct MutationArgs {
288    #[command(flatten)]
289    path: PathArgs,
290    #[command(flatten)]
291    output: MutationOutputArgs,
292}
293
294#[derive(Args)]
295struct FromMutationArgs {
296    #[command(flatten)]
297    path: FromPathArgs,
298    #[command(flatten)]
299    output: MutationOutputArgs,
300}
301
302#[derive(Args)]
303struct ValueArgs {
304    #[command(flatten)]
305    path: PathArgs,
306    #[command(flatten)]
307    value: ValueSourceArgs,
308}
309
310#[derive(Args)]
311struct ValueMutationArgs {
312    #[command(flatten)]
313    value: ValueArgs,
314    #[command(flatten)]
315    output: MutationOutputArgs,
316}
317
318#[derive(Args)]
319struct RenameKeyArgs {
320    #[command(flatten)]
321    path: PathArgs,
322    /// Decoded destination key name.
323    #[arg(long, value_name = "KEY")]
324    to: String,
325    #[command(flatten)]
326    output: MutationOutputArgs,
327}
328
329#[derive(Args)]
330struct PatchArgs {
331    #[command(flatten)]
332    target: TargetArgs,
333    #[command(flatten)]
334    source: PatchSourceArgs,
335    #[command(flatten)]
336    output: MutationOutputArgs,
337}
338
339fn execute(
340    operation: &Operation,
341    stdin: &mut dyn Read,
342    stdout: &mut dyn Write,
343    options: RunOptions,
344) -> Result<(), RunError> {
345    if let Operation::Schema(args) = operation
346        && fs::symlink_metadata(&args.file).is_ok_and(|metadata| metadata.is_dir())
347    {
348        return Err(RunError::usage("schema generation requires one YAML file"));
349    }
350    let targets = resolve_targets(operation.input_path())?;
351    if matches!(targets, InputTargets::Batch { .. })
352        && operation
353            .mutation_output()
354            .is_some_and(|output| !output.in_place)
355    {
356        return Err(RunError::usage(
357            "directory targets require --in-place for mutations",
358        ));
359    }
360    let target_uses_stdin = matches!(targets, InputTargets::Stdin);
361    if matches!(operation, Operation::Patch(arguments) if arguments.source.patch_file.as_deref() == Some(Path::new("-")))
362        && target_uses_stdin
363    {
364        return Err(RunError::message(
365            "target YAML and --patch-file cannot both read stdin",
366        ));
367    }
368    let prepared = prepare_operation(operation, target_uses_stdin, stdin, options)?;
369    match targets {
370        InputTargets::Stdin => {
371            let input = read_stream(stdin, "stdin")?;
372            execute_one(operation, &prepared, None, input, stdout, false, options)
373        }
374        InputTargets::File(path) => {
375            let input = read_target(&path)?;
376            execute_one(
377                operation,
378                &prepared,
379                Some(&path),
380                input,
381                stdout,
382                false,
383                options,
384            )
385        }
386        InputTargets::Batch {
387            files,
388            discovery_failures,
389        } => execute_batch(
390            operation,
391            &prepared,
392            &files,
393            discovery_failures,
394            stdout,
395            options,
396        ),
397    }
398}
399
400fn execute_one(
401    operation: &Operation,
402    prepared: &PreparedOperation,
403    input_path: Option<&Path>,
404    input: String,
405    stdout: &mut dyn Write,
406    batch_capture: bool,
407    options: RunOptions,
408) -> Result<(), RunError> {
409    let source_name = input_path
410        .map(|path| path.display().to_string())
411        .unwrap_or_else(|| "<stdin>".to_owned());
412    let mut doc = YamlDoc::parse(&input)
413        .map_err(|error| RunError::yaml_diagnostic(error, &input, &source_name, options.color))?;
414    if let Operation::Validate(_) = operation {
415        if let Some(schema) = &prepared.schema {
416            for document in 0..doc.document_count() {
417                schema.validate(&doc, document).map_err(|error| {
418                    RunError::schema_diagnostic(error, &input, &source_name, options.color)
419                })?;
420            }
421        }
422        return Ok(());
423    }
424    if let Operation::Schema(args) = operation {
425        if doc.document_count() != 1 {
426            return Err(RunError::message(
427                "schema generation requires exactly one YAML document",
428            ));
429        }
430        let schema = generate_schema(&doc, 0).map_err(|error| {
431            RunError::schema_diagnostic(error, &input, &source_name, options.color)
432        })?;
433        let mut rendered = schema.to_pretty_string();
434        rendered.push('\n');
435        return write_result(
436            rendered.as_bytes(),
437            args.output.output.as_deref(),
438            input_path,
439            stdout,
440        );
441    }
442    let target = operation.target();
443    let document = select_document(&doc, target.doc)?;
444
445    if let Operation::Query(arguments) = operation {
446        let output = run_query(
447            &doc,
448            document,
449            prepared
450                .query
451                .as_ref()
452                .expect("query operation is prepared"),
453        )
454        .map_err(RunError::display)?;
455        return write_result(
456            output.as_bytes(),
457            if batch_capture {
458                None
459            } else {
460                arguments.output.output.as_deref()
461            },
462            input_path,
463            stdout,
464        );
465    }
466
467    if let Operation::Patch(arguments) = operation {
468        doc.apply_patch(
469            document,
470            prepared
471                .patch
472                .as_ref()
473                .expect("patch operation is prepared"),
474        )
475        .map_err(RunError::display)?;
476        return write_mutation(&doc, &arguments.output, input_path, stdout);
477    }
478
479    if operation.selection_query().is_some() {
480        let matches = query_matches(
481            &doc,
482            document,
483            prepared
484                .query
485                .as_ref()
486                .expect("query-targeted operation is prepared"),
487        )
488        .map_err(RunError::display)?;
489        let mut output = CommandOutput {
490            input_path,
491            stdout,
492            batch_capture,
493        };
494        return execute_query_targeted(
495            operation,
496            &mut doc,
497            document,
498            &matches,
499            prepared.value.as_ref(),
500            &mut output,
501        );
502    }
503
504    let path = prepared
505        .path
506        .as_ref()
507        .expect("pointer operation is prepared");
508    let from = prepared.from.as_ref();
509    match operation {
510        Operation::Validate(_) | Operation::Schema(_) => {
511            unreachable!("operation returned after parsing")
512        }
513        Operation::Query(_) => unreachable!("query returned before pointer operations"),
514        Operation::Get(arguments) => {
515            let node = doc
516                .resolve_pointer(document, path)
517                .map_err(RunError::display)?;
518            let output = doc.extract_node(node).map_err(|error| {
519                RunError::yaml_diagnostic(error, doc.as_source(), &source_name, options.color)
520            })?;
521            write_result(
522                output.as_bytes(),
523                if batch_capture {
524                    None
525                } else {
526                    arguments.output.output.as_deref()
527                },
528                input_path,
529                stdout,
530            )
531        }
532        Operation::Test(_) => {
533            let equal = doc
534                .test_at(
535                    document,
536                    path,
537                    prepared.value.as_ref().expect("Clap requires a value"),
538                )
539                .map_err(RunError::display)?;
540            if equal {
541                Ok(())
542            } else {
543                Err(RunError::message(format!(
544                    "test failed at {:?}: values are not semantically equal",
545                    path.as_str()
546                )))
547            }
548        }
549        Operation::Add(arguments) => {
550            doc.add_at(
551                document,
552                path,
553                prepared.value.as_ref().expect("Clap requires a value"),
554            )
555            .map_err(RunError::display)?;
556            write_mutation(&doc, &arguments.output, input_path, stdout)
557        }
558        Operation::Remove(arguments) => {
559            doc.remove_at(document, path).map_err(RunError::display)?;
560            write_mutation(&doc, &arguments.output, input_path, stdout)
561        }
562        Operation::Replace(arguments) => {
563            doc.replace_at(
564                document,
565                path,
566                prepared.value.as_ref().expect("Clap requires a value"),
567            )
568            .map_err(RunError::display)?;
569            write_mutation(&doc, &arguments.output, input_path, stdout)
570        }
571        Operation::RenameKey(arguments) => {
572            doc.rename_key_at(document, path, &arguments.to)
573                .map_err(RunError::display)?;
574            write_mutation(&doc, &arguments.output, input_path, stdout)
575        }
576        Operation::Move(arguments) => {
577            doc.move_at(document, from.expect("Clap requires from"), path)
578                .map_err(RunError::display)?;
579            write_mutation(&doc, &arguments.output, input_path, stdout)
580        }
581        Operation::Copy(arguments) => {
582            doc.copy_at(document, from.expect("Clap requires from"), path)
583                .map_err(RunError::display)?;
584            write_mutation(&doc, &arguments.output, input_path, stdout)
585        }
586        Operation::Patch(_) => unreachable!("patch returned before pointer operations"),
587    }
588}
589
590struct PreparedOperation {
591    path: Option<JsonPointer>,
592    from: Option<JsonPointer>,
593    query: Option<JsonPath>,
594    value: Option<YamlFragment>,
595    patch: Option<YamlPatch>,
596    schema: Option<Schema>,
597}
598
599fn prepare_operation(
600    operation: &Operation,
601    target_uses_stdin: bool,
602    stdin: &mut dyn Read,
603    options: RunOptions,
604) -> Result<PreparedOperation, RunError> {
605    let query = operation
606        .query_source()
607        .map(JsonPath::parse)
608        .transpose()
609        .map_err(RunError::display)?;
610    let path = if query.is_none()
611        && !matches!(
612            operation,
613            Operation::Patch(_) | Operation::Validate(_) | Operation::Schema(_)
614        ) {
615        Some(JsonPointer::parse(operation.path()).map_err(RunError::display)?)
616    } else {
617        None
618    };
619    let from = operation
620        .from()
621        .map(JsonPointer::parse)
622        .transpose()
623        .map_err(RunError::display)?;
624    let value = read_value(operation.value(), target_uses_stdin, stdin)?;
625    let patch = match operation {
626        Operation::Patch(arguments) => Some(read_patch(&arguments.source, stdin)?),
627        _ => None,
628    };
629    let schema = match operation {
630        Operation::Validate(args) => {
631            if let Some(path) = args.schema.as_deref() {
632                let source = read_path(path, "schema file")?;
633                Some(Schema::parse(&source, Some(path)).map_err(|error| {
634                    RunError::schema_diagnostic(
635                        error,
636                        &source,
637                        &path.display().to_string(),
638                        options.color,
639                    )
640                })?)
641            } else {
642                None
643            }
644        }
645        _ => None,
646    };
647    Ok(PreparedOperation {
648        path,
649        from,
650        query,
651        value,
652        patch,
653        schema,
654    })
655}
656
657enum InputTargets {
658    Stdin,
659    File(PathBuf),
660    Batch {
661        files: Vec<BatchTarget>,
662        discovery_failures: Vec<DiscoveryFailure>,
663    },
664}
665
666struct BatchTarget {
667    path: PathBuf,
668    relative: PathBuf,
669}
670
671struct DiscoveryFailure {
672    relative: PathBuf,
673    message: String,
674}
675
676fn resolve_targets(path: Option<&Path>) -> Result<InputTargets, RunError> {
677    let path = match path {
678        None => std::env::current_dir().map_err(|error| {
679            RunError::message(format!("cannot determine current directory: {error}"))
680        })?,
681        Some(path) if path == Path::new("-") => return Ok(InputTargets::Stdin),
682        Some(path) => path.to_owned(),
683    };
684    if fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.is_dir()) {
685        let (files, discovery_failures) = discover_yaml_files(&path);
686        Ok(InputTargets::Batch {
687            files,
688            discovery_failures,
689        })
690    } else {
691        Ok(InputTargets::File(path))
692    }
693}
694
695fn discover_yaml_files(root: &Path) -> (Vec<BatchTarget>, Vec<DiscoveryFailure>) {
696    let mut files = Vec::new();
697    let mut failures = Vec::new();
698    discover_directory(root, root, &mut files, &mut failures);
699    files.sort_by(|left, right| left.relative.cmp(&right.relative));
700    failures.sort_by(|left, right| left.relative.cmp(&right.relative));
701    (files, failures)
702}
703
704fn discover_directory(
705    root: &Path,
706    directory: &Path,
707    files: &mut Vec<BatchTarget>,
708    failures: &mut Vec<DiscoveryFailure>,
709) {
710    let entries = match fs::read_dir(directory) {
711        Ok(entries) => entries,
712        Err(error) => {
713            failures.push(DiscoveryFailure {
714                relative: relative_to(root, directory),
715                message: format!("cannot read directory: {error}"),
716            });
717            return;
718        }
719    };
720    let mut entries = entries
721        .filter_map(|entry| match entry {
722            Ok(entry) => Some(entry),
723            Err(error) => {
724                failures.push(DiscoveryFailure {
725                    relative: relative_to(root, directory),
726                    message: format!("cannot read directory entry: {error}"),
727                });
728                None
729            }
730        })
731        .collect::<Vec<_>>();
732    entries.sort_by_key(std::fs::DirEntry::file_name);
733    for entry in entries {
734        let path = entry.path();
735        let file_type = match entry.file_type() {
736            Ok(file_type) => file_type,
737            Err(error) => {
738                failures.push(DiscoveryFailure {
739                    relative: relative_to(root, &path),
740                    message: format!("cannot inspect path: {error}"),
741                });
742                continue;
743            }
744        };
745        if file_type.is_symlink() {
746            continue;
747        }
748        if file_type.is_dir() {
749            discover_directory(root, &path, files, failures);
750        } else if file_type.is_file() && has_yaml_extension(&path) {
751            files.push(BatchTarget {
752                relative: relative_to(root, &path),
753                path,
754            });
755        }
756    }
757}
758
759fn relative_to(root: &Path, path: &Path) -> PathBuf {
760    path.strip_prefix(root)
761        .ok()
762        .filter(|path| !path.as_os_str().is_empty())
763        .unwrap_or_else(|| Path::new("."))
764        .to_owned()
765}
766
767fn has_yaml_extension(path: &Path) -> bool {
768    path.extension()
769        .and_then(OsStr::to_str)
770        .is_some_and(|extension| {
771            extension.eq_ignore_ascii_case("yaml") || extension.eq_ignore_ascii_case("yml")
772        })
773}
774
775fn execute_batch(
776    operation: &Operation,
777    prepared: &PreparedOperation,
778    files: &[BatchTarget],
779    discovery_failures: Vec<DiscoveryFailure>,
780    stdout: &mut dyn Write,
781    options: RunOptions,
782) -> Result<(), RunError> {
783    if let Some(output) = operation.read_output()
784        && let Some(input) = files
785            .iter()
786            .find(|input| paths_equivalent(&input.path, output))
787    {
788        return Err(RunError::message(format!(
789            "--output must not name input file {}",
790            render_batch_path(&input.relative)
791        )));
792    }
793
794    let mut diagnostics = discovery_failures
795        .iter()
796        .map(|failure| {
797            format!(
798                "{}: {}",
799                render_batch_path(&failure.relative),
800                failure.message
801            )
802        })
803        .collect::<Vec<_>>();
804    let mut succeeded = 0;
805    let mut failed = 0;
806    let mut combined_output = Vec::new();
807    for input in files {
808        let source = match read_target(&input.path) {
809            Ok(source) => source,
810            Err(RunError::Message(message)) => {
811                diagnostics.push(format!("{}: {message}", render_batch_path(&input.relative)));
812                failed += 1;
813                continue;
814            }
815            Err(error) => return Err(error),
816        };
817        let mut result = Vec::new();
818        match execute_one(
819            operation,
820            prepared,
821            Some(&input.path),
822            source,
823            &mut result,
824            true,
825            options,
826        ) {
827            Ok(()) => {
828                succeeded += 1;
829                if operation.should_emit_batch_result(&result) {
830                    append_batch_result(&mut combined_output, &input.relative, &result);
831                }
832            }
833            Err(RunError::Message(message)) => {
834                diagnostics.push(format!("{}: {message}", render_batch_path(&input.relative)));
835                failed += 1;
836            }
837            Err(RunError::Diagnostic(diagnostic)) => {
838                diagnostics.push(diagnostic);
839                failed += 1;
840            }
841            Err(error) => return Err(error),
842        }
843    }
844
845    if operation.has_read_output() {
846        write_result(&combined_output, operation.read_output(), None, stdout)?;
847    }
848    if diagnostics.is_empty() {
849        Ok(())
850    } else {
851        Err(RunError::Batch {
852            diagnostics,
853            summary: format!(
854                "processed {} YAML files: {succeeded} succeeded, {failed} failed; {} traversal errors",
855                files.len(),
856                discovery_failures.len()
857            ),
858        })
859    }
860}
861
862fn append_batch_result(output: &mut Vec<u8>, path: &Path, result: &[u8]) {
863    if !output.is_empty() {
864        output.push(b'\n');
865    }
866    writeln!(output, "==> {} <==", render_batch_path(path)).expect("writing to a Vec cannot fail");
867    output.extend_from_slice(result);
868    if !result.is_empty() && !result.ends_with(b"\n") {
869        output.push(b'\n');
870    }
871}
872
873fn render_batch_path(path: &Path) -> String {
874    path.components()
875        .map(|component| component.as_os_str().to_string_lossy())
876        .collect::<Vec<_>>()
877        .join("/")
878}
879
880impl Operation {
881    fn validate(&self) -> Result<(), String> {
882        let path = match self {
883            Self::Get(args) => Some(&args.path),
884            Self::Add(args) | Self::Replace(args) => Some(&args.value.path),
885            Self::RenameKey(args) => Some(&args.path),
886            Self::Remove(args) => Some(&args.path),
887            Self::Test(args) => Some(&args.path),
888            _ => None,
889        };
890        if let Some(path) = path {
891            path.validate()?;
892        }
893        Ok(())
894    }
895
896    fn target(&self) -> &TargetArgs {
897        match self {
898            Self::Validate(_) | Self::Schema(_) => {
899                unreachable!("operation does not select a document")
900            }
901            Self::Query(args) => &args.target,
902            Self::Get(args) => &args.path.target,
903            Self::Add(args) | Self::Replace(args) => &args.value.path.target,
904            Self::RenameKey(args) => &args.path.target,
905            Self::Remove(args) => &args.path.target,
906            Self::Move(args) | Self::Copy(args) => &args.path.target,
907            Self::Test(args) => &args.path.target,
908            Self::Patch(args) => &args.target,
909        }
910    }
911
912    fn path(&self) -> &str {
913        match self {
914            Self::Validate(_) | Self::Schema(_) | Self::Query(_) | Self::Patch(_) => {
915                unreachable!("operation does not use a JSON Pointer argument")
916            }
917            Self::Get(args) => args.path.pointer(),
918            Self::Add(args) | Self::Replace(args) => args.value.path.pointer(),
919            Self::RenameKey(args) => args.path.pointer(),
920            Self::Remove(args) => args.path.pointer(),
921            Self::Move(args) | Self::Copy(args) => &args.path.path,
922            Self::Test(args) => args.path.pointer(),
923        }
924    }
925
926    fn selection_query(&self) -> Option<&str> {
927        match self {
928            Self::Get(args) => args.path.query.as_deref(),
929            Self::Add(args) | Self::Replace(args) => args.value.path.query.as_deref(),
930            Self::RenameKey(args) => args.path.query.as_deref(),
931            Self::Remove(args) => args.path.query.as_deref(),
932            Self::Test(args) => args.path.query.as_deref(),
933            _ => None,
934        }
935    }
936
937    fn query_source(&self) -> Option<&str> {
938        match self {
939            Self::Query(args) => Some(&args.query),
940            _ => self.selection_query(),
941        }
942    }
943
944    fn mutation_output(&self) -> Option<&MutationOutputArgs> {
945        match self {
946            Self::Add(args) | Self::Replace(args) => Some(&args.output),
947            Self::RenameKey(args) => Some(&args.output),
948            Self::Remove(args) => Some(&args.output),
949            Self::Move(args) | Self::Copy(args) => Some(&args.output),
950            Self::Patch(args) => Some(&args.output),
951            Self::Validate(_) | Self::Schema(_) | Self::Query(_) | Self::Get(_) | Self::Test(_) => {
952                None
953            }
954        }
955    }
956
957    fn read_output(&self) -> Option<&Path> {
958        match self {
959            Self::Query(args) => args.output.output.as_deref(),
960            Self::Get(args) => args.output.output.as_deref(),
961            Self::Schema(args) => args.output.output.as_deref(),
962            _ => None,
963        }
964    }
965
966    fn has_read_output(&self) -> bool {
967        matches!(self, Self::Query(_) | Self::Get(_) | Self::Schema(_))
968    }
969
970    fn should_emit_batch_result(&self, result: &[u8]) -> bool {
971        match self {
972            Self::Query(_) => !result.is_empty(),
973            Self::Get(args) if args.path.query.is_some() => !result.is_empty(),
974            Self::Get(_) => true,
975            Self::Schema(_) => true,
976            _ => false,
977        }
978    }
979
980    fn input_path(&self) -> Option<&Path> {
981        match self {
982            Self::Validate(args) => args.file.as_deref(),
983            Self::Schema(args) => Some(&args.file),
984            Self::Get(args) => args.path.input_path(),
985            Self::Add(args) | Self::Replace(args) => args.value.path.input_path(),
986            Self::RenameKey(args) => args.path.input_path(),
987            Self::Remove(args) => args.path.input_path(),
988            Self::Test(args) => args.path.input_path(),
989            _ => self.target().file.as_deref(),
990        }
991    }
992
993    fn from(&self) -> Option<&str> {
994        match self {
995            Self::Move(args) | Self::Copy(args) => Some(&args.path.from),
996            _ => None,
997        }
998    }
999
1000    fn value(&self) -> Option<&ValueSourceArgs> {
1001        match self {
1002            Self::Add(args) | Self::Replace(args) => Some(&args.value.value),
1003            Self::Test(args) => Some(&args.value),
1004            _ => None,
1005        }
1006    }
1007}
1008
1009impl PathArgs {
1010    fn validate(&self) -> Result<(), String> {
1011        if self.query.is_some() && self.target.file.is_some() {
1012            return Err(
1013                "a JSONPath-targeted command accepts at most one positional FILE argument"
1014                    .to_owned(),
1015            );
1016        }
1017        Ok(())
1018    }
1019
1020    fn pointer(&self) -> &str {
1021        self.path_or_file
1022            .as_deref()
1023            .expect("Clap requires a pointer when --query is absent")
1024    }
1025
1026    fn input_path(&self) -> Option<&Path> {
1027        if self.query.is_some() {
1028            self.path_or_file.as_deref().map(Path::new)
1029        } else {
1030            self.target.file.as_deref()
1031        }
1032    }
1033}
1034
1035struct CommandOutput<'a> {
1036    input_path: Option<&'a Path>,
1037    stdout: &'a mut dyn Write,
1038    batch_capture: bool,
1039}
1040
1041fn execute_query_targeted(
1042    operation: &Operation,
1043    doc: &mut YamlDoc,
1044    document: usize,
1045    matches: &QueryMatches,
1046    value: Option<&YamlFragment>,
1047    output: &mut CommandOutput<'_>,
1048) -> Result<(), RunError> {
1049    match operation {
1050        Operation::Get(arguments) => {
1051            let rendered = render_yaml_stream(doc, matches)?;
1052            write_result(
1053                rendered.as_bytes(),
1054                if output.batch_capture {
1055                    None
1056                } else {
1057                    arguments.output.output.as_deref()
1058                },
1059                output.input_path,
1060                output.stdout,
1061            )
1062        }
1063        Operation::Test(_) => test_query_matches(
1064            doc,
1065            document,
1066            matches,
1067            value.expect("Clap requires a value"),
1068        ),
1069        Operation::Add(arguments) => {
1070            apply_query_mutation(
1071                doc,
1072                document,
1073                matches,
1074                QueryMutation::Add(value.expect("Clap requires a value")),
1075            )?;
1076            write_mutation(doc, &arguments.output, output.input_path, output.stdout)
1077        }
1078        Operation::Remove(arguments) => {
1079            apply_query_mutation(doc, document, matches, QueryMutation::Remove)?;
1080            write_mutation(doc, &arguments.output, output.input_path, output.stdout)
1081        }
1082        Operation::Replace(arguments) => {
1083            apply_query_mutation(
1084                doc,
1085                document,
1086                matches,
1087                QueryMutation::Replace(value.expect("Clap requires a value")),
1088            )?;
1089            write_mutation(doc, &arguments.output, output.input_path, output.stdout)
1090        }
1091        Operation::RenameKey(arguments) => {
1092            if matches.is_empty() {
1093                return Err(RunError::message("query matched no nodes"));
1094            }
1095            let pointers = matches
1096                .iter()
1097                .map(|matched| matched.pointer().clone())
1098                .collect::<Vec<_>>();
1099            doc.rename_keys_at(document, &pointers, &arguments.to)
1100                .map_err(RunError::display)?;
1101            write_mutation(doc, &arguments.output, output.input_path, output.stdout)
1102        }
1103        _ => unreachable!("only single-path commands accept --query"),
1104    }
1105}
1106
1107fn render_yaml_stream(doc: &YamlDoc, matches: &QueryMatches) -> Result<String, RunError> {
1108    let mut output = String::new();
1109    for matched in matches {
1110        output.push_str("---\n");
1111        if let Some(node) = matched.node() {
1112            let fragment = doc.extract_node(node).map_err(RunError::display)?;
1113            output.push_str(&fragment);
1114            if !fragment.ends_with(['\n', '\r']) {
1115                output.push('\n');
1116            }
1117        }
1118    }
1119    Ok(output)
1120}
1121
1122enum QueryMutation<'a> {
1123    Add(&'a YamlFragment),
1124    Remove,
1125    Replace(&'a YamlFragment),
1126}
1127
1128fn apply_query_mutation(
1129    doc: &mut YamlDoc,
1130    document: usize,
1131    matches: &QueryMatches,
1132    mutation: QueryMutation<'_>,
1133) -> Result<(), RunError> {
1134    if matches.is_empty() {
1135        return Err(RunError::message("query matched no nodes"));
1136    }
1137    let mut targets = normalized_mutation_targets(matches);
1138    if matches!(mutation, QueryMutation::Remove) {
1139        targets.sort_by(removal_order);
1140    }
1141    let mut work = doc.clone();
1142    for pointer in &targets {
1143        match mutation {
1144            QueryMutation::Add(value) => work.add_at(document, pointer, value),
1145            QueryMutation::Remove => work.remove_at(document, pointer),
1146            QueryMutation::Replace(value) => work.replace_at(document, pointer, value),
1147        }
1148        .map_err(RunError::display)?;
1149    }
1150    *doc = work;
1151    Ok(())
1152}
1153
1154fn normalized_mutation_targets(matches: &QueryMatches) -> Vec<JsonPointer> {
1155    let mut seen = HashSet::new();
1156    let unique = matches
1157        .iter()
1158        .filter_map(|matched| {
1159            let pointer = matched.pointer();
1160            seen.insert(pointer.as_str().to_owned())
1161                .then(|| pointer.clone())
1162        })
1163        .collect::<Vec<_>>();
1164    unique
1165        .iter()
1166        .filter(|pointer| {
1167            !unique
1168                .iter()
1169                .any(|candidate| candidate.is_proper_prefix_of(pointer))
1170        })
1171        .cloned()
1172        .collect()
1173}
1174
1175fn removal_order(left: &JsonPointer, right: &JsonPointer) -> CmpOrdering {
1176    right
1177        .tokens()
1178        .len()
1179        .cmp(&left.tokens().len())
1180        .then_with(|| {
1181            for (left, right) in left.tokens().iter().zip(right.tokens()) {
1182                let order = match (
1183                    left.as_str().parse::<usize>(),
1184                    right.as_str().parse::<usize>(),
1185                ) {
1186                    (Ok(left), Ok(right)) => right.cmp(&left),
1187                    _ => right.as_str().cmp(left.as_str()),
1188                };
1189                if order != CmpOrdering::Equal {
1190                    return order;
1191                }
1192            }
1193            CmpOrdering::Equal
1194        })
1195}
1196
1197fn test_query_matches(
1198    doc: &YamlDoc,
1199    document: usize,
1200    matches: &QueryMatches,
1201    value: &YamlFragment,
1202) -> Result<(), RunError> {
1203    if matches.is_empty() {
1204        return Err(RunError::message("query matched no nodes"));
1205    }
1206    for matched in matches {
1207        let pointer = matched.pointer();
1208        let equal = doc
1209            .test_at(document, pointer, value)
1210            .map_err(RunError::display)?;
1211        if !equal {
1212            return Err(RunError::message(format!(
1213                "test failed at {:?}: values are not semantically equal",
1214                pointer.as_str()
1215            )));
1216        }
1217    }
1218    Ok(())
1219}
1220
1221fn read_patch(arguments: &PatchSourceArgs, stdin: &mut dyn Read) -> Result<YamlPatch, RunError> {
1222    let input = if let Some(patch) = &arguments.patch {
1223        patch.clone()
1224    } else if let Some(path) = arguments.patch_file.as_deref() {
1225        if path == Path::new("-") {
1226            read_stream(stdin, "patch stdin")?
1227        } else {
1228            read_path(path, "patch file")?
1229        }
1230    } else {
1231        unreachable!("Clap requires a patch source")
1232    };
1233    YamlPatch::parse_owned(input).map_err(RunError::display)
1234}
1235
1236fn read_target(path: &Path) -> Result<String, RunError> {
1237    read_path(path, "")
1238}
1239
1240fn read_value(
1241    arguments: Option<&ValueSourceArgs>,
1242    target_uses_stdin: bool,
1243    stdin: &mut dyn Read,
1244) -> Result<Option<YamlFragment>, RunError> {
1245    let input = if let Some(value) = arguments.and_then(|arguments| arguments.value.as_ref()) {
1246        Some(value.clone())
1247    } else if let Some(path) = arguments.and_then(|arguments| arguments.value_file.as_deref()) {
1248        if path == Path::new("-") {
1249            if target_uses_stdin {
1250                return Err(RunError::message(
1251                    "target YAML and --value-file cannot both read stdin",
1252                ));
1253            }
1254            Some(read_stream(stdin, "value stdin")?)
1255        } else {
1256            Some(read_path(path, "value file")?)
1257        }
1258    } else {
1259        None
1260    };
1261    input
1262        .map(YamlFragment::parse_owned)
1263        .transpose()
1264        .map_err(RunError::display)
1265}
1266
1267fn read_stream(stream: &mut dyn Read, name: &str) -> Result<String, RunError> {
1268    read_with_limit(stream, name, ResourceLimits::default().max_source_bytes)
1269}
1270
1271fn read_path(path: &Path, kind: &str) -> Result<String, RunError> {
1272    let name = if kind.is_empty() {
1273        path.display().to_string()
1274    } else {
1275        format!("{kind} {}", path.display())
1276    };
1277    let mut file = File::open(path)
1278        .map_err(|error| RunError::message(format!("cannot read {name}: {error}")))?;
1279    read_with_limit(&mut file, &name, ResourceLimits::default().max_source_bytes)
1280}
1281
1282fn read_with_limit(
1283    stream: &mut dyn Read,
1284    name: &str,
1285    byte_limit: usize,
1286) -> Result<String, RunError> {
1287    let read_limit = byte_limit.saturating_add(1).min(u32::MAX as usize);
1288    let mut input = Vec::new();
1289    stream
1290        .take(read_limit as u64)
1291        .read_to_end(&mut input)
1292        .map_err(|error| RunError::message(format!("cannot read {name}: {error}")))?;
1293    if input.len() > byte_limit {
1294        return Err(RunError::message(format!(
1295            "{name} exceeds byte limit of {byte_limit}"
1296        )));
1297    }
1298    String::from_utf8(input)
1299        .map_err(|error| RunError::message(format!("cannot read {name}: {error}")))
1300}
1301
1302fn select_document(doc: &YamlDoc, selected: Option<usize>) -> Result<usize, RunError> {
1303    let count = doc.document_count();
1304    match selected {
1305        Some(index) if index < count => Ok(index),
1306        Some(index) => Err(RunError::message(format!(
1307            "document index {index} is out of range for {count} documents"
1308        ))),
1309        None if count == 1 => Ok(0),
1310        None if count == 0 => Err(RunError::message("YAML stream contains no documents")),
1311        None => Err(RunError::message(format!(
1312            "YAML stream contains {count} documents; select one with --doc"
1313        ))),
1314    }
1315}
1316
1317fn write_mutation(
1318    doc: &YamlDoc,
1319    arguments: &MutationOutputArgs,
1320    input: Option<&Path>,
1321    stdout: &mut dyn Write,
1322) -> Result<(), RunError> {
1323    if arguments.in_place {
1324        let input = input
1325            .filter(|path| *path != Path::new("-"))
1326            .ok_or_else(|| RunError::message("--in-place requires a real input filename"))?;
1327        atomic_replace(input, doc.as_source().as_bytes())
1328    } else {
1329        write_result(
1330            doc.as_source().as_bytes(),
1331            arguments.output.output.as_deref(),
1332            input,
1333            stdout,
1334        )
1335    }
1336}
1337
1338fn write_result(
1339    bytes: &[u8],
1340    output: Option<&Path>,
1341    input: Option<&Path>,
1342    stdout: &mut dyn Write,
1343) -> Result<(), RunError> {
1344    if let Some(output) = output {
1345        if input.is_some_and(|input| paths_equivalent(input, output)) {
1346            return Err(RunError::message(
1347                "--output must not name the input file; use --in-place",
1348            ));
1349        }
1350        fs::write(output, bytes).map_err(|error| {
1351            RunError::message(format!("cannot write {}: {error}", output.display()))
1352        })
1353    } else {
1354        stdout
1355            .write_all(bytes)
1356            .map_err(|error| RunError::io(&error))?;
1357        stdout.flush().map_err(|error| RunError::io(&error))
1358    }
1359}
1360
1361fn paths_equivalent(left: &Path, right: &Path) -> bool {
1362    match (fs::canonicalize(left), fs::canonicalize(right)) {
1363        (Ok(left), Ok(right)) => left == right,
1364        _ => absolute_path(left).ok() == absolute_path(right).ok(),
1365    }
1366}
1367
1368fn absolute_path(path: &Path) -> io::Result<PathBuf> {
1369    if path.is_absolute() {
1370        Ok(path.to_owned())
1371    } else {
1372        Ok(std::env::current_dir()?.join(path))
1373    }
1374}
1375
1376fn atomic_replace(path: &Path, bytes: &[u8]) -> Result<(), RunError> {
1377    let metadata = fs::symlink_metadata(path).map_err(|error| {
1378        RunError::message(format!("cannot inspect {}: {error}", path.display()))
1379    })?;
1380    if metadata.file_type().is_symlink() {
1381        return Err(RunError::message(
1382            "--in-place refuses to replace a symbolic link",
1383        ));
1384    }
1385    let parent = path.parent().unwrap_or_else(|| Path::new("."));
1386    let file_name = path
1387        .file_name()
1388        .ok_or_else(|| RunError::message("input path has no filename"))?;
1389    let (temporary, mut file) = create_sibling_temp(parent, file_name)?;
1390    let mut guard = TempGuard {
1391        path: temporary.clone(),
1392        armed: true,
1393    };
1394    file.set_permissions(metadata.permissions())
1395        .map_err(|error| {
1396            RunError::message(format!(
1397                "cannot preserve permissions for {}: {error}",
1398                path.display()
1399            ))
1400        })?;
1401    file.write_all(bytes)
1402        .map_err(|error| RunError::io(&error))?;
1403    file.flush().map_err(|error| RunError::io(&error))?;
1404    file.sync_all().map_err(|error| RunError::io(&error))?;
1405    drop(file);
1406    fs::rename(&temporary, path).map_err(|error| {
1407        RunError::message(format!(
1408            "cannot atomically replace {}: {error}",
1409            path.display()
1410        ))
1411    })?;
1412    guard.armed = false;
1413    Ok(())
1414}
1415
1416fn create_sibling_temp(parent: &Path, file_name: &OsStr) -> Result<(PathBuf, File), RunError> {
1417    for _ in 0..100 {
1418        let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
1419        let mut name = OsString::from(".");
1420        name.push(file_name);
1421        name.push(format!(".yaml-rt-{}-{counter}.tmp", std::process::id()));
1422        let path = parent.join(name);
1423        match OpenOptions::new().write(true).create_new(true).open(&path) {
1424            Ok(file) => return Ok((path, file)),
1425            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
1426            Err(error) => {
1427                return Err(RunError::message(format!(
1428                    "cannot create temporary file in {}: {error}",
1429                    parent.display()
1430                )));
1431            }
1432        }
1433    }
1434    Err(RunError::message(
1435        "could not allocate a unique temporary filename",
1436    ))
1437}
1438
1439struct TempGuard {
1440    path: PathBuf,
1441    armed: bool,
1442}
1443
1444impl Drop for TempGuard {
1445    fn drop(&mut self) {
1446        if self.armed {
1447            let _ = fs::remove_file(&self.path);
1448        }
1449    }
1450}
1451
1452enum RunError {
1453    BrokenPipe,
1454    Message(String),
1455    Diagnostic(String),
1456    Usage(String),
1457    Batch {
1458        diagnostics: Vec<String>,
1459        summary: String,
1460    },
1461}
1462
1463impl RunError {
1464    fn message(message: impl Into<String>) -> Self {
1465        Self::Message(message.into())
1466    }
1467
1468    fn usage(message: impl Into<String>) -> Self {
1469        Self::Usage(message.into())
1470    }
1471
1472    fn display(error: impl std::fmt::Display) -> Self {
1473        Self::Message(error.to_string())
1474    }
1475
1476    fn yaml_diagnostic(error: YamlError, source: &str, source_name: &str, color: bool) -> Self {
1477        let color = if color {
1478            DiagnosticColor::Always
1479        } else {
1480            DiagnosticColor::Never
1481        };
1482        Self::Diagnostic(
1483            error
1484                .render(source)
1485                .with_source_name(source_name)
1486                .with_color(color)
1487                .to_string(),
1488        )
1489    }
1490
1491    fn schema_diagnostic(error: SchemaError, source: &str, source_name: &str, color: bool) -> Self {
1492        let mut diagnostic = Diagnostic::new(
1493            DiagnosticKind::Semantic,
1494            error.message(),
1495            error.source_span().unwrap_or(Span::new(0, 0)),
1496        );
1497        if let Some(path) = error.instance_path() {
1498            diagnostic = diagnostic.with_note(format!("instance: {path}"));
1499        }
1500        if let Some(path) = error.schema_path() {
1501            diagnostic = diagnostic.with_note(format!("schema: {path}"));
1502        }
1503        let color = if color {
1504            DiagnosticColor::Always
1505        } else {
1506            DiagnosticColor::Never
1507        };
1508        Self::Diagnostic(
1509            diagnostic
1510                .render(source)
1511                .with_label("schema")
1512                .with_source_name(source_name)
1513                .with_color(color)
1514                .to_string(),
1515        )
1516    }
1517
1518    fn io(error: &io::Error) -> Self {
1519        if error.kind() == io::ErrorKind::BrokenPipe {
1520            Self::BrokenPipe
1521        } else {
1522            Self::Message(error.to_string())
1523        }
1524    }
1525}
1526
1527#[cfg(test)]
1528mod tests {
1529    use super::*;
1530
1531    fn invoke(args: &[&str], input: &str) -> (i32, String, String) {
1532        let mut stdin = input.as_bytes();
1533        let mut stdout = Vec::new();
1534        let mut stderr = Vec::new();
1535        let mut args = args.to_vec();
1536        args.push("-");
1537        let status = run(args, &mut stdin, &mut stdout, &mut stderr);
1538        (
1539            status,
1540            String::from_utf8(stdout).unwrap(),
1541            String::from_utf8(stderr).unwrap(),
1542        )
1543    }
1544
1545    #[test]
1546    fn validation_errors_render_source_aware_diagnostics() {
1547        let input = "enabled: true\nitems: [a, , b]\n";
1548        let mut stdin = input.as_bytes();
1549        let mut stdout = Vec::new();
1550        let mut stderr = Vec::new();
1551        let status = run(
1552            ["yaml-rt", "validate", "-"],
1553            &mut stdin,
1554            &mut stdout,
1555            &mut stderr,
1556        );
1557        let stderr = String::from_utf8(stderr).unwrap();
1558        assert_eq!(status, 1, "{stderr}");
1559        assert!(stdout.is_empty());
1560        assert!(stderr.contains("error[parser]:"), "{stderr}");
1561        assert!(stderr.contains(" --> <stdin>:2:"), "{stderr}");
1562        assert!(stderr.contains("2 | items: [a, , b]"), "{stderr}");
1563        assert!(stderr.contains('^'), "{stderr}");
1564        assert!(!stderr.contains("\x1b["), "{stderr:?}");
1565    }
1566
1567    #[test]
1568    fn input_reading_stops_at_the_configured_byte_limit() {
1569        let mut oversized = std::io::Cursor::new(b"abcdef".to_vec());
1570        let Err(RunError::Message(message)) = read_with_limit(&mut oversized, "stdin", 4) else {
1571            panic!("oversized input should be rejected");
1572        };
1573        assert_eq!(message, "stdin exceeds byte limit of 4");
1574        assert_eq!(oversized.position(), 5);
1575
1576        let mut exact = std::io::Cursor::new(b"abcd".to_vec());
1577        let Ok(exact) = read_with_limit(&mut exact, "stdin", 4) else {
1578            panic!("input at the limit should be accepted");
1579        };
1580        assert_eq!(exact, "abcd");
1581    }
1582
1583    #[test]
1584    fn explicit_cli_color_uses_standard_ansi_colors() {
1585        let mut stdin = "[\n".as_bytes();
1586        let mut stdout = Vec::new();
1587        let mut stderr = Vec::new();
1588        let status = run_with_options(
1589            ["yaml-rt", "validate", "-"],
1590            &mut stdin,
1591            &mut stdout,
1592            &mut stderr,
1593            RunOptions { color: true },
1594        );
1595        let stderr = String::from_utf8(stderr).unwrap();
1596        assert_eq!(status, 1, "{stderr}");
1597        assert!(stderr.contains("\x1b[1;31merror\x1b[0m"), "{stderr:?}");
1598        assert!(stderr.contains("\x1b[1;34m-->\x1b[0m"), "{stderr:?}");
1599    }
1600
1601    #[test]
1602    fn get_and_replace_work_with_stdin() {
1603        let (status, stdout, stderr) = invoke(
1604            &["yaml-rt", "get", "/server/host"],
1605            "server:\n  host: localhost\n",
1606        );
1607        assert_eq!(status, 0, "{stderr}");
1608        assert_eq!(stdout, "localhost");
1609
1610        let (status, stdout, stderr) = invoke(
1611            &[
1612                "yaml-rt",
1613                "replace",
1614                "/server/host",
1615                "--value",
1616                "example.com",
1617            ],
1618            "server:\n  host: localhost\n",
1619        );
1620        assert_eq!(status, 0, "{stderr}");
1621        assert_eq!(stdout, "server:\n  host: example.com\n");
1622    }
1623
1624    #[test]
1625    fn rename_key_works_with_pointer_and_document_selection() {
1626        let input = "---\nold: first\n---\nold: second # keep\n";
1627        let (status, stdout, stderr) = invoke(
1628            &[
1629                "yaml-rt",
1630                "rename-key",
1631                "/old",
1632                "--to",
1633                "true",
1634                "--doc",
1635                "1",
1636            ],
1637            input,
1638        );
1639        assert_eq!(status, 0, "{stderr}");
1640        assert_eq!(stdout, "---\nold: first\n---\n\"true\": second # keep\n");
1641    }
1642
1643    #[test]
1644    fn query_targeted_rename_is_atomic_and_requires_mapping_members() {
1645        let input = "items: [{old: 1}, {old: 2}]\n";
1646        let (status, stdout, stderr) = invoke(
1647            &["yaml-rt", "rename-key", "--query", "$..old", "--to", "new"],
1648            input,
1649        );
1650        assert_eq!(status, 0, "{stderr}");
1651        assert_eq!(stdout, "items: [{new: 1}, {new: 2}]\n");
1652
1653        let (status, stdout, stderr) = invoke(
1654            &["yaml-rt", "rename-key", "--query", "$..*", "--to", "new"],
1655            input,
1656        );
1657        assert_eq!(status, FAILURE);
1658        assert!(stdout.is_empty());
1659        assert!(stderr.contains("does not select a mapping member"));
1660
1661        let (status, stdout, stderr) = invoke(
1662            &[
1663                "yaml-rt",
1664                "rename-key",
1665                "--query",
1666                "$.missing",
1667                "--to",
1668                "new",
1669            ],
1670            input,
1671        );
1672        assert_eq!(status, FAILURE);
1673        assert!(stdout.is_empty());
1674        assert!(stderr.contains("query matched no nodes"));
1675    }
1676
1677    #[test]
1678    fn query_targeted_rename_rolls_back_collisions() {
1679        let (status, stdout, stderr) = invoke(
1680            &[
1681                "yaml-rt",
1682                "rename-key",
1683                "--query",
1684                "$['a','b']",
1685                "--to",
1686                "x",
1687            ],
1688            "a: 1\nb: 2\n",
1689        );
1690        assert_eq!(status, FAILURE);
1691        assert!(stdout.is_empty());
1692        assert!(stderr.contains("duplicate key \"x\""));
1693    }
1694
1695    #[test]
1696    fn query_works_with_stdin_and_no_matches_succeed() {
1697        let input = "users:\n  - {name: Ada, active: true}\n  - {name: Linus, active: false}\n";
1698        let (status, stdout, stderr) = invoke(
1699            &["yaml-rt", "query", "$.users[?@.active == true].name"],
1700            input,
1701        );
1702        assert_eq!(status, 0, "{stderr}");
1703        assert_eq!(stdout, "\"/users/0/name\": \"Ada\"\n");
1704
1705        let (status, stdout, stderr) = invoke(&["yaml-rt", "query", "$.missing"], input);
1706        assert_eq!(status, 0, "{stderr}");
1707        assert!(stdout.is_empty());
1708    }
1709
1710    #[test]
1711    fn get_query_emits_a_yaml_document_stream() {
1712        let input = "users:\n  - {name: Ada}\n  - {name: Linus}\n";
1713        let (status, stdout, stderr) =
1714            invoke(&["yaml-rt", "get", "--query", "$.users[*].name"], input);
1715        assert_eq!(status, 0, "{stderr}");
1716        assert_eq!(stdout, "---\nAda\n---\nLinus\n");
1717
1718        let (status, stdout, stderr) = invoke(&["yaml-rt", "get", "--query", "$.missing"], input);
1719        assert_eq!(status, 0, "{stderr}");
1720        assert!(stdout.is_empty());
1721
1722        let (status, stdout, stderr) = invoke(&["yaml-rt", "get", "--query", "$"], "---\n");
1723        assert_eq!(status, 0, "{stderr}");
1724        assert_eq!(stdout, "---\n");
1725    }
1726
1727    #[test]
1728    fn query_targeted_value_mutations_are_atomic() {
1729        let input = "items: [{enabled: false}, {enabled: false}]\n";
1730        for operation in ["add", "replace"] {
1731            let (status, stdout, stderr) = invoke(
1732                &[
1733                    "yaml-rt",
1734                    operation,
1735                    "--query",
1736                    "$.items[*].enabled",
1737                    "--value",
1738                    "true",
1739                ],
1740                input,
1741            );
1742            assert_eq!(status, 0, "{stderr}");
1743            assert_eq!(stdout, "items: [{enabled: true}, {enabled: true}]\n");
1744        }
1745
1746        let (status, stdout, stderr) = invoke(
1747            &[
1748                "yaml-rt",
1749                "replace",
1750                "--query",
1751                "$.missing",
1752                "--value",
1753                "true",
1754            ],
1755            input,
1756        );
1757        assert_eq!(status, FAILURE);
1758        assert!(stdout.is_empty());
1759        assert!(stderr.contains("query matched no nodes"));
1760    }
1761
1762    #[test]
1763    fn query_targeted_remove_normalizes_and_orders_matches() {
1764        let (status, stdout, stderr) = invoke(
1765            &["yaml-rt", "remove", "--query", "$.items[0,2,0]"],
1766            "items: [a, b, c, d]\n",
1767        );
1768        assert_eq!(status, 0, "{stderr}");
1769        assert_eq!(stdout, "items: [b, d]\n");
1770
1771        let (status, stdout, stderr) = invoke(
1772            &["yaml-rt", "remove", "--query", "$..*"],
1773            "root: {child: x}\nuntouched: y\n",
1774        );
1775        assert_eq!(status, 0, "{stderr}");
1776        assert_eq!(stdout, "{}\n");
1777    }
1778
1779    #[test]
1780    fn query_targeted_test_requires_matches_and_tests_every_node() {
1781        let input = "values: [1, 1, 2]\n";
1782        let (status, stdout, stderr) = invoke(
1783            &[
1784                "yaml-rt",
1785                "test",
1786                "--query",
1787                "$.values[0,1]",
1788                "--value",
1789                "1",
1790            ],
1791            input,
1792        );
1793        assert_eq!(status, 0, "{stderr}");
1794        assert!(stdout.is_empty());
1795
1796        let (status, stdout, stderr) = invoke(
1797            &["yaml-rt", "test", "--query", "$.values[*]", "--value", "1"],
1798            input,
1799        );
1800        assert_eq!(status, FAILURE);
1801        assert!(stdout.is_empty());
1802        assert!(stderr.contains("/values/2"));
1803
1804        let (status, stdout, stderr) = invoke(
1805            &["yaml-rt", "test", "--query", "$.missing", "--value", "1"],
1806            input,
1807        );
1808        assert_eq!(status, FAILURE);
1809        assert!(stdout.is_empty());
1810        assert!(stderr.contains("query matched no nodes"));
1811    }
1812
1813    #[test]
1814    fn query_targeted_commands_reject_extra_positionals_as_usage_errors() {
1815        let (status, stdout, stderr) = invoke(
1816            &["yaml-rt", "get", "--query", "$.value", "first"],
1817            "value: 1\n",
1818        );
1819        assert_eq!(status, USAGE);
1820        assert!(stdout.is_empty());
1821        assert!(stderr.contains("at most one positional FILE"));
1822    }
1823
1824    #[test]
1825    fn query_targeted_commands_report_query_errors_before_output() {
1826        let (status, stdout, stderr) =
1827            invoke(&["yaml-rt", "get", "--query", "not-jsonpath"], "value: 1\n");
1828        assert_eq!(status, FAILURE);
1829        assert!(stdout.is_empty());
1830        assert!(stderr.contains("JSONPath"));
1831
1832        let (status, stdout, stderr) = invoke(
1833            &["yaml-rt", "remove", "--query", "$.*"],
1834            "? [complex, key]\n: value\n",
1835        );
1836        assert_eq!(status, FAILURE);
1837        assert!(stdout.is_empty());
1838        assert!(stderr.contains("non-string key"));
1839    }
1840
1841    #[test]
1842    fn test_failure_has_no_stdout() {
1843        let (status, stdout, stderr) =
1844            invoke(&["yaml-rt", "test", "/value", "--value", "2"], "value: 1\n");
1845        assert_eq!(status, FAILURE);
1846        assert!(stdout.is_empty());
1847        assert!(stderr.contains("test failed"));
1848    }
1849
1850    #[test]
1851    fn inline_patch_is_transactional() {
1852        let patch =
1853            "- {op: replace, path: /port, value: 9090}\n- {op: add, path: /debug, value: true}\n";
1854        let (status, stdout, stderr) = invoke(
1855            &["yaml-rt", "patch", "--patch", patch],
1856            "port: 8080 # keep\n",
1857        );
1858        assert_eq!(status, 0, "{stderr}");
1859        assert_eq!(stdout, "port: 9090 # keep\ndebug: true\n");
1860
1861        let failing =
1862            "- {op: replace, path: /port, value: 9090}\n- {op: test, path: /port, value: 8080}\n";
1863        let (status, stdout, stderr) =
1864            invoke(&["yaml-rt", "patch", "--patch", failing], "port: 8080\n");
1865        assert_eq!(status, FAILURE);
1866        assert!(stdout.is_empty());
1867        assert!(stderr.contains("patch operation[1]"));
1868    }
1869
1870    #[test]
1871    fn patch_source_is_required_and_exclusive() {
1872        let (status, _, stderr) = invoke(&["yaml-rt", "patch"], "{}\n");
1873        assert_eq!(status, USAGE);
1874        assert!(stderr.contains("required"));
1875
1876        let (status, _, stderr) = invoke(
1877            &[
1878                "yaml-rt",
1879                "patch",
1880                "--patch",
1881                "[]",
1882                "--patch-file",
1883                "changes.yaml",
1884            ],
1885            "{}\n",
1886        );
1887        assert_eq!(status, USAGE);
1888        assert!(stderr.contains("cannot be used with"));
1889    }
1890
1891    #[test]
1892    fn multiple_documents_require_selection() {
1893        let (status, _, stderr) = invoke(&["yaml-rt", "get", ""], "--- one\n--- two\n");
1894        assert_eq!(status, FAILURE);
1895        assert!(stderr.contains("--doc"));
1896    }
1897
1898    #[test]
1899    fn derive_arguments_enforce_value_and_output_conflicts() {
1900        let (status, stdout, stderr) = invoke(&["yaml-rt", "replace", "/value"], "value: 1\n");
1901        assert_eq!(status, USAGE);
1902        assert!(stdout.is_empty());
1903        assert!(stderr.contains("--value"));
1904
1905        let (status, stdout, stderr) = invoke(
1906            &[
1907                "yaml-rt",
1908                "replace",
1909                "/value",
1910                "--value",
1911                "1",
1912                "--value-file",
1913                "value.yaml",
1914            ],
1915            "value: 1\n",
1916        );
1917        assert_eq!(status, USAGE);
1918        assert!(stdout.is_empty());
1919        assert!(stderr.contains("cannot be used with"));
1920
1921        let (status, stdout, stderr) = invoke(
1922            &[
1923                "yaml-rt",
1924                "remove",
1925                "/value",
1926                "--output",
1927                "out.yaml",
1928                "--in-place",
1929            ],
1930            "value: 1\n",
1931        );
1932        assert_eq!(status, USAGE);
1933        assert!(stdout.is_empty());
1934        assert!(stderr.contains("cannot be used with"));
1935    }
1936
1937    #[test]
1938    fn hyphen_prefixed_inline_yaml_is_accepted() {
1939        let (status, stdout, stderr) = invoke(&["yaml-rt", "get", "-invalid"], "value: old\n");
1940        assert_eq!(status, FAILURE);
1941        assert!(stdout.is_empty());
1942        assert!(stderr.contains("JSON Pointer"));
1943
1944        let (status, stdout, stderr) = invoke(
1945            &["yaml-rt", "replace", "/value", "--value", "-1"],
1946            "value: old\n",
1947        );
1948        assert_eq!(status, 0, "{stderr}");
1949        assert_eq!(stdout, "value: -1\n");
1950    }
1951}