Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
What is Yerba?
Yerba is a lossless YAML editing tool. It lets you programmatically read, modify, and enforce formatting in YAML files while preserving their original structure, including comments, blank lines, quote styles, and key ordering.
Most YAML libraries parse a file into a data structure and serialize it back, discarding all formatting in the process. Yerba operates on the concrete syntax tree (CST), so your edits are surgical: only the targeted values change, and everything else stays exactly as it was.
Yerba is available as:
- A standalone CLI binary with zero runtime dependencies
- A Rust crate for embedding in Rust applications
- A Ruby gem for programmatic YAML editing from Ruby
Yerba was born out of the need to manage, validate, and enforce consistent formatting for hundreds of YAML data files in the RubyEvents.org project.
Installation
CLI (standalone)
The yerba CLI is a standalone Rust binary with no Ruby dependency. Install it via Cargo:
Rust Crate
Use yerba as a library in your Rust project:
[]
= "0.4"
let mut document = parse_file?;
document.set?;
document.save?; // saves to original path
document.save_to?; // saves to new path
Ruby Gem
The Ruby gem bundles both the CLI binary and a native extension for programmatic access from Ruby:
Or add it to your Gemfile:
The gem ships with precompiled binaries for macOS and Linux.
If no precompiled binary is available for your platform, it will compile from source automatically, which requires a Rust toolchain.
CLI Usage
The yerba CLI follows a consistent pattern:
yerba <command> <file> <selector> [value] [options]
Selectors use dot-notation for nested keys, brackets for array access, and support glob patterns for operating on multiple files at once.
Selectors
Selectors let you address any node in a YAML document:
| Pattern | Meaning | Example |
|---|---|---|
key |
A single key | "database.host" |
key.nested |
Nested key path | "database.settings.pool" |
[] |
All items in array | "[].title" |
[N] |
Item at index | "[0].title" |
[].key[].nested |
Nested array access | "[].speakers[].name" |
Conditions
Conditions filter which items a command operates on:
| Syntax | Meaning | Example |
|---|---|---|
.key == value |
Equality | ".kind == keynote" |
.key != value |
Inequality | ".status != draft" |
.key contains val |
Substring or member | ".title contains Ruby" |
.key not_contains val |
Negated contains | ".title not_contains test" |
get
Retrieve values from YAML files. Supports single values, array traversal, glob patterns across multiple files, conditions for filtering, and field selection.
Use --select to pick specific fields from each item, and --condition to filter which items are returned:
Glob patterns let you query across many files at once:
Use --raw to output plain values (one per line) instead of JSON:
set
Update an existing value at a path. The original quote style is preserved automatically, if a value was double-quoted before, it stays double-quoted after the edit.
Use --if-exists to only set the value when the path already exists, or --if-missing to only set it when the path does not exist:
Use --condition to only apply the change when a sibling field matches:
Use --all to update all nodes matching a wildcard selector:
insert
Insert a new key into a map or a new item into a sequence. By default, new items are appended at the end.
Control placement with --before, --after, or --at:
For sequences of maps, use conditions to position relative to other items:
Use --from to read the value from another file (or stdin with -):
delete
Remove a key and its value from a map:
Use --dry-run to preview the result without writing to the file:
remove
Remove a specific item from a sequence by its value:
rename
Rename a key in a map while preserving its value and position:
move
Move a sequence item to a new position. You can reference items by value, index, or condition:
move-key
Move a key to a new position within a map:
sort
Sort items in a sequence. For simple scalar sequences, no options are needed. For sequences of maps, use --by to specify the sort field. Use --order desc for descending. Repeat --by and --order for tie-breakers:
Use --order with a comma-separated list to specify an explicit custom order. All items must be listed:
This is useful for reordering items in a specific sequence (e.g., conference schedule order, priority lists) or when an LLM agent needs to rearrange items programmatically.
sort-keys
Reorder the keys in a map to match a predefined order. If any key in the document is not present in the order list, the command aborts with an error, this ensures you account for every field:
quote-style
Enforce a consistent quote style across keys and/or values:
Scope the operation to a specific selector:
Use block scalar styles to enforce multiline formatting on specific fields:
Key styles (--keys):
| Style | Symbol | Example |
|---|---|---|
plain |
— | host: value |
single |
' |
'host': value |
double |
" |
"host": value |
Value styles (--values):
| Style | Symbol | Example | Behavior | |
|---|---|---|---|---|
plain |
— | host: localhost |
Unquoted | |
single |
' |
host: 'localhost' |
Single-quoted | |
double |
" |
host: "localhost" |
Double-quoted, supports \n escapes |
|
literal |
`\ | -` | Preserves newlines | Strip trailing newline |
literal-clip |
`\ | ` | Preserves newlines | Keep one trailing newline |
literal-keep |
`\ | +` | Preserves newlines | Keep all trailing newlines |
folded |
>- |
Folds newlines to spaces | Strip trailing newline | |
folded-clip |
> |
Folds newlines to spaces | Keep one trailing newline | |
folded-keep |
>+ |
Folds newlines to spaces | Keep all trailing newlines |
Block scalars are only converted when scoped to a specific selector. An unscoped --values double will not touch existing block scalars.
blank-lines
Enforce a consistent number of blank lines between sequence entries:
directives
Add or remove the document start marker (---):
unique
Find or remove duplicate items in a sequence. Use --by to specify which field determines uniqueness:
By default, duplicates are reported but not removed. Use --remove to remove them (keeps the first occurrence):
location
Show the location (line, column, byte offset) of a selector in a YAML file:
Output:
schema
Validate YAML files against a JSON schema:
Use --path to scope validation to a specific selector (e.g. validate each item in an array):
selectors
Show all valid selectors for a YAML file. Useful for discovering the structure of a file and knowing which selectors you can use with other commands:
Output:
database
database.host
database.port
tags
tags[]
For sequences of objects:
Output:
[]
[].id
[].title
[].speakers
[].speakers[]
[].speakers[].name
[].speakers[].slug
[].video_id
[].video_provider
Pass a selector to scope the output to a specific subtree:
Works with glob patterns to show the union of selectors across multiple files:
Yerbafile
A Yerbafile is a YAML configuration file that defines formatting and editing rules as pipelines of operations that are applied to your files across your project.
Use yerba init to create one, then yerba apply to apply all rules, or yerba check to verify compliance (exits with code 1 if files would change):
Each rule specifies a file glob and a list of steps to run in order:
rules:
- files: "config/**/*.yml"
pipeline:
- quote_style:
key_style: plain
value_style: double
- sort_keys:
path: ""
order:
- id
- title
- description
- blank_lines:
count: 1
- files: "data/speakers.yml"
pipeline:
- quote_style:
key_style: plain
value_style: double
- sort_keys:
path: ""
order:
- name
- slug
- github
- twitter
- website
- sort:
path: ""
by: name
Available pipeline steps:
quote_styleEnforce quote style on keys and/or values, optionally scoped by pathsort_keysReorder keys to match a predefined listsortSort sequence items by field(s)blank_linesEnforce blank lines between sequence entriessetSet a value (supports conditions)insertInsert a new key or sequence itemdeleteRemove a key (supports conditions)renameRename a keyremoveRemove an item from a sequencedirectivesAdd or remove the document start marker (---)uniqueFind or remove duplicate items in a sequenceschemaValidate against a JSON schema (with optionalpathfor scoping)getRead a value and store it as a variable for subsequent steps
This makes it easy to enforce project-wide YAML conventions in CI:
Ruby API
Yerba includes a native C extension (backed by the same Rust core) that provides a full Ruby API for YAML editing.
Parsing
Create a document from a file path or from a string:
document = Yerba.parse_file()
document = Yerba.parse()
Reading Values
Use bracket notation ([]) to navigate the document. Returns typed node objects (Scalar, Map, or Sequence) that are live references — mutations flow back to the document.
All access methods ([], fetch, dig, value_at) accept full selector strings like "database.host", "[0].title", or "[].speakers[].name". In the examples below we prefer the more idiomatic chained bracket style, but the two forms are equivalent:
document[][].value # => "localhost"
document[].value # => "localhost" (same thing)
The returned object type depends on what's at the path:
document[] # => Yerba::Map
document[][] # => Yerba::Scalar
document[] # => Yerba::Sequence
Scalars expose their value and quote style:
scalar = document[][]
scalar.value # => "localhost"
scalar.quote_style # => :double
Use fetch for strict access, it raises Yerba::SelectorNotFoundError with "did you mean?" suggestions if the selector doesn't exist:
document.fetch() # => Yerba::Scalar
document.fetch() # => raises SelectorNotFoundError: ... Did you mean: database.host?
Use dig to traverse multiple levels, returning nil for missing paths:
document.dig(, ) # => Yerba::Scalar
document.dig(, 0, ) # => Yerba::Scalar
document.dig(, ) # => nil
Use value_at to get the plain Ruby value (String, Integer, Hash, Array, etc.) instead of a node object:
document.value_at() # => "localhost"
document.value_at() # => 5432
document.value_at() # => {"host" => "localhost", "port" => 5432}
document.value_at() # => ["First Talk", "Second Talk"]
Summary of access methods:
| Method | Not found | Returns |
|---|---|---|
[] |
nil |
Scalar / Map / Sequence node |
fetch |
raises SelectorNotFoundError |
Scalar / Map / Sequence node |
dig |
nil |
Scalar / Map / Sequence node |
value_at |
nil |
plain Ruby value |
Mutations
Modify values in place. The original formatting is preserved:
document[][].value =
document.set(, 3306)
Set all matching nodes at once with all: true:
document.set(, , all: true)
Insert new keys with positional control:
document[].insert(, true, after: )
Work with sequences using familiar Ruby patterns:
tags = document[]
tags <<
tags << { name: , version: }
tags.remove()
Sorting
Sort sequences in place. Works on both the document and sequence level:
document.sort(by: :name)
document.sort(by: :name, order: :desc)
document.sort(by: :name, order: [, , ])
document.sort()
document.sort(, order: :desc)
document.sort(, order: [, , ])
The by: option accepts symbols, strings, or dot-prefixed strings (:name, "name", ".name").
Querying
Find and filter items in sequences with find_by, where, and pluck:
document.find_by(name: )
document.where(role: )
document.pluck(:name)
document.find_by(speakers: { name: })
document.where(tags: [])
document.find_by(: )
These methods work on Document (delegates to root), Sequence, and Collection (searches across files):
collection = Yerba.files()
collection.find_by(name: )
collection.where(kind: )
collection.pluck(:name)
Schema Validation
Validate documents against JSON schemas from Ruby:
schema = {
type: ,
properties: { name: { type: }, slug: { type: } },
required: [, ]
}
document.valid?(schema) # => true/false
document.valid?(schema, selector: ) # validate each array item
errors = document.validate(schema, selector: )
errors.each do
puts
end
Also accepts a JSON string:
document.valid?()
Quote Style Control
Read and set the quote style on individual scalars:
scalar = document[][]
scalar.quote_style # => :double
scalar.quote_style = :single
Location
Get the precise location (line, column, byte offset) of any selector in a document:
loc = document[0][].location
loc.start_line # => 2
loc.start_column # => 9
loc.end_line # => 2
loc.end_column # => 19
loc.start_offset # => 22
loc.end_offset # => 32
You can also get a location by selector string:
document.location()
The above is the same as:
document[0][].location
document[].location
Omit the selector to get the whole document's location:
document.location # => #<Yerba::Location start_line=1, ...>
Returns nil for non-existent selectors. Use locations for wildcard selectors that match multiple nodes:
locs = document.locations()
locs.each { puts }
# line 2
# line 4
document.locations()
document.locations()
Wildcard Access
When [] receives a wildcard selector (containing []), it returns an array of nodes instead of a single node:
document[] # => [Yerba::Scalar, Yerba::Scalar, ...]
document[] # => [Yerba::Scalar, Yerba::Scalar, ...]
document[] # => [Yerba::Scalar, Yerba::Scalar, ...]
document[].each { puts scalar.value }
document[].each { scalar.value = }
Collections
Operate on multiple files matching a glob pattern:
collection = Yerba.files()
collection.each do
puts document[0][].value
end
collection.find_by(name: )
collection.where(kind: )
collection.pluck(:name)
collection.apply! do
document.set(, )
end
Use Collection.get to retrieve nodes across all matching files in parallel. Returns Scalar, Map, or Sequence objects with file_path, line, and selector:
speakers = Yerba::Collection.get(, )
speakers.each do
puts
end
maps = Yerba::Collection.get(, )
maps.first.class
# => Yerba::Map
sequences = Yerba::Collection.get(, )
sequences.first.class
# => Yerba::Sequence
Nodes returned by Collection.get lazily load their Document on first mutation, so reads are fast and writes work transparently:
scalars = Yerba::Collection.get(, )
scalars.first.value =
scalars.first.document.save!
Saving
Write changes back to the original file:
document.save!
Or render the document as a string without writing to disk:
document.to_s
Development
After checking out the repo, run bundle install to install Ruby dependencies, then bundle exec rake test to run the test suite.
Building from source
The Rust core is in the rust/ directory, with a workspace Cargo.toml at the root so all cargo commands work from the project root:
The C extension (for the Ruby API) is compiled via ext/yerba/extconf.rb which invokes cargo build and links against the resulting static library. Running bundle exec rake compile will build both the Rust library and the C extension.
Running the CLI locally
Or build a release binary:
License
The gem is available as open source under the terms of the MIT License.