### Multiline flow mapping style example Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Style.html Example of a multiline flow mapping style, as shown in the documentation for the MultilineFlowMapping variant. ```yaml { key: value, key2: value2 } ``` -------------------------------- ### Multiline flow sequence style example Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Style.html Example of a multiline flow sequence style, as shown in the documentation for the MultilineFlowSequence variant. ```yaml [ item1, item2, ] ``` -------------------------------- ### YAML rewrite example for RewriteFragment Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Example showing a YAML fragment before and after a rewrite operation, along with the configuration for the rewrite. The operation replaces the first match of 'from' with 'to'. ```yaml run: | echo "foo: ${{ foo }}" ``` ```yaml run: | echo "foo ${FOO}" ``` ```text route: "/run", from: "${{ foo }}", to: "${FOO}", ``` -------------------------------- ### route_to_feature_pretty function Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Queries a YAML document using a route and returns the feature in a pretty format. ```rust pub fn route_to_feature_pretty<'a>( route: &yamlpath::Route<'_>, doc: &'a yamlpath::Document, ) -> Result, Error> { doc.query_pretty(route).map_err(Error::from) } ``` -------------------------------- ### Op::Replace Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Replaces the value at the given path. ```APIDOC ## Op::Replace ### Description Replaces the value at the given path. ### Variant `Replace(Value)` ### Fields - **value** (Value) - Required - The new value to replace the existing one. ``` -------------------------------- ### Op::Add Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Adds a new key-value pair at the given path. The route should point to a mapping. The mapping must be a block mapping or single-line flow mapping; multi-line flow mappings are not supported. The key must not already exist in the targeted mapping. ```APIDOC ## Op::Add ### Description Adds a new key-value pair at the given path. The route should point to a mapping. The mapping must be a block mapping or single-line flow mapping; multi-line flow mappings are not currently supported. The key must not already exist in the targeted mapping. ### Variant `Add { key: String, value: Value }` ### Fields - **key** (String) - Required - The key to add. - **value** (Value) - Required - The value to associate with the key. ### Limitations - The mapping must be a block mapping or single-line flow mapping. - Multi-line flow mappings are not currently supported. - The key must not already exist in the targeted mapping. ``` -------------------------------- ### Rust: handle_block_mapping_addition function Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Formats a new YAML key-value entry for insertion into a block mapping. Serializes the value (using flow style for sequences, otherwise standard YAML serialization), determines indentation from the existing document, and builds the entry string. For empty mappings, formats inline; for non-empty mappings, nests the value with two spaces of indentation per level. ```rust fn handle_block_mapping_addition( feature_content: &str, doc: &yamlpath::Document, feature: &yamlpath::Feature, key: &str, value: &yaml_serde::Value, ) -> Result { // Convert the new value to YAML string for block style handling let new_value_str = if matches!(value, yaml_serde::Value::Sequence(_)) { // For sequences, use flow-aware serialization to maintain consistency serialize_flow(value)? } else { serialize_yaml_value(value)? }; let new_value_str = new_value_str.trim_end(); // Remove trailing newline // Determine the appropriate indentation let indent = " ".repeat(extract_leading_indentation_for_block_item(doc, feature)); // Format the new entry let mut final_entry = if let yaml_serde::Value::Mapping(mapping) = &value { if mapping.is_empty() { // For empty mappings, format inline format!("\n{indent}{key}: {new_value_str}") } else { // For non-empty mappings, format as a nested structure let value_lines = new_value_str.lines(); let mut result = format!("\n{indent}{key}:"); for line in value_lines { if !line.trim().is_empty() { result.push('\n'); result.push_str(&indent); result.push_str(" "); // 2 spaces for nested content // `serialize_yaml_value` anchors its output at column 0, so // each line's own leading whitespace *is* its depth relative // to the value's root. Trimming it here would flatten every // nested level into a sibling of the top-level key. result.push_str(line); } } } }; // ... (rest of function omitted in source) } ``` -------------------------------- ### Op::MergeInto Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Updates a mapping at the given path. If the mapping does not already exist, it will be created. ```APIDOC ## Op::MergeInto ### Description Updates a mapping at the given path. If the mapping does not already exist, it will be created. ### Variant `MergeInto { key: String, updates: IndexMap }` ### Fields - **key** (String) - Required - The key of the mapping to update. - **updates** (IndexMap) - Required - The updates to apply to the mapping. ``` -------------------------------- ### route_to_feature_exact function Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Queries a YAML document using a route and returns the exact feature, or None if not found. ```rust pub fn route_to_feature_exact<'a>( route: &yamlpath::Route<'_>, doc: &'a yamlpath::Document, ) -> Result>, Error> { doc.query_exact(route).map_err(Error::from) } ``` -------------------------------- ### Rust: indent_multiline_yaml function Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Indents multi-line YAML content to match a target base indentation. The first line is kept as-is; subsequent non-empty lines are prefixed with the base indent plus two extra spaces. Empty lines are preserved with just the base indent. Returns the original content unchanged if it has one line or fewer. ```rust fn indent_multiline_yaml(content: &str, base_indent: &str) -> String { let lines: Vec<&str> = content.lines().collect(); if lines.len() <= 1 { return content.to_string(); } let mut result = String::new(); for (i, line) in lines.iter().enumerate() { if i == 0 { result.push_str(line); } else { result.push('\n'); result.push_str(base_indent); if !line.trim().is_empty() { result.push_str(" "); // Additional indentation for continuation result.push_str(line.trim_start()); } } } result } ``` -------------------------------- ### serialize_flow(value: &Value) -> Result Source: https://docs.rs/yamlpatch/latest/yamlpatch/fn.serialize_flow.html Serializes a `yaml_serde::Value` to a YAML string in flow layout. This function supports only a restricted subset of YAML: tags are not supported, and mapping keys must be strings. ```APIDOC ## Function: serialize_flow ### Description Serializes a `yaml_serde::Value` to a YAML string in flow layout. This function supports only a restricted subset of YAML: tags are not supported, and mapping keys must be strings. ### Signature rust pub fn serialize_flow(value: &Value) -> Result ### Parameters - **value** (`&Value`) - The `yaml_serde::Value` to serialize. ### Returns - `Result` - On success, returns the YAML string in flow layout. On failure, returns an error. ### Constraints - Tags are not supported. - Mapping keys must be strings. ``` -------------------------------- ### Op::Remove Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Removes the key at the given path. ```APIDOC ## Op::Remove ### Description Removes the key at the given path. ### Variant `Remove` ``` -------------------------------- ### MergeInto operation handling Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Handles the MergeInto operation, checking if a key exists in a mapping and applying the appropriate patch (Replace or Add). Returns an error if the key exists but has an empty body, and adds the entire update if the key does not exist. ```rust if existing_mapping.contains_key(k) { current_document = apply_single_patch( ¤t_document, &Patch { route: existing_key_route.with_key(k.as_str()), operation: Op::Replace(v.clone()), }, )?; } else { current_document = apply_single_patch( ¤t_document, &Patch { route: existing_key_route.clone(), operation: Op::Add { key: k.into(), value: v.clone(), }, }, )?; } } return Ok(current_document); } // The key exists, but has an empty body. // TODO: Support this. Ok(None) => { return Err(Error::InvalidOperation(format!( "MergeInto: cannot merge into empty key at {existing_key_route:?}" ))); } // The key does not exist. Err(Error::Query(yamlpath::QueryError::ExhaustedMapping(_))) => { return apply_single_patch( document, &Patch { route: patch.route.clone(), operation: Op::Add { key: key.clone(), value: yaml_serde::to_value(updates.clone())?, }, }, ); } Err(e) => return Err(e), ``` -------------------------------- ### route_to_feature_pretty Source: https://docs.rs/yamlpatch/latest/yamlpatch/fn.route_to_feature_pretty.html Converts a route to a feature representation using a YAML document. ```APIDOC ## Function route_to_feature_pretty ### Description Converts a route to a feature representation using a YAML document. ### Signature ```rust pub fn route_to_feature_pretty<'a>( route: &Route<'_>, doc: &'a Document, ) -> Result, Error> ``` ### Parameters - **route** (`&Route<'_>`) - The route to convert. - **doc** (`&'a Document`) - The YAML document to use for feature extraction. ### Returns - **Result, Error>** - The resulting feature or an error if conversion fails. ``` -------------------------------- ### Op::Append Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Appends a new item to a sequence at the given path. The sequence must be a block sequence; flow sequences are not supported. ```APIDOC ## Op::Append ### Description Appends a new item to a sequence at the given path. The sequence must be a block sequence; flow sequences are not supported. ### Variant `Append { value: Value }` ### Fields - **value** (Value) - Required - The value to append to the sequence. ### Limitations - The sequence must be a block sequence. - Flow sequences are not supported. ``` -------------------------------- ### Replace operation implementation Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Handles the Op::Replace operation. It retrieves the feature at the patch route, applies value replacement, and calculates the span to replace, including leading whitespace for key-value pairs. ```rust Op::Replace(value) => { let feature = route_to_feature_pretty(&patch.route, document)?; // Get the replacement content let replacement = apply_value_replacement(&feature, document, value, true)?; // Extract the current content to calculate spans let current_content = document.extract(&feature); let current_content_with_ws = document.extract_with_leading_whitespace(&feature); // Find the span to replace - use the span with leading whitespace if it's a key-value pair let (start_span, end_span) = if current_content_with_ws.contains(':') { // Replace the entire key-value pair span let ws_start = feature.location.byte_span.0 ``` -------------------------------- ### apply_yaml_patches Source: https://docs.rs/yamlpatch/latest/yamlpatch/fn.apply_yaml_patches.html Applies a sequence of YAML patch operations to a YAML document and returns a new YAML document. Returns an error if the input is invalid, a patch operation fails, or the resulting YAML is malformed. ```APIDOC ## apply_yaml_patches ### Description Applies a sequence of YAML patch operations to a YAML document. Returns a new YAML document with the patches applied. Returns an error if the given YAML input is not valid, if a patch operation fails, or if the resulting YAML is malformed. ### Function Signature ```rust pub fn apply_yaml_patches( document: &Document, patches: &[Patch<'_>], ) -> Result ``` ### Parameters - **document** (`&Document`) - The YAML document to which patches are applied. - **patches** (`&[Patch<'_>]`) - A slice of patch operations to apply in order. ### Returns - **Result** - A new YAML document with the patches applied, or an error if the input is invalid, a patch operation fails, or the resulting YAML is malformed. ### Behavior Each patch is applied in the order given. The `Patch` APIs are designed to operate symbolically without absolute byte positions, so operations should not invalidate each other unless they actually conflict in terms of proposed changes. ``` -------------------------------- ### Handle flow mapping value replacement Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Replaces a value within a flow mapping (e.g., `{ key: }` or `{ key: oldvalue }`). It parses the content to find the colon and existing value, then constructs the new mapping string. Handles both cases: empty value after colon and existing value. ```rust /// Handle value replacement within flow mappings more precisely fn handle_flow_mapping_value_replacement( _content: &str, _start_byte: usize, _end_byte: usize, current_content: &str, value: &yaml_serde::Value, ) -> Result { let val_str = serialize_yaml_value(value)?; let val_str = val_str.trim(); // Parse the flow mapping content to understand the structure let trimmed = current_content.trim(); // Case 1: { key: } - has colon, empty value if let Some(colon_pos) = trimmed.find(':') { let before_colon = &trimmed[..colon_pos]; let after_colon = &trimmed[colon_pos + 1..]; // Check if there's already a value after the colon (excluding the closing brace) let value_part = after_colon.trim().trim_end_matches('}').trim(); if value_part.is_empty() { // Case: { key: } -> { key: value } let key_part = before_colon.trim_start_matches('{').trim(); Ok(format!("{{ {key_part}: {val_str} }}")) } else { // Case: { key: oldvalue } -> { key: newvalue } let key_part = before_colon.trim_start_matches('{').trim(); Ok(format!("{{ {key_part}: {val_str} }}")) } } else { // Case 2: { key } - no colon, bare key -> { key: value } let key_part = trimmed.trim_start_matches('{').trim_end_matches('}').trim(); Ok(format!("{{ {key_part}: {val_str} }}")) } } ``` -------------------------------- ### Handle non-empty block collection replacement Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Replaces a value in a block mapping when the new value is a non-empty collection (mapping or sequence). It emits the value as a nested block with 2-space indentation, preserving each line's relative depth. Empty collections remain inline. ```rust // A non-empty block collection can't share the key's line: splicing it // after `key:` produces invalid YAML even when its serialized form is a // single line, e.g. `target: outer: value` or `target: - value`. Emit it // as a nested block instead, while keeping empty collections inline. let is_nonempty_block_collection = match value { yaml_serde::Value::Mapping(mapping) => !mapping.is_empty(), yaml_serde::Value::Sequence(sequence) => !sequence.is_empty(), _ => false, }; if is_nonempty_block_collection { let key_indent = &key_part[..key_part.len() - key_part.trim_start().len()]; let mut result = key_part.to_string(); for line in val_str.lines() { if !line.trim().is_empty() { result.push('\n'); result.push_str(key_indent); result.push_str(" "); // 2 spaces for nested content // As above: preserve each line's own relative depth. result.push_str(line); } } result } else { format!("{} {}", key_part, val_str.trim()) } } else { // This is just a value, replace it directly serialize_yaml_value(value)? }; Ok(replacement) } ``` -------------------------------- ### Rust: extract_leading_whitespace function Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Extracts leading spaces from the line containing a given YAML feature. Uses the document source and feature location to find the line span, then returns the whitespace prefix. Returns an empty string if the line has no leading spaces. ```rust pub fn extract_leading_whitespace<'doc>( doc: &'doc yamlpath::Document, feature: &yamlpath::Feature, ) -> &'doc str { let line_range = line_span(doc, feature.location.byte_span.0); let line_content = &doc.source()[line_range]; let end = line_content .bytes() .position(|b| b != b' ') .unwrap_or(line_content.len()); &line_content[..end] } ``` -------------------------------- ### Patch Struct Source: https://docs.rs/yamlpatch/latest/yamlpatch/struct.Patch.html Represents a single YAML patch, consisting of a route to the feature to patch and the operation to perform. ```APIDOC ## Struct Patch ### Description Represents a single YAML patch. A patch operation consists of a route to the feature to patch and the operation to perform on that feature. ### Definition ```rust pub struct Patch<'doc> { pub route: Route<'doc>, pub operation: Op<'doc>, } ``` ### Fields - **route** (`Route<'doc>`) - The route to the feature to patch. - **operation** (`Op<'doc>`) - The operation to perform on the feature. ### Trait Implementations - `Clone` - Provides `clone` and `clone_from` methods. - `Debug` - Provides `fmt` method for formatting. ### Auto Trait Implementations - `Freeze` - `RefUnwindSafe` - `Send` - `Sync` - `Unpin` - `UnsafeUnpin` - `UnwindSafe` ### Blanket Implementations - `Any`, `Borrow`, `BorrowMut`, `CloneToUninit`, `From`, `Into`, `ToOwned`, `TryFrom`, `TryInto` ``` -------------------------------- ### Op::RewriteFragment Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Rewrites a fragment of a feature at the given path. This operation performs exactly one rewrite at a time, replacing the first match of `from` in the feature. ```APIDOC ## Op::RewriteFragment ### Description Rewrites a fragment of a feature at the given path. This can be used to perform graceful rewrites of string values, regardless of their nested position or single/multi-line nature. This operation performs exactly one rewrite at a time, meaning that the first match of `from` in the feature will be replaced. ### Variant `RewriteFragment { from: Subfeature<'doc>, to: Cow<'doc, str> }` ### Fields - **from** (Subfeature<'doc>) - Required - The fragment to match and replace. - **to** (Cow<'doc, str>) - Required - The replacement string. ### Notes - The first match of `from` in the feature will be replaced. - Can be made more precise by passing an `after` index, which specifies that the rewrite should only occur on the first match of `from` that occurs after the given byte index. ### Example Given a feature with the value: run: | echo "foo: ${{ foo }}" It can be rewritten to: run: | echo "foo ${FOO}" via a `RewriteFragment` with: route: "/run", from: "${{ foo }}", to: "${FOO}", ``` -------------------------------- ### Style::from_feature Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Style.html Determines the YAML style of a feature based on its document. This is a public method on the Style enum that takes a feature reference and its document, returning the corresponding Style variant. ```APIDOC ## Style::from_feature ### Description Given a feature and its document, determine the style of the feature. This method inspects the YAML representation and returns the appropriate Style variant. ### Method from_feature ### Signature pub fn from_feature(feature: &Feature<'_>, doc: &Document) -> Self ### Parameters - **feature** (&Feature<'_>) - Required - Reference to the feature whose style is to be determined. - **doc** (&Document) - Required - Reference to the YAML document containing the feature. ### Returns - **Style** - The style variant representing the YAML formatting of the feature. ### Example ```rust let style = Style::from_feature(&feature, &doc); ``` ``` -------------------------------- ### EmplaceComment operation implementation Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Handles the Op::EmplaceComment operation. It checks for existing comments and either emplaces a new comment at the end of the first line of the feature, delegates to ReplaceComment if one comment exists, or errors on multiple comments. Includes FIXME notes about edge cases. ```rust Op::EmplaceComment { new } => { // FIXME: We should gracefully handle empty features here, // since `foo:` -> `foo: # comment` is a reasonable operation. let feature = route_to_feature_exact(&patch.route, document)?.ok_or_else(|| { Error::InvalidOperation(format!( "no existing feature at {route:?}", route = patch.route )) })?; // FIXME: We can't emplace comments on non-block multi-line // scalars with the technique below, since the comment // would end up inside the scalar. We just exclude these for now. if matches!( Style::from_feature(&feature, document), Style::SingleQuoted | Style::DoubleQuoted ) && feature.is_multiline() { return Err(Error::InvalidOperation(format!( "cannot emplace comment on non-block multi-line scalar at {route:?}", route = patch.route ))); } let comment_features = document.feature_comments(&feature); match comment_features.len() { 0 => { // No existing comment; emplace a new one. // The 'right' emplacement location is subjective; // we capriciously choose to emplace the new comment at the end // of the first line of the feature. let line_range = line_span(document, feature.location.byte_span.0); let mut insert_pos = line_range.end; if let Some(b'\n') = document.source().as_bytes().get(insert_pos - 1) { insert_pos -= 1; } if let Some(b'\r') = document.source().as_bytes().get(insert_pos - 1) { insert_pos -= 1; } let mut result = content.to_string(); result.insert_str(insert_pos, &format!(" {new}")); result } 1 => { return apply_single_patch( document, &Patch { route: patch.route.clone(), operation: Op::ReplaceComment { new: new.clone() }, }, ); } _ => { return Err(Error::InvalidOperation(format!( "multiple comments found at {route:?}", route = patch.route ))); } } } ``` -------------------------------- ### extract_leading_indentation_for_block_item Source: https://docs.rs/yamlpatch/latest/yamlpatch/fn.extract_leading_indentation_for_block_item.html Extracts the number of leading spaces needed to align a block item with its surrounding context, accounting for block sequences. ```APIDOC ## Function extract_leading_indentation_for_block_item ### Description Extracts the number of leading spaces needed to align a block item with its surrounding context. This takes into account block sequences, e.g. where the mapping is a child of a list item and needs to be properly aligned with the list item's other content. ### Signature ```rust pub fn extract_leading_indentation_for_block_item( doc: &Document, feature: &Feature<'_>, ) -> usize ``` ### Parameters - **doc** (`&Document`) - The YAML document to inspect. - **feature** (`&Feature<'_>`) - The feature for which to extract indentation. ### Returns - **usize** - The number of leading spaces needed for alignment. ``` -------------------------------- ### Finalize patched content Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Ensures the patched content ends with a newline and creates a new yamlpath::Document from it. ```rust if !patched_content.ends_with('\n') { patched_content.push('\n'); } yamlpath::Document::new(patched_content).map_err(Error::from) ``` -------------------------------- ### ReplaceComment operation implementation Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Handles the Op::ReplaceComment operation. It finds the exact feature at the patch route, retrieves its comment features, and replaces the comment. Returns an error if no feature exists or if multiple comments are found. ```rust Op::ReplaceComment { new } => { let feature = route_to_feature_exact(&patch.route, document)?.ok_or_else(|| { Error::InvalidOperation(format!( "no existing feature at {route:?}", route = patch.route )) })?; let comment_features = document.feature_comments(&feature); let comment_feature = match comment_features.len() { 0 => return Ok(document.clone()), 1 => &comment_features[0], _ => { return Err(Error::InvalidOperation(format!( "multiple comments found at {route:?}", route = patch.route ))); } }; let mut result = content.to_string(); result.replace_range(comment_feature, new); result } ``` -------------------------------- ### Style enum definition Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Style.html The Style enum definition with all its variants, representing different YAML styles. ```rust pub enum Style { BlockMapping, BlockSequence, MultilineFlowMapping, FlowMapping, MultilineFlowSequence, FlowSequence, MultilineLiteralScalar, MultilineFoldedScalar, DoubleQuoted, SingleQuoted, PlainScalar, } ``` -------------------------------- ### route_to_feature_exact Source: https://docs.rs/yamlpatch/latest/yamlpatch/fn.route_to_feature_exact.html Resolves a route to a feature in a YAML document, returning an optional Feature reference. This function is part of the yamlpatch crate's public API. ```APIDOC ## Function route_to_feature_exact ### Description Resolves a route to a feature in a YAML document, returning an optional Feature reference. This function is part of the yamlpatch crate's public API. ### Signature ```rust pub fn route_to_feature_exact<'a>( route: &Route<'_>, doc: &'a Document, ) -> Result>, Error> ``` ### Parameters - **route** (`&Route<'_>`) - Required - The route to resolve. - **doc** (`&'a Document`) - Required - The YAML document to search. ### Returns - **`Result>, Error>`** - Returns `Ok(Some(feature))` if the route resolves to a feature, `Ok(None)` if no feature is found, or `Err(Error)` on failure. ``` -------------------------------- ### Op::ReplaceComment Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Replaces the entire comment associated with the feature at the given path with the new comment. Only one matching comment is permitted; features without a comment are ignored, and features with multiple comments are rejected. ```APIDOC ## Op::ReplaceComment ### Description Replaces the entire comment associated with the feature at the given path with the new comment. The entire comment is replaced at once, and only one matching comment is permitted. Features that don't have an associated comment are ignored, while features with multiple comments will be rejected. ### Variant `ReplaceComment { new: Cow<'doc, str> }` ### Fields - **new** (Cow<'doc, str>) - Required - The new comment to replace the existing one. ### Notes - Only one matching comment is permitted. - Features without a comment are ignored. - Features with multiple comments are rejected. ``` -------------------------------- ### Append operation Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Implements the Append operation, which appends a value to a sequence. It checks the style of the sequence (block vs flow) and returns an error for flow sequences or non-sequence routes. For block sequences, it replaces the content in the document. ```rust Op::Append { value } => { let feature = route_to_feature_exact(&patch.route, document)?.ok_or_else(|| { Error::InvalidOperation(format!( "no existing sequence at {route:?}", route = patch.route )) })?; let style = Style::from_feature(&feature, document); match style { Style::BlockSequence => { let updated_feature = handle_block_sequence_append(document, &feature, value)?; // Replace the content in the document let mut result = content.to_string(); result.replace_range(&feature, &updated_feature); result } Style::FlowSequence => { return Err(Error::InvalidOperation(format!( "append operation is not permitted against flow sequence route: {:?}", patch.route ))); } _ => { return Err(Error::InvalidOperation(format!( "append operation is only permitted against sequence routes: {:?}", patch.route ))); } } } ``` -------------------------------- ### Op::EmplaceComment Source: https://docs.rs/yamlpatch/latest/yamlpatch/enum.Op.html Emplaces a comment at the given path. This is like `ReplaceComment`, but will insert a new comment if none exists. ```APIDOC ## Op::EmplaceComment ### Description Emplaces a comment at the given path. This is like `ReplaceComment`, but will insert a new comment if none exists. ### Variant `EmplaceComment { new: Cow<'doc, str> }` ### Fields - **new** (Cow<'doc, str>) - Required - The comment to emplace. ### Notes - If no comment exists, a new one is inserted. ``` -------------------------------- ### Remove operation Source: https://docs.rs/yamlpatch/latest/src/yamlpatch/lib.rs.html Implements the Remove operation, which deletes a value from the document. It returns an error if the route is empty (cannot remove root), otherwise computes the byte span to delete and removes it from the content string. ```rust Op::Remove => { if patch.route.is_empty() { return Err(Error::InvalidOperation( "Cannot remove root document".to_string(), )); } // Delegate to `yamlpath`, which computes the precise byte span // to delete based on the value's container kind. let span = document.removal_span(&patch.route)?; let mut result = content.to_string(); result.replace_range(span, ""); result } ``` -------------------------------- ### extract_leading_whitespace Source: https://docs.rs/yamlpatch/latest/yamlpatch/fn.extract_leading_whitespace.html Extracts leading whitespace from the beginning of the line containing the given feature. ```APIDOC ## Function extract_leading_whitespace ### Description Extracts leading whitespace from the beginning of the line containing the given feature. ### Signature ```rust pub fn extract_leading_whitespace<'doc>( doc: &'doc Document, feature: &Feature<'_>, ) -> &'doc str ``` ### Parameters - **doc** (`&'doc Document`) - The YAML document to search. - **feature** (`&Feature<'_>`) - The feature whose line's leading whitespace is to be extracted. ### Return Value - `&'doc str` - The leading whitespace of the line containing the feature. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.