yerba 0.2.1

YAML Editing and Refactoring with Better Accuracy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
<p align="center">
  <img src="assets/logo.png" alt="Yerba Logo" width="150px">
</p>

<h2 align="center">Yerba</h2>

<h4 align="center"><u>Y</u>AML <u>E</u>diting and <u>R</u>efactoring with <u>B</u>etter <u>A</u>ccuracy</h4>

<div align="center">A Rust CLI tool and Ruby library for editing YAML while preserving structure, comments, and format.</div><br/>

<p align="center">
  <a href="https://rubygems.org/gems/yerba"><img alt="Gem Version" src="https://img.shields.io/gem/v/yerba"></a>
  <a href="https://crates.io/crates/yerba"><img alt="Crates.io Version" src="https://img.shields.io/crates/v/yerba"></a>
  <a href="https://github.com/marcoroth/yerba/blob/main/LICENSE.txt"><img alt="License" src="https://img.shields.io/github/license/marcoroth/yerba"></a>
  <a href="https://github.com/marcoroth/yerba/issues"><img alt="Issues" src="https://img.shields.io/github/issues/marcoroth/yerba"></a>
</p>

<br/>

## 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](https://github.com/rubyevents/rubyevents) project.

## Installation

### CLI (standalone)

The `yerba` CLI is a standalone Rust binary with no Ruby dependency. Install it via Cargo:

```bash
cargo install yerba
```

### Rust Crate

Use `yerba` as a library in your Rust project:

```toml
[dependencies]
yerba = "0.2"
```

```rust
let mut document = yerba::parse_file("config.yml")?;
document.set("database.host", "0.0.0.0")?;
document.save()?;
```

### Ruby Gem

The Ruby gem bundles both the CLI binary and a native extension for programmatic access from Ruby:

```bash
gem install yerba
```

Or add it to your `Gemfile`:

```ruby
gem "yerba"
```

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](https://rustup.rs).

## 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.

```bash
yerba get config.yml "database.host"
yerba get videos.yml "[].title"
yerba get videos.yml "[0].title"
```

Use `--select` to pick specific fields from each item, and `--condition` to filter which items are returned:

```bash
yerba get videos.yml "[]" --select ".title,.speakers"
yerba get videos.yml "[]" --condition ".kind == keynote"
yerba get videos.yml "[]" --select ".title" --condition ".kind == keynote"
```

Glob patterns let you query across many files at once:

```bash
yerba get "data/**/videos.yml" "[].speakers[].name"
yerba get "data/**/videos.yml" "[]" --condition ".kind == keynote" --select ".id,.title"
```

Use `--raw` to output plain values (one per line) instead of JSON:

```bash
yerba get videos.yml "[]" --condition ".speakers contains Matz" --raw
```

### `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.

```bash
yerba set config.yml "database.host" "0.0.0.0"
yerba set videos.yml "[0].title" "New Title"
```

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:

```bash
yerba set config.yml "database.host" "0.0.0.0" --if-exists
yerba set "data/**/event.yml" "website" "" --if-exists
```

Use `--condition` to only apply the change when a sibling field matches:

```bash
yerba set config.yml "database.host" "0.0.0.0" --condition ".port == 5432"
```

### `insert`

Insert a new key into a map or a new item into a sequence. By default, new items are appended at the end.

```bash
yerba insert config.yml "database.ssl" true
yerba insert config.yml "tags" "yaml"
```

Control placement with `--before`, `--after`, or `--at`:

```bash
yerba insert config.yml "database.ssl" true --after "host"
yerba insert config.yml "database.ssl" true --before "port"
yerba insert config.yml "tags" "yaml" --at 0
yerba insert config.yml "tags" "yaml" --after "ruby"
```

For sequences of maps, use conditions to position relative to other items:

```bash
yerba insert speakers.yml "" "name: Bob" --after ".name == Alice"
yerba insert videos.yml "[0].speakers" "Diana" --before ".name == Charlie"
```

Use `--from` to read the value from another file (or stdin with `-`):

```bash
yerba insert videos.yml "" --from "new_talk.yml" --after ".id == first-talk"
```

### `delete`

Remove a key and its value from a map:

```bash
yerba delete config.yml "database.pool"
yerba delete videos.yml "[0].description"
```

Use `--dry-run` to preview the result without writing to the file:

```bash
yerba delete config.yml "database.pool" --dry-run
```

### `remove`

Remove a specific item from a sequence by its value:

```bash
yerba remove config.yml "tags" "rust"
yerba remove videos.yml "[0].speakers" "Alice"
```

### `rename`

Rename a key in a map while preserving its value and position:

```bash
yerba rename config.yml "database.host" "database.hostname"
yerba rename config.yml "database.host" "hostname"
```

### `move`

Move a sequence item to a new position. You can reference items by value, index, or condition:

```bash
yerba move config.yml "tags" "rust" --before "ruby"
yerba move config.yml "tags" "rust" --after "yaml"
yerba move config.yml "tags" 2 --to 0
yerba move videos.yml "" ".id == talk-2" --after ".id == talk-1"
```

### `move-key`

Move a key to a new position within a map:

```bash
yerba move-key config.yml "database.name" --to 0
yerba move-key config.yml "database.pool" --before "database.host"
yerba move-key config.yml "database.pool" --after "database.name"
```

### `sort`

Sort items in a sequence. For simple scalar sequences, no options are needed. For sequences of maps, use `--by` to specify sort fields. Append `:desc` for descending order:

```bash
yerba sort config.yml "tags"
yerba sort videos.yml --by "title"
yerba sort videos.yml --by "date:desc,title"
yerba sort videos.yml "[].speakers" --by "name"
```

### `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:

```bash
yerba sort-keys config.yml "database" "host,port,name,pool"
yerba sort-keys "data/**/event.yml" "" "id,title,kind,location"
yerba sort-keys "data/**/videos.yml" "[]" "id,title,speakers"
```

### `quote-style`

Enforce a consistent quote style across keys and/or values. Available styles are `plain`, `single`, and `double`:

```bash
yerba quote-style config.yml --values double
yerba quote-style config.yml --keys plain
yerba quote-style config.yml --keys plain --values double
```

Scope the operation to a specific selector:

```bash
yerba quote-style config.yml "[].speakers" --values plain
yerba quote-style "data/**/*.yml" --keys plain --values double
```

### `blank-lines`

Enforce a consistent number of blank lines between sequence entries:

```bash
yerba blank-lines videos.yml 1
yerba blank-lines videos.yml "[]" 1
yerba blank-lines config.yml "tags" 0
```

## `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):

```bash
yerba init
yerba apply
yerba check
```

Each rule specifies a file glob and a list of steps to run in order:

```yaml
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_style` Enforce quote style on keys and/or values, optionally scoped by path
- `sort_keys` Reorder keys to match a predefined list
- `sort` Sort sequence items by field(s)
- `blank_lines` Enforce blank lines between sequence entries
- `set` Set a value (supports conditions)
- `insert` Insert a new key or sequence item
- `delete` Remove a key (supports conditions)
- `rename` Rename a key
- `remove` Remove an item from a sequence
- `get` Read a value and store it as a variable for subsequent steps

This makes it easy to enforce project-wide YAML conventions in CI:

```bash
yerba check
```

## 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:

```ruby
require "yerba"

document = Yerba.parse_file("config.yml")
document = Yerba.parse("database:\n  host: localhost\n  port: 5432\n")
```

### Reading Values

Use `get` to retrieve the raw value at a path. Values are returned with their YAML types, strings, integers, booleans, and nil are all mapped to their Ruby equivalents:

```ruby
document.get("database.host")   # => "localhost"
document.get("database.port")   # => 5432
document.get("database.ssl")    # => false
```

### Structured Navigation

Use bracket notation to get typed wrapper objects (`Scalar`, `Map`, or `Sequence`) representing nodes in the document. These are live references, mutations flow back to the document.

You can use a full dot-path in a single bracket call, or chain brackets to navigate one level at a time:

```ruby
document["database.host"].value          # => "localhost"
document["database"]["host"].value       # => "localhost"
document["database"]["port"].value       # => 5432
```

The returned object type depends on what's at the path:

```ruby
document["database"]       # => Yerba::Map
document["database.host"]  # => Yerba::Scalar
document["tags"]           # => Yerba::Sequence
```

Scalars expose their value and quote style:

```ruby
scalar = document["database.host"]
scalar.value         # => "localhost"
scalar.quote_style   # => :double
```

### Mutations

Modify values in place. The original formatting is preserved:

```ruby
document["database"]["host"].value = "0.0.0.0"
document.set("database.port", 3306)
```

Insert new keys with positional control:

```ruby
document["database"].insert("ssl", true, after: "host")
```

Work with sequences using familiar Ruby patterns:

```ruby
tags = document["tags"]
tags << "yaml"
tags << { name: "Rust", version: "1.80" }
tags.remove("obsolete")
tags.sort(by: "name")
```

### Quote Style Control

Read and set the quote style on individual scalars:

```ruby
scalar = document["database.host"]
scalar.quote_style          # => :double
scalar.quote_style = :single
```

### Wildcard Access

Use `at_path` to access all items matching a wildcard selector:

```ruby
titles = document.at_path("[].title")
titles.each { |scalar| puts scalar.value }
```

### Collections

Operate on multiple files matching a glob pattern:

```ruby
collection = Yerba.files("data/**/videos.yml")

collection.each do |document|
  puts document.get("[0].title")
end

collection.apply! do |document|
  document.set("status", "published")
end
```

### Saving

Write changes back to the original file:

```ruby
document.save!
```

Or render the document as a string without writing to disk:

```ruby
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:

```bash
cd rust
cargo build
cargo test
```

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

```bash
cargo run -- get config.yml "database.host"
```

Or build a release binary:

```bash
cd rust
cargo build --release
./target/release/yerba --help
```

## License

The gem is available as open source under the terms of the [MIT License](https://github.com/marcoroth/yerba/blob/main/LICENSE.txt).