yerba 0.2.0-aarch64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.md +528 -0
  4. data/exe/yerba +6 -0
  5. data/ext/yerba/extconf.rb +111 -0
  6. data/ext/yerba/yerba.c +752 -0
  7. data/lib/yerba/3.2/yerba.so +0 -0
  8. data/lib/yerba/3.3/yerba.so +0 -0
  9. data/lib/yerba/3.4/yerba.so +0 -0
  10. data/lib/yerba/4.0/yerba.so +0 -0
  11. data/lib/yerba/collection.rb +31 -0
  12. data/lib/yerba/document.rb +59 -0
  13. data/lib/yerba/formatting.rb +18 -0
  14. data/lib/yerba/location.rb +5 -0
  15. data/lib/yerba/map.rb +166 -0
  16. data/lib/yerba/scalar.rb +85 -0
  17. data/lib/yerba/sequence.rb +182 -0
  18. data/lib/yerba/version.rb +5 -0
  19. data/lib/yerba.rb +131 -0
  20. data/rust/Cargo.lock +805 -0
  21. data/rust/Cargo.toml +36 -0
  22. data/rust/build.rs +11 -0
  23. data/rust/cbindgen.toml +27 -0
  24. data/rust/rustfmt.toml +2 -0
  25. data/rust/src/commands/apply.rs +5 -0
  26. data/rust/src/commands/blank_lines.rs +58 -0
  27. data/rust/src/commands/check.rs +5 -0
  28. data/rust/src/commands/delete.rs +35 -0
  29. data/rust/src/commands/get.rs +194 -0
  30. data/rust/src/commands/init.rs +89 -0
  31. data/rust/src/commands/insert.rs +106 -0
  32. data/rust/src/commands/mate.rs +55 -0
  33. data/rust/src/commands/mod.rs +349 -0
  34. data/rust/src/commands/move_item.rs +54 -0
  35. data/rust/src/commands/move_key.rs +87 -0
  36. data/rust/src/commands/quote_style.rs +62 -0
  37. data/rust/src/commands/remove.rs +35 -0
  38. data/rust/src/commands/rename.rs +37 -0
  39. data/rust/src/commands/set.rs +59 -0
  40. data/rust/src/commands/sort.rs +52 -0
  41. data/rust/src/commands/sort_keys.rs +62 -0
  42. data/rust/src/commands/version.rs +8 -0
  43. data/rust/src/document.rs +2237 -0
  44. data/rust/src/error.rs +45 -0
  45. data/rust/src/ffi.rs +991 -0
  46. data/rust/src/json.rs +128 -0
  47. data/rust/src/lib.rs +29 -0
  48. data/rust/src/main.rs +72 -0
  49. data/rust/src/quote_style.rs +42 -0
  50. data/rust/src/selector.rs +241 -0
  51. data/rust/src/syntax.rs +262 -0
  52. data/rust/src/yaml_writer.rs +89 -0
  53. data/rust/src/yerbafile.rs +475 -0
  54. data/sig/yerba.rbs +3 -0
  55. data/yerba.gemspec +52 -0
  56. metadata +108 -0
@@ -0,0 +1,2237 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use rowan::ast::AstNode;
5
+ use rowan::TextRange;
6
+
7
+ use yaml_parser::ast::{BlockMap, BlockSeq, Root};
8
+ use yaml_parser::{SyntaxKind, SyntaxNode, SyntaxToken};
9
+
10
+ use crate::error::YerbaError;
11
+ use crate::QuoteStyle;
12
+
13
+ use crate::syntax::{
14
+ extract_scalar, extract_scalar_text, find_entry_by_key, find_scalar_token, format_scalar_value, is_map_key,
15
+ is_yaml_non_string, preceding_whitespace_indent, preceding_whitespace_token, removal_range, unescape_double_quoted,
16
+ unescape_single_quoted, ScalarValue,
17
+ };
18
+
19
+ #[derive(Debug, Clone)]
20
+ pub struct SortField {
21
+ pub path: String,
22
+ pub ascending: bool,
23
+ }
24
+
25
+ impl SortField {
26
+ pub fn asc(path: &str) -> Self {
27
+ SortField {
28
+ path: path.to_string(),
29
+ ascending: true,
30
+ }
31
+ }
32
+
33
+ pub fn desc(path: &str) -> Self {
34
+ SortField {
35
+ path: path.to_string(),
36
+ ascending: false,
37
+ }
38
+ }
39
+
40
+ pub fn parse(input: &str) -> Self {
41
+ if let Some((path, direction)) = input.rsplit_once(':') {
42
+ match direction {
43
+ "desc" | "descending" => SortField::desc(path),
44
+ _ => SortField::asc(input),
45
+ }
46
+ } else {
47
+ SortField::asc(input)
48
+ }
49
+ }
50
+
51
+ pub fn parse_list(input: &str) -> Vec<Self> {
52
+ input.split(',').map(|field| SortField::parse(field.trim())).collect()
53
+ }
54
+ }
55
+
56
+ #[derive(Debug)]
57
+ pub enum InsertPosition {
58
+ At(usize),
59
+ Last,
60
+ Before(String),
61
+ After(String),
62
+ BeforeCondition(String),
63
+ AfterCondition(String),
64
+ FromSortOrder(Vec<String>),
65
+ }
66
+
67
+ #[derive(Debug)]
68
+ pub struct Document {
69
+ root: SyntaxNode,
70
+ path: Option<PathBuf>,
71
+ }
72
+
73
+ impl Document {
74
+ pub fn parse(source: &str) -> Result<Self, YerbaError> {
75
+ let tree = yaml_parser::parse(source).map_err(|error| YerbaError::ParseError(format!("{}", error)))?;
76
+
77
+ Ok(Document { root: tree, path: None })
78
+ }
79
+
80
+ pub fn parse_file(path: impl AsRef<Path>) -> Result<Self, YerbaError> {
81
+ let path = path.as_ref();
82
+ let source = fs::read_to_string(path)?;
83
+
84
+ let mut document = Self::parse(&source)?;
85
+
86
+ document.path = Some(path.to_path_buf());
87
+
88
+ Ok(document)
89
+ }
90
+
91
+ pub fn get(&self, dot_path: &str) -> Option<String> {
92
+ if dot_path.contains('[') {
93
+ return self.get_all(dot_path).into_iter().next();
94
+ }
95
+
96
+ let current_node = self.navigate(dot_path).ok()?;
97
+
98
+ extract_scalar_text(&current_node)
99
+ }
100
+
101
+ pub fn get_all(&self, dot_path: &str) -> Vec<String> {
102
+ self
103
+ .navigate_all(dot_path)
104
+ .iter()
105
+ .filter_map(extract_scalar_text)
106
+ .collect()
107
+ }
108
+
109
+ pub fn get_typed(&self, dot_path: &str) -> Option<ScalarValue> {
110
+ if crate::selector::Selector::parse(dot_path).has_wildcard() {
111
+ return self.get_all_typed(dot_path).into_iter().next();
112
+ }
113
+
114
+ let current_node = self.navigate(dot_path).ok()?;
115
+
116
+ if current_node
117
+ .descendants()
118
+ .any(|child| child.kind() == SyntaxKind::BLOCK_MAP || child.kind() == SyntaxKind::BLOCK_SEQ)
119
+ {
120
+ return None;
121
+ }
122
+
123
+ extract_scalar(&current_node)
124
+ }
125
+
126
+ pub fn get_all_typed(&self, dot_path: &str) -> Vec<ScalarValue> {
127
+ self
128
+ .navigate_all(dot_path)
129
+ .iter()
130
+ .filter(|node| {
131
+ !node
132
+ .descendants()
133
+ .any(|child| child.kind() == SyntaxKind::BLOCK_MAP || child.kind() == SyntaxKind::BLOCK_SEQ)
134
+ })
135
+ .filter_map(extract_scalar)
136
+ .collect()
137
+ }
138
+
139
+ pub fn get_value(&self, dot_path: &str) -> Option<serde_yaml::Value> {
140
+ if dot_path.is_empty() {
141
+ return Some(node_to_yaml_value(&self.root));
142
+ }
143
+
144
+ let nodes = self.navigate_all(dot_path);
145
+
146
+ if nodes.is_empty() {
147
+ return None;
148
+ }
149
+
150
+ if nodes.len() == 1 {
151
+ return Some(node_to_yaml_value(&nodes[0]));
152
+ }
153
+
154
+ let values: Vec<serde_yaml::Value> = nodes.iter().map(node_to_yaml_value).collect();
155
+
156
+ Some(serde_yaml::Value::Sequence(values))
157
+ }
158
+
159
+ pub fn get_values(&self, dot_path: &str) -> Vec<serde_yaml::Value> {
160
+ self.navigate_all(dot_path).iter().map(node_to_yaml_value).collect()
161
+ }
162
+
163
+ pub fn filter(&self, dot_path: &str, condition: &str) -> Vec<serde_yaml::Value> {
164
+ self
165
+ .navigate_all(dot_path)
166
+ .iter()
167
+ .filter(|node| self.evaluate_condition_on_node(node, condition))
168
+ .map(node_to_yaml_value)
169
+ .collect()
170
+ }
171
+
172
+ fn evaluate_condition_on_node(&self, node: &SyntaxNode, condition: &str) -> bool {
173
+ let condition = condition.trim();
174
+
175
+ let (left, operator, right) = match parse_condition(condition) {
176
+ Some(parts) => parts,
177
+ None => return false,
178
+ };
179
+
180
+ let path = crate::selector::Selector::parse(&left);
181
+
182
+ if !path.is_relative() {
183
+ return false;
184
+ }
185
+
186
+ let target_nodes = navigate_from_node(node, &path.to_selector_string());
187
+ let values: Vec<String> = target_nodes.iter().filter_map(extract_scalar_text).collect();
188
+
189
+ match operator {
190
+ "==" => values.iter().any(|value| value == &right),
191
+ "!=" => values.iter().all(|value| value != &right),
192
+ "contains" => {
193
+ if values.iter().any(|value| value == &right || value.contains(&right)) {
194
+ return true;
195
+ }
196
+
197
+ for node in &target_nodes {
198
+ if let Some(sequence) = node.descendants().find_map(BlockSeq::cast) {
199
+ for entry in sequence.entries() {
200
+ if let Some(text) = entry.flow().and_then(|flow| extract_scalar_text(flow.syntax())) {
201
+ if text == right {
202
+ return true;
203
+ }
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ false
210
+ }
211
+ "not_contains" => {
212
+ for node in &target_nodes {
213
+ if let Some(sequence) = node.descendants().find_map(BlockSeq::cast) {
214
+ for entry in sequence.entries() {
215
+ if let Some(text) = entry.flow().and_then(|flow| extract_scalar_text(flow.syntax())) {
216
+ if text == right {
217
+ return false;
218
+ }
219
+ }
220
+ }
221
+ }
222
+ }
223
+
224
+ !values.iter().any(|value| value == &right || value.contains(&right))
225
+ }
226
+ _ => false,
227
+ }
228
+ }
229
+
230
+ pub fn exists(&self, dot_path: &str) -> bool {
231
+ if dot_path.contains('[') {
232
+ return !self.navigate_all(dot_path).is_empty();
233
+ }
234
+
235
+ self.get(dot_path).is_some()
236
+ }
237
+
238
+ pub fn evaluate_condition(&self, parent_path: &str, condition: &str) -> bool {
239
+ let condition = condition.trim();
240
+
241
+ let (left, operator, right) = match parse_condition(condition) {
242
+ Some(parts) => parts,
243
+ None => return false,
244
+ };
245
+
246
+ let path = crate::selector::Selector::parse(&left);
247
+
248
+ let full_path = if path.is_relative() {
249
+ let path_string = path.to_selector_string();
250
+
251
+ if parent_path.is_empty() {
252
+ path_string
253
+ } else {
254
+ format!("{}.{}", parent_path, path_string)
255
+ }
256
+ } else {
257
+ path.to_selector_string()
258
+ };
259
+
260
+ let has_brackets = crate::selector::Selector::parse(&full_path).has_brackets();
261
+
262
+ match operator {
263
+ "==" => {
264
+ if has_brackets {
265
+ self.get_all(&full_path).iter().any(|value| value == &right)
266
+ } else {
267
+ self.get(&full_path).unwrap_or_default() == right
268
+ }
269
+ }
270
+ "!=" => {
271
+ if has_brackets {
272
+ self.get_all(&full_path).iter().all(|value| value != &right)
273
+ } else {
274
+ self.get(&full_path).unwrap_or_default() != right
275
+ }
276
+ }
277
+ "contains" => {
278
+ if has_brackets {
279
+ self
280
+ .get_all(&full_path)
281
+ .iter()
282
+ .any(|value| value == &right || value.contains(&right))
283
+ } else {
284
+ let items = self.get_sequence_values(&full_path);
285
+
286
+ if !items.is_empty() {
287
+ items.iter().any(|item| item == &right)
288
+ } else {
289
+ self
290
+ .get(&full_path)
291
+ .map(|value| value.contains(&right))
292
+ .unwrap_or(false)
293
+ }
294
+ }
295
+ }
296
+ "not_contains" => {
297
+ if has_brackets {
298
+ self
299
+ .get_all(&full_path)
300
+ .iter()
301
+ .all(|value| value != &right && !value.contains(&right))
302
+ } else {
303
+ let items = self.get_sequence_values(&full_path);
304
+
305
+ if !items.is_empty() {
306
+ !items.iter().any(|item| item == &right)
307
+ } else {
308
+ self
309
+ .get(&full_path)
310
+ .map(|value| !value.contains(&right))
311
+ .unwrap_or(true)
312
+ }
313
+ }
314
+ }
315
+ _ => false,
316
+ }
317
+ }
318
+
319
+ pub fn get_sequence_values(&self, dot_path: &str) -> Vec<String> {
320
+ let current_node = match self.navigate(dot_path) {
321
+ Ok(node) => node,
322
+ Err(_) => return Vec::new(),
323
+ };
324
+
325
+ let sequence = match current_node.descendants().find_map(BlockSeq::cast) {
326
+ Some(sequence) => sequence,
327
+ None => return Vec::new(),
328
+ };
329
+
330
+ sequence
331
+ .entries()
332
+ .filter_map(|entry| entry.flow().and_then(|flow| extract_scalar_text(flow.syntax())))
333
+ .collect()
334
+ }
335
+
336
+ pub fn set(&mut self, dot_path: &str, value: &str) -> Result<(), YerbaError> {
337
+ let current_node = self.navigate(dot_path)?;
338
+
339
+ if let Some(block_scalar) = current_node
340
+ .descendants()
341
+ .find(|node| node.kind() == SyntaxKind::BLOCK_SCALAR)
342
+ {
343
+ let new_text = if value.is_empty() {
344
+ "\"\"".to_string()
345
+ } else if value.contains('\n') {
346
+ format!("|-\n {}", value.replace('\n', "\n "))
347
+ } else {
348
+ format!("\"{}\"", value.replace('"', "\\\""))
349
+ };
350
+
351
+ let range = block_scalar.text_range();
352
+
353
+ return self.apply_edit(range, &new_text);
354
+ }
355
+
356
+ let scalar_token =
357
+ find_scalar_token(&current_node).ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
358
+
359
+ let new_text = format_scalar_value(value, scalar_token.kind());
360
+
361
+ self.replace_token(&scalar_token, &new_text)
362
+ }
363
+
364
+ pub fn set_scalar_style(&mut self, dot_path: &str, style: &QuoteStyle) -> Result<(), YerbaError> {
365
+ let current_node = self.navigate(dot_path)?;
366
+ let scalar_token =
367
+ find_scalar_token(&current_node).ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
368
+
369
+ let current_kind = scalar_token.kind();
370
+ let target_kind = style.to_syntax_kind();
371
+
372
+ if current_kind == target_kind {
373
+ return Ok(());
374
+ }
375
+
376
+ let raw_value = match current_kind {
377
+ SyntaxKind::DOUBLE_QUOTED_SCALAR => {
378
+ let text = scalar_token.text();
379
+ unescape_double_quoted(&text[1..text.len() - 1])
380
+ }
381
+
382
+ SyntaxKind::SINGLE_QUOTED_SCALAR => {
383
+ let text = scalar_token.text();
384
+ unescape_single_quoted(&text[1..text.len() - 1])
385
+ }
386
+
387
+ SyntaxKind::PLAIN_SCALAR => scalar_token.text().to_string(),
388
+
389
+ _ => return Ok(()),
390
+ };
391
+
392
+ let new_text = format_scalar_value(&raw_value, target_kind);
393
+
394
+ self.replace_token(&scalar_token, &new_text)
395
+ }
396
+
397
+ pub fn set_plain(&mut self, dot_path: &str, value: &str) -> Result<(), YerbaError> {
398
+ let current_node = self.navigate(dot_path)?;
399
+
400
+ if let Some(block_scalar) = current_node
401
+ .descendants()
402
+ .find(|node| node.kind() == SyntaxKind::BLOCK_SCALAR)
403
+ {
404
+ let range = block_scalar.text_range();
405
+ return self.apply_edit(range, value);
406
+ }
407
+
408
+ let scalar_token =
409
+ find_scalar_token(&current_node).ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
410
+
411
+ self.replace_token(&scalar_token, value)
412
+ }
413
+
414
+ pub fn append(&mut self, dot_path: &str, value: &str) -> Result<(), YerbaError> {
415
+ self.insert_into(dot_path, value, InsertPosition::Last)
416
+ }
417
+
418
+ pub fn insert_into(&mut self, dot_path: &str, value: &str, position: InsertPosition) -> Result<(), YerbaError> {
419
+ Self::validate_path(dot_path)?;
420
+
421
+ if let Ok(current_node) = self.navigate(dot_path) {
422
+ if current_node.descendants().find_map(BlockSeq::cast).is_some() {
423
+ return self.insert_sequence_item(dot_path, value, position);
424
+ }
425
+ }
426
+
427
+ let (parent_path, key) = dot_path.rsplit_once('.').unwrap_or(("", dot_path));
428
+
429
+ self.insert_map_key(parent_path, key, value, position)
430
+ }
431
+
432
+ fn insert_sequence_item(&mut self, dot_path: &str, value: &str, position: InsertPosition) -> Result<(), YerbaError> {
433
+ let current_node = self.navigate(dot_path)?;
434
+
435
+ let sequence = current_node
436
+ .descendants()
437
+ .find_map(BlockSeq::cast)
438
+ .ok_or_else(|| YerbaError::NotASequence(dot_path.to_string()))?;
439
+
440
+ let entries: Vec<_> = sequence.entries().collect();
441
+
442
+ if entries.is_empty() {
443
+ return Err(YerbaError::PathNotFound(dot_path.to_string()));
444
+ }
445
+
446
+ let indent = entries
447
+ .get(1)
448
+ .or(entries.first())
449
+ .map(|entry| preceding_whitespace_indent(entry.syntax()))
450
+ .unwrap_or_default();
451
+
452
+ let new_item = if value.contains('\n') {
453
+ let item_indent = format!("{} ", indent);
454
+ let lines: Vec<&str> = value.split('\n').collect();
455
+
456
+ let min_indent = lines
457
+ .iter()
458
+ .skip(1)
459
+ .filter(|line| !line.trim().is_empty())
460
+ .map(|line| line.len() - line.trim_start().len())
461
+ .min()
462
+ .unwrap_or(0);
463
+
464
+ let indented: Vec<String> = lines
465
+ .iter()
466
+ .enumerate()
467
+ .map(|(index, line)| {
468
+ if index == 0 {
469
+ line.to_string()
470
+ } else if line.trim().is_empty() {
471
+ String::new()
472
+ } else {
473
+ let relative = &line[min_indent..];
474
+ format!("{}{}", item_indent, relative)
475
+ }
476
+ })
477
+ .collect();
478
+
479
+ format!("- {}", indented.join("\n"))
480
+ } else {
481
+ format!("- {}", value)
482
+ };
483
+
484
+ match position {
485
+ InsertPosition::Last => {
486
+ let last_entry = entries.last().unwrap();
487
+ let new_text = format!("\n{}{}", indent, new_item);
488
+
489
+ self.insert_after_node(last_entry.syntax(), &new_text)
490
+ }
491
+
492
+ InsertPosition::At(index) => {
493
+ if index >= entries.len() {
494
+ let last_entry = entries.last().unwrap();
495
+ let new_text = format!("\n{}{}", indent, new_item);
496
+
497
+ self.insert_after_node(last_entry.syntax(), &new_text)
498
+ } else {
499
+ let target_entry = &entries[index];
500
+ let target_range = target_entry.syntax().text_range();
501
+ let replacement = format!("{}\n{}", new_item, indent);
502
+ let insert_range = TextRange::new(target_range.start(), target_range.start());
503
+
504
+ self.apply_edit(insert_range, &replacement)
505
+ }
506
+ }
507
+
508
+ InsertPosition::Before(target_value) => {
509
+ let target_entry = entries
510
+ .iter()
511
+ .find(|entry| {
512
+ entry
513
+ .flow()
514
+ .and_then(|flow| extract_scalar_text(flow.syntax()))
515
+ .map(|text| text == target_value)
516
+ .unwrap_or(false)
517
+ })
518
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} item '{}'", dot_path, target_value)))?;
519
+
520
+ let target_range = target_entry.syntax().text_range();
521
+ let replacement = format!("{}\n{}", new_item, indent);
522
+ let insert_range = TextRange::new(target_range.start(), target_range.start());
523
+
524
+ self.apply_edit(insert_range, &replacement)
525
+ }
526
+
527
+ InsertPosition::After(target_value) => {
528
+ let target_entry = entries
529
+ .iter()
530
+ .find(|entry| {
531
+ entry
532
+ .flow()
533
+ .and_then(|flow| extract_scalar_text(flow.syntax()))
534
+ .map(|text| text == target_value)
535
+ .unwrap_or(false)
536
+ })
537
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} item '{}'", dot_path, target_value)))?;
538
+
539
+ let new_text = format!("\n{}{}", indent, new_item);
540
+
541
+ self.insert_after_node(target_entry.syntax(), &new_text)
542
+ }
543
+
544
+ InsertPosition::BeforeCondition(condition) => {
545
+ let target_entry = entries
546
+ .iter()
547
+ .find(|entry| self.evaluate_condition_on_node(entry.syntax(), &condition))
548
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} condition '{}'", dot_path, condition)))?;
549
+
550
+ let target_range = target_entry.syntax().text_range();
551
+ let replacement = format!("{}\n{}", new_item, indent);
552
+ let insert_range = TextRange::new(target_range.start(), target_range.start());
553
+
554
+ self.apply_edit(insert_range, &replacement)
555
+ }
556
+
557
+ InsertPosition::AfterCondition(condition) => {
558
+ let target_entry = entries
559
+ .iter()
560
+ .find(|entry| self.evaluate_condition_on_node(entry.syntax(), &condition))
561
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} condition '{}'", dot_path, condition)))?;
562
+
563
+ let new_text = format!("\n{}{}", indent, new_item);
564
+
565
+ self.insert_after_node(target_entry.syntax(), &new_text)
566
+ }
567
+
568
+ InsertPosition::FromSortOrder(_) => {
569
+ let last_entry = entries.last().unwrap();
570
+ let new_text = format!("\n{}{}", indent, new_item);
571
+
572
+ self.insert_after_node(last_entry.syntax(), &new_text)
573
+ }
574
+ }
575
+ }
576
+
577
+ fn insert_map_key(
578
+ &mut self,
579
+ dot_path: &str,
580
+ key: &str,
581
+ value: &str,
582
+ position: InsertPosition,
583
+ ) -> Result<(), YerbaError> {
584
+ let current_node = self.navigate(dot_path)?;
585
+
586
+ let map = current_node
587
+ .descendants()
588
+ .find_map(BlockMap::cast)
589
+ .ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
590
+
591
+ let entries: Vec<_> = map.entries().collect();
592
+
593
+ if entries.is_empty() {
594
+ let indent = preceding_whitespace_indent(map.syntax());
595
+ let new_entry = format!("\n{}{}: {}", indent, key, value);
596
+
597
+ return self.insert_after_node(map.syntax(), &new_entry);
598
+ }
599
+
600
+ if find_entry_by_key(&map, key).is_some() {
601
+ return Err(YerbaError::ParseError(format!(
602
+ "key '{}' already exists at '{}'",
603
+ key, dot_path
604
+ )));
605
+ }
606
+
607
+ let indent = entries
608
+ .get(1)
609
+ .or(entries.first())
610
+ .map(|entry| preceding_whitespace_indent(entry.syntax()))
611
+ .unwrap_or_default();
612
+
613
+ let new_entry_text = format!("{}: {}", key, value);
614
+
615
+ match position {
616
+ InsertPosition::Last => {
617
+ let last_entry = entries.last().unwrap();
618
+ let new_text = format!("\n{}{}", indent, new_entry_text);
619
+
620
+ self.insert_after_node(last_entry.syntax(), &new_text)
621
+ }
622
+
623
+ InsertPosition::At(index) => {
624
+ if index >= entries.len() {
625
+ let last_entry = entries.last().unwrap();
626
+ let new_text = format!("\n{}{}", indent, new_entry_text);
627
+
628
+ self.insert_after_node(last_entry.syntax(), &new_text)
629
+ } else {
630
+ let target_entry = &entries[index];
631
+ let target_range = target_entry.syntax().text_range();
632
+ let replacement = format!("{}\n{}", new_entry_text, indent);
633
+ let insert_range = TextRange::new(target_range.start(), target_range.start());
634
+
635
+ self.apply_edit(insert_range, &replacement)
636
+ }
637
+ }
638
+
639
+ InsertPosition::Before(target_key) => {
640
+ let target_entry = find_entry_by_key(&map, &target_key)
641
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{}.{}", dot_path, target_key)))?;
642
+
643
+ let target_range = target_entry.syntax().text_range();
644
+ let replacement = format!("{}\n{}", new_entry_text, indent);
645
+ let insert_range = TextRange::new(target_range.start(), target_range.start());
646
+
647
+ self.apply_edit(insert_range, &replacement)
648
+ }
649
+
650
+ InsertPosition::After(target_key) => {
651
+ let target_entry = find_entry_by_key(&map, &target_key)
652
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{}.{}", dot_path, target_key)))?;
653
+
654
+ let new_text = format!("\n{}{}", indent, new_entry_text);
655
+
656
+ self.insert_after_node(target_entry.syntax(), &new_text)
657
+ }
658
+
659
+ InsertPosition::BeforeCondition(_) | InsertPosition::AfterCondition(_) => {
660
+ self.insert_map_key(dot_path, key, value, InsertPosition::Last)
661
+ }
662
+
663
+ InsertPosition::FromSortOrder(order) => {
664
+ let new_key_position = order.iter().position(|ordered_key| ordered_key == key);
665
+
666
+ let resolved = match new_key_position {
667
+ Some(new_position) => {
668
+ let mut insert_after: Option<String> = None;
669
+
670
+ for ordered_key in order.iter().take(new_position).rev() {
671
+ if find_entry_by_key(&map, ordered_key).is_some() {
672
+ insert_after = Some(ordered_key.clone());
673
+ break;
674
+ }
675
+ }
676
+
677
+ match insert_after {
678
+ Some(after_key) => InsertPosition::After(after_key),
679
+ None => InsertPosition::At(0),
680
+ }
681
+ }
682
+
683
+ None => InsertPosition::Last,
684
+ };
685
+
686
+ self.insert_map_key(dot_path, key, value, resolved)
687
+ }
688
+ }
689
+ }
690
+
691
+ pub fn rename(&mut self, source_path: &str, destination_path: &str) -> Result<(), YerbaError> {
692
+ Self::validate_path(source_path)?;
693
+ Self::validate_path(destination_path)?;
694
+
695
+ let source_parent = source_path.rsplit_once('.').map(|(parent, _)| parent).unwrap_or("");
696
+
697
+ let destination_parent = destination_path
698
+ .rsplit_once('.')
699
+ .map(|(parent, _)| parent)
700
+ .unwrap_or("");
701
+
702
+ let destination_key = destination_path
703
+ .rsplit_once('.')
704
+ .map(|(_, key)| key)
705
+ .unwrap_or(destination_path);
706
+
707
+ if source_parent == destination_parent {
708
+ let (parent_path, source_key) = source_path.rsplit_once('.').unwrap_or(("", source_path));
709
+ let parent_node = self.navigate(parent_path)?;
710
+
711
+ let map = parent_node
712
+ .descendants()
713
+ .find_map(BlockMap::cast)
714
+ .ok_or_else(|| YerbaError::PathNotFound(source_path.to_string()))?;
715
+
716
+ let entry =
717
+ find_entry_by_key(&map, source_key).ok_or_else(|| YerbaError::PathNotFound(source_path.to_string()))?;
718
+
719
+ let key_node = entry
720
+ .key()
721
+ .ok_or_else(|| YerbaError::PathNotFound(source_path.to_string()))?;
722
+
723
+ let key_token =
724
+ find_scalar_token(key_node.syntax()).ok_or_else(|| YerbaError::PathNotFound(source_path.to_string()))?;
725
+
726
+ let new_text = format_scalar_value(destination_key, key_token.kind());
727
+
728
+ self.replace_token(&key_token, &new_text)
729
+ } else {
730
+ let value = self
731
+ .get(source_path)
732
+ .ok_or_else(|| YerbaError::PathNotFound(source_path.to_string()))?;
733
+
734
+ self.delete(source_path)?;
735
+ self.insert_into(destination_path, &value, InsertPosition::Last)
736
+ }
737
+ }
738
+
739
+ pub fn delete(&mut self, dot_path: &str) -> Result<(), YerbaError> {
740
+ Self::validate_path(dot_path)?;
741
+
742
+ let (parent_path, last_key) = dot_path.rsplit_once('.').unwrap_or(("", dot_path));
743
+ let parent_node = self.navigate(parent_path)?;
744
+
745
+ let map = parent_node
746
+ .descendants()
747
+ .find_map(BlockMap::cast)
748
+ .ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
749
+
750
+ let entry = find_entry_by_key(&map, last_key).ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
751
+
752
+ self.remove_node(entry.syntax())
753
+ }
754
+
755
+ pub fn remove(&mut self, dot_path: &str, value: &str) -> Result<(), YerbaError> {
756
+ let current_node = self.navigate(dot_path)?;
757
+
758
+ let sequence = current_node
759
+ .descendants()
760
+ .find_map(BlockSeq::cast)
761
+ .ok_or_else(|| YerbaError::NotASequence(dot_path.to_string()))?;
762
+
763
+ let target_entry = sequence
764
+ .entries()
765
+ .find(|entry| {
766
+ entry
767
+ .flow()
768
+ .and_then(|flow| extract_scalar_text(flow.syntax()))
769
+ .map(|text| text == value)
770
+ .unwrap_or(false)
771
+ })
772
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} item '{}'", dot_path, value)))?;
773
+
774
+ self.remove_node(target_entry.syntax())
775
+ }
776
+
777
+ pub fn remove_at(&mut self, dot_path: &str, index: usize) -> Result<(), YerbaError> {
778
+ Self::validate_path(dot_path)?;
779
+
780
+ let current_node = self.navigate(dot_path)?;
781
+
782
+ let sequence = current_node
783
+ .descendants()
784
+ .find_map(BlockSeq::cast)
785
+ .ok_or_else(|| YerbaError::NotASequence(dot_path.to_string()))?;
786
+
787
+ let entries: Vec<_> = sequence.entries().collect();
788
+
789
+ if index >= entries.len() {
790
+ return Err(YerbaError::IndexOutOfBounds(index, entries.len()));
791
+ }
792
+
793
+ self.remove_node(entries[index].syntax())
794
+ }
795
+
796
+ pub fn move_item(&mut self, dot_path: &str, from: usize, to: usize) -> Result<(), YerbaError> {
797
+ if from == to {
798
+ return Ok(());
799
+ }
800
+
801
+ let current_node = self.navigate(dot_path)?;
802
+
803
+ let sequence = current_node
804
+ .descendants()
805
+ .find_map(BlockSeq::cast)
806
+ .ok_or_else(|| YerbaError::NotASequence(dot_path.to_string()))?;
807
+
808
+ let entries: Vec<_> = sequence.entries().collect();
809
+
810
+ self.reorder_entries(sequence.syntax(), &entries, from, to)
811
+ }
812
+
813
+ pub fn move_key(&mut self, dot_path: &str, from: usize, to: usize) -> Result<(), YerbaError> {
814
+ if from == to {
815
+ return Ok(());
816
+ }
817
+
818
+ let current_node = self.navigate(dot_path)?;
819
+
820
+ let map = current_node
821
+ .descendants()
822
+ .find_map(BlockMap::cast)
823
+ .ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
824
+
825
+ let entries: Vec<_> = map.entries().collect();
826
+
827
+ self.reorder_entries(map.syntax(), &entries, from, to)
828
+ }
829
+
830
+ pub fn resolve_key_index(&self, dot_path: &str, reference: &str) -> Result<usize, YerbaError> {
831
+ let current_node = self.navigate(dot_path)?;
832
+
833
+ let map = current_node
834
+ .descendants()
835
+ .find_map(BlockMap::cast)
836
+ .ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
837
+
838
+ if let Ok(index) = reference.parse::<usize>() {
839
+ let length = map.entries().count();
840
+
841
+ if index >= length {
842
+ return Err(YerbaError::IndexOutOfBounds(index, length));
843
+ }
844
+
845
+ return Ok(index);
846
+ }
847
+
848
+ map
849
+ .entries()
850
+ .enumerate()
851
+ .find(|(_index, entry)| {
852
+ entry
853
+ .key()
854
+ .and_then(|key_node| extract_scalar_text(key_node.syntax()))
855
+ .map(|key_text| key_text == reference)
856
+ .unwrap_or(false)
857
+ })
858
+ .map(|(index, _entry)| index)
859
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} key '{}'", dot_path, reference)))
860
+ }
861
+
862
+ pub fn resolve_sequence_index(&self, dot_path: &str, reference: &str) -> Result<usize, YerbaError> {
863
+ let current_node = self.navigate(dot_path)?;
864
+
865
+ let sequence = current_node
866
+ .descendants()
867
+ .find_map(BlockSeq::cast)
868
+ .ok_or_else(|| YerbaError::NotASequence(dot_path.to_string()))?;
869
+
870
+ if let Ok(index) = reference.parse::<usize>() {
871
+ let length = sequence.entries().count();
872
+
873
+ if index >= length {
874
+ return Err(YerbaError::IndexOutOfBounds(index, length));
875
+ }
876
+
877
+ return Ok(index);
878
+ }
879
+
880
+ if crate::selector::Selector::parse(reference).is_relative() {
881
+ return sequence
882
+ .entries()
883
+ .enumerate()
884
+ .find(|(_index, entry)| self.evaluate_condition_on_node(entry.syntax(), reference))
885
+ .map(|(index, _entry)| index)
886
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} condition '{}'", dot_path, reference)));
887
+ }
888
+
889
+ sequence
890
+ .entries()
891
+ .enumerate()
892
+ .find(|(_index, entry)| {
893
+ entry
894
+ .flow()
895
+ .and_then(|flow| extract_scalar_text(flow.syntax()))
896
+ .map(|text| text == reference)
897
+ .unwrap_or(false)
898
+ })
899
+ .map(|(index, _entry)| index)
900
+ .ok_or_else(|| YerbaError::PathNotFound(format!("{} item '{}'", dot_path, reference)))
901
+ }
902
+
903
+ pub fn validate_sort_keys(&self, dot_path: &str, key_order: &[&str]) -> Result<(), YerbaError> {
904
+ if dot_path == "[]" || dot_path.ends_with(".[]") {
905
+ let seq_path = if dot_path == "[]" {
906
+ ""
907
+ } else {
908
+ &dot_path[..dot_path.len() - 3]
909
+ };
910
+
911
+ return self.validate_each_sort_keys(seq_path, key_order);
912
+ }
913
+
914
+ let current_node = self.navigate(dot_path)?;
915
+
916
+ let map = current_node
917
+ .descendants()
918
+ .find_map(BlockMap::cast)
919
+ .ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
920
+
921
+ let unknown_keys: Vec<String> = map
922
+ .entries()
923
+ .filter_map(|entry| entry.key().and_then(|key_node| extract_scalar_text(key_node.syntax())))
924
+ .filter(|key_name| !key_order.contains(&key_name.as_str()))
925
+ .collect();
926
+
927
+ if unknown_keys.is_empty() {
928
+ Ok(())
929
+ } else {
930
+ Err(YerbaError::UnknownKeys(unknown_keys))
931
+ }
932
+ }
933
+
934
+ pub fn sort_keys(&mut self, dot_path: &str, key_order: &[&str]) -> Result<(), YerbaError> {
935
+ if dot_path == "[]" || dot_path.ends_with(".[]") {
936
+ let seq_path = if dot_path == "[]" {
937
+ ""
938
+ } else {
939
+ &dot_path[..dot_path.len() - 3]
940
+ };
941
+
942
+ return self.sort_each_keys(seq_path, key_order);
943
+ }
944
+
945
+ let current_node = self.navigate(dot_path)?;
946
+
947
+ let map = current_node
948
+ .descendants()
949
+ .find_map(BlockMap::cast)
950
+ .ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
951
+
952
+ let entries: Vec<_> = map.entries().collect();
953
+
954
+ if entries.len() <= 1 {
955
+ return Ok(());
956
+ }
957
+
958
+ let (groups, range) = collect_groups_with_range(map.syntax());
959
+
960
+ let mut keyed: Vec<(String, EntryGroup)> = entries
961
+ .iter()
962
+ .zip(groups)
963
+ .map(|(entry, group)| {
964
+ let key_name = entry
965
+ .key()
966
+ .and_then(|key_node| extract_scalar_text(key_node.syntax()))
967
+ .unwrap_or_default();
968
+ (key_name, group)
969
+ })
970
+ .collect();
971
+
972
+ let original_keys: Vec<String> = keyed.iter().map(|(key, _)| key.clone()).collect();
973
+
974
+ keyed.sort_by(|(key_a, _), (key_b, _)| {
975
+ let position_a = key_order.iter().position(|&key| key == key_a);
976
+ let position_b = key_order.iter().position(|&key| key == key_b);
977
+
978
+ match (position_a, position_b) {
979
+ (Some(a), Some(b)) => a.cmp(&b),
980
+ (Some(_), None) => std::cmp::Ordering::Less,
981
+ (None, Some(_)) => std::cmp::Ordering::Greater,
982
+ (None, None) => {
983
+ let original_a = original_keys.iter().position(|key| key == key_a).unwrap();
984
+ let original_b = original_keys.iter().position(|key| key == key_b).unwrap();
985
+ original_a.cmp(&original_b)
986
+ }
987
+ }
988
+ });
989
+
990
+ let sorted_keys: Vec<&str> = keyed.iter().map(|(key, _)| key.as_str()).collect();
991
+ let orig_refs: Vec<&str> = original_keys.iter().map(|key| key.as_str()).collect();
992
+
993
+ if sorted_keys == orig_refs {
994
+ return Ok(());
995
+ }
996
+
997
+ let indent = entries
998
+ .get(1)
999
+ .map(|entry| preceding_whitespace_indent(entry.syntax()))
1000
+ .unwrap_or_default();
1001
+
1002
+ let sorted_groups: Vec<EntryGroup> = keyed.into_iter().map(|(_, group)| group).collect();
1003
+ let map_text = rebuild_from_groups(&sorted_groups, &indent);
1004
+
1005
+ self.apply_edit(range, &map_text)
1006
+ }
1007
+
1008
+ pub fn sort_each_keys(&mut self, dot_path: &str, key_order: &[&str]) -> Result<(), YerbaError> {
1009
+ let current_node = self.navigate(dot_path)?;
1010
+
1011
+ let sequence = match current_node.descendants().find_map(BlockSeq::cast) {
1012
+ Some(sequence) => sequence,
1013
+ None => return Ok(()),
1014
+ };
1015
+
1016
+ let mut edits: Vec<(TextRange, String)> = Vec::new();
1017
+
1018
+ for entry in sequence.entries() {
1019
+ let entry_node = entry.syntax();
1020
+
1021
+ let map = match entry_node.descendants().find_map(BlockMap::cast) {
1022
+ Some(map) => map,
1023
+ None => continue,
1024
+ };
1025
+
1026
+ let entries: Vec<_> = map.entries().collect();
1027
+
1028
+ if entries.len() <= 1 {
1029
+ continue;
1030
+ }
1031
+
1032
+ let (groups, group_range) = collect_groups_with_range(map.syntax());
1033
+
1034
+ let mut keyed: Vec<(String, EntryGroup)> = entries
1035
+ .iter()
1036
+ .zip(groups)
1037
+ .map(|(entry, group)| {
1038
+ let key_name = entry
1039
+ .key()
1040
+ .and_then(|key_node| extract_scalar_text(key_node.syntax()))
1041
+ .unwrap_or_default();
1042
+ (key_name, group)
1043
+ })
1044
+ .collect();
1045
+
1046
+ let original_keys: Vec<String> = keyed.iter().map(|(key, _)| key.clone()).collect();
1047
+
1048
+ keyed.sort_by(|(key_a, _), (key_b, _)| {
1049
+ let position_a = key_order.iter().position(|&key| key == key_a);
1050
+ let position_b = key_order.iter().position(|&key| key == key_b);
1051
+
1052
+ match (position_a, position_b) {
1053
+ (Some(a), Some(b)) => a.cmp(&b),
1054
+ (Some(_), None) => std::cmp::Ordering::Less,
1055
+ (None, Some(_)) => std::cmp::Ordering::Greater,
1056
+
1057
+ (None, None) => {
1058
+ let original_a = original_keys.iter().position(|key| key == key_a).unwrap();
1059
+ let original_b = original_keys.iter().position(|key| key == key_b).unwrap();
1060
+
1061
+ original_a.cmp(&original_b)
1062
+ }
1063
+ }
1064
+ });
1065
+
1066
+ let sorted_keys: Vec<&str> = keyed.iter().map(|(key, _)| key.as_str()).collect();
1067
+ let orig_refs: Vec<&str> = original_keys.iter().map(|key| key.as_str()).collect();
1068
+
1069
+ if sorted_keys == orig_refs {
1070
+ continue;
1071
+ }
1072
+
1073
+ let indent = entries
1074
+ .get(1)
1075
+ .map(|entry| preceding_whitespace_indent(entry.syntax()))
1076
+ .unwrap_or_default();
1077
+
1078
+ let sorted_groups: Vec<EntryGroup> = keyed.into_iter().map(|(_, group)| group).collect();
1079
+ let map_text = rebuild_from_groups(&sorted_groups, &indent);
1080
+ edits.push((group_range, map_text));
1081
+ }
1082
+
1083
+ if edits.is_empty() {
1084
+ return Ok(());
1085
+ }
1086
+
1087
+ edits.reverse();
1088
+
1089
+ let source = self.root.text().to_string();
1090
+ let mut new_source = source;
1091
+
1092
+ for (range, replacement) in edits {
1093
+ let start: usize = range.start().into();
1094
+ let end: usize = range.end().into();
1095
+
1096
+ new_source.replace_range(start..end, &replacement);
1097
+ }
1098
+
1099
+ let path = self.path.take();
1100
+ *self = Self::parse(&new_source)?;
1101
+ self.path = path;
1102
+
1103
+ Ok(())
1104
+ }
1105
+
1106
+ pub fn validate_each_sort_keys(&self, dot_path: &str, key_order: &[&str]) -> Result<(), YerbaError> {
1107
+ let current_node = self.navigate(dot_path)?;
1108
+
1109
+ let sequence = match current_node.descendants().find_map(BlockSeq::cast) {
1110
+ Some(sequence) => sequence,
1111
+ None => return Ok(()),
1112
+ };
1113
+
1114
+ let mut all_unknown: Vec<String> = Vec::new();
1115
+
1116
+ for entry in sequence.entries() {
1117
+ if let Some(map) = entry.syntax().descendants().find_map(BlockMap::cast) {
1118
+ for map_entry in map.entries() {
1119
+ if let Some(key_name) = map_entry
1120
+ .key()
1121
+ .and_then(|key_node| extract_scalar_text(key_node.syntax()))
1122
+ {
1123
+ if !key_order.contains(&key_name.as_str()) && !all_unknown.contains(&key_name) {
1124
+ all_unknown.push(key_name);
1125
+ }
1126
+ }
1127
+ }
1128
+ }
1129
+ }
1130
+
1131
+ if all_unknown.is_empty() {
1132
+ Ok(())
1133
+ } else {
1134
+ Err(YerbaError::UnknownKeys(all_unknown))
1135
+ }
1136
+ }
1137
+
1138
+ pub fn sort_items(
1139
+ &mut self,
1140
+ dot_path: &str,
1141
+ sort_fields: &[SortField],
1142
+ case_sensitive: bool,
1143
+ ) -> Result<(), YerbaError> {
1144
+ if dot_path.contains("[].") {
1145
+ return self.sort_each_items(dot_path, sort_fields, case_sensitive);
1146
+ }
1147
+
1148
+ let current_node = self.navigate(dot_path)?;
1149
+
1150
+ let sequence = match current_node.descendants().find_map(BlockSeq::cast) {
1151
+ Some(sequence) => sequence,
1152
+ None => return Ok(()),
1153
+ };
1154
+
1155
+ let entries: Vec<_> = sequence.entries().collect();
1156
+
1157
+ if entries.len() <= 1 {
1158
+ return Ok(());
1159
+ }
1160
+
1161
+ let (groups, range) = collect_groups_with_range(sequence.syntax());
1162
+
1163
+ let mut sortable: Vec<(Vec<String>, EntryGroup)> = entries
1164
+ .iter()
1165
+ .zip(groups)
1166
+ .map(|(entry, group)| {
1167
+ let sort_values = if sort_fields.is_empty() {
1168
+ vec![entry
1169
+ .flow()
1170
+ .and_then(|flow| extract_scalar_text(flow.syntax()))
1171
+ .unwrap_or_default()]
1172
+ } else {
1173
+ sort_fields
1174
+ .iter()
1175
+ .map(|field| {
1176
+ let nodes = navigate_from_node(entry.syntax(), &field.path);
1177
+ nodes.first().and_then(extract_scalar_text).unwrap_or_default()
1178
+ })
1179
+ .collect()
1180
+ };
1181
+
1182
+ (sort_values, group)
1183
+ })
1184
+ .collect();
1185
+
1186
+ let original_bodies: Vec<String> = sortable.iter().map(|(_, group)| group.body.clone()).collect();
1187
+
1188
+ sortable.sort_by(|(values_a, _), (values_b, _)| {
1189
+ for (index, field) in sort_fields.iter().enumerate().take(values_a.len()) {
1190
+ let value_a = &values_a[index];
1191
+ let value_b = &values_b[index];
1192
+
1193
+ let ordering = if case_sensitive {
1194
+ value_a.cmp(value_b)
1195
+ } else {
1196
+ value_a.to_lowercase().cmp(&value_b.to_lowercase())
1197
+ };
1198
+
1199
+ let ordering = if field.ascending { ordering } else { ordering.reverse() };
1200
+
1201
+ if ordering != std::cmp::Ordering::Equal {
1202
+ return ordering;
1203
+ }
1204
+ }
1205
+
1206
+ if sort_fields.is_empty() && !values_a.is_empty() && !values_b.is_empty() {
1207
+ return if case_sensitive {
1208
+ values_a[0].cmp(&values_b[0])
1209
+ } else {
1210
+ values_a[0].to_lowercase().cmp(&values_b[0].to_lowercase())
1211
+ };
1212
+ }
1213
+
1214
+ std::cmp::Ordering::Equal
1215
+ });
1216
+
1217
+ let sorted_bodies: Vec<String> = sortable.iter().map(|(_, group)| group.body.clone()).collect();
1218
+
1219
+ if sorted_bodies == original_bodies {
1220
+ return Ok(());
1221
+ }
1222
+
1223
+ let indent = entries
1224
+ .get(1)
1225
+ .map(|entry| preceding_whitespace_indent(entry.syntax()))
1226
+ .unwrap_or_default();
1227
+
1228
+ let sorted_groups: Vec<EntryGroup> = sortable.into_iter().map(|(_, group)| group).collect();
1229
+ let sequence_text = rebuild_from_groups(&sorted_groups, &indent);
1230
+
1231
+ self.apply_edit(range, &sequence_text)
1232
+ }
1233
+
1234
+ fn sort_each_items(
1235
+ &mut self,
1236
+ dot_path: &str,
1237
+ sort_fields: &[SortField],
1238
+ case_sensitive: bool,
1239
+ ) -> Result<(), YerbaError> {
1240
+ let (parent_path, child_path) = if let Some(last_bracket) = dot_path.rfind("[].") {
1241
+ (&dot_path[..last_bracket + 2], &dot_path[last_bracket + 3..])
1242
+ } else {
1243
+ (dot_path, "")
1244
+ };
1245
+
1246
+ let parent_nodes = self.navigate_all(parent_path);
1247
+ let source = self.root.text().to_string();
1248
+ let mut edits: Vec<(TextRange, String)> = Vec::new();
1249
+
1250
+ for parent_node in &parent_nodes {
1251
+ let child_nodes = if child_path.is_empty() {
1252
+ vec![parent_node.clone()]
1253
+ } else {
1254
+ navigate_from_node(parent_node, child_path)
1255
+ };
1256
+
1257
+ for child_node in &child_nodes {
1258
+ let sequence = match child_node.descendants().find_map(BlockSeq::cast) {
1259
+ Some(sequence) => sequence,
1260
+ None => continue,
1261
+ };
1262
+
1263
+ let entries: Vec<_> = sequence.entries().collect();
1264
+
1265
+ if entries.len() <= 1 {
1266
+ continue;
1267
+ }
1268
+
1269
+ let (groups, group_range) = collect_groups_with_range(sequence.syntax());
1270
+
1271
+ let mut sortable: Vec<(Vec<String>, EntryGroup)> = entries
1272
+ .iter()
1273
+ .zip(groups)
1274
+ .map(|(entry, group)| {
1275
+ let sort_values = if sort_fields.is_empty() {
1276
+ vec![entry
1277
+ .flow()
1278
+ .and_then(|flow| extract_scalar_text(flow.syntax()))
1279
+ .unwrap_or_default()]
1280
+ } else {
1281
+ sort_fields
1282
+ .iter()
1283
+ .map(|field| {
1284
+ let nodes = navigate_from_node(entry.syntax(), &field.path);
1285
+ nodes.first().and_then(extract_scalar_text).unwrap_or_default()
1286
+ })
1287
+ .collect()
1288
+ };
1289
+
1290
+ (sort_values, group)
1291
+ })
1292
+ .collect();
1293
+
1294
+ let original_bodies: Vec<String> = sortable.iter().map(|(_, group)| group.body.clone()).collect();
1295
+
1296
+ sortable.sort_by(|(values_a, _), (values_b, _)| {
1297
+ for (index, field) in sort_fields.iter().enumerate().take(values_a.len()) {
1298
+ let value_a = &values_a[index];
1299
+ let value_b = &values_b[index];
1300
+
1301
+ let ordering = if case_sensitive {
1302
+ value_a.cmp(value_b)
1303
+ } else {
1304
+ value_a.to_lowercase().cmp(&value_b.to_lowercase())
1305
+ };
1306
+
1307
+ let ordering = if field.ascending { ordering } else { ordering.reverse() };
1308
+
1309
+ if ordering != std::cmp::Ordering::Equal {
1310
+ return ordering;
1311
+ }
1312
+ }
1313
+
1314
+ if sort_fields.is_empty() && !values_a.is_empty() && !values_b.is_empty() {
1315
+ return if case_sensitive {
1316
+ values_a[0].cmp(&values_b[0])
1317
+ } else {
1318
+ values_a[0].to_lowercase().cmp(&values_b[0].to_lowercase())
1319
+ };
1320
+ }
1321
+
1322
+ std::cmp::Ordering::Equal
1323
+ });
1324
+
1325
+ let sorted_bodies: Vec<String> = sortable.iter().map(|(_, group)| group.body.clone()).collect();
1326
+
1327
+ if sorted_bodies == original_bodies {
1328
+ continue;
1329
+ }
1330
+
1331
+ let indent = entries
1332
+ .get(1)
1333
+ .map(|entry| preceding_whitespace_indent(entry.syntax()))
1334
+ .unwrap_or_default();
1335
+
1336
+ let sorted_groups: Vec<EntryGroup> = sortable.into_iter().map(|(_, group)| group).collect();
1337
+ let sequence_text = rebuild_from_groups(&sorted_groups, &indent);
1338
+ edits.push((group_range, sequence_text));
1339
+ }
1340
+ }
1341
+
1342
+ if edits.is_empty() {
1343
+ return Ok(());
1344
+ }
1345
+
1346
+ edits.reverse();
1347
+
1348
+ let mut new_source = source;
1349
+
1350
+ for (range, replacement) in edits {
1351
+ let start: usize = range.start().into();
1352
+ let end: usize = range.end().into();
1353
+
1354
+ new_source.replace_range(start..end, &replacement);
1355
+ }
1356
+
1357
+ let path = self.path.take();
1358
+ *self = Self::parse(&new_source)?;
1359
+ self.path = path;
1360
+
1361
+ Ok(())
1362
+ }
1363
+
1364
+ pub fn enforce_blank_lines(&mut self, dot_path: &str, blank_lines: usize) -> Result<(), YerbaError> {
1365
+ let nodes = if dot_path.contains('[') {
1366
+ self.navigate_all(dot_path)
1367
+ } else {
1368
+ vec![self.navigate(dot_path)?]
1369
+ };
1370
+
1371
+ let mut edits: Vec<(TextRange, String)> = Vec::new();
1372
+
1373
+ for current_node in &nodes {
1374
+ let sequence = match current_node.descendants().find_map(BlockSeq::cast) {
1375
+ Some(sequence) => sequence,
1376
+ None => continue,
1377
+ };
1378
+
1379
+ let entries: Vec<_> = sequence.entries().collect();
1380
+
1381
+ if entries.len() <= 1 {
1382
+ continue;
1383
+ }
1384
+
1385
+ for entry in entries.iter().skip(1) {
1386
+ if let Some(whitespace_token) = preceding_whitespace_token(entry.syntax()) {
1387
+ let whitespace_text = whitespace_token.text();
1388
+ let newline_count = whitespace_text.chars().filter(|character| *character == '\n').count();
1389
+
1390
+ let indent = whitespace_text
1391
+ .rfind('\n')
1392
+ .map(|position| &whitespace_text[position + 1..])
1393
+ .unwrap_or("");
1394
+
1395
+ let desired_newlines = blank_lines + 1;
1396
+
1397
+ if newline_count != desired_newlines {
1398
+ let new_whitespace = format!("{}{}", "\n".repeat(desired_newlines), indent);
1399
+
1400
+ edits.push((whitespace_token.text_range(), new_whitespace));
1401
+ }
1402
+ }
1403
+ }
1404
+ }
1405
+
1406
+ if edits.is_empty() {
1407
+ return Ok(());
1408
+ }
1409
+
1410
+ edits.sort_by_key(|edit| std::cmp::Reverse(edit.0.start()));
1411
+
1412
+ let source = self.root.text().to_string();
1413
+ let mut new_source = source;
1414
+
1415
+ for (range, replacement) in edits {
1416
+ let start: usize = range.start().into();
1417
+ let end: usize = range.end().into();
1418
+
1419
+ new_source.replace_range(start..end, &replacement);
1420
+ }
1421
+
1422
+ let path = self.path.take();
1423
+ *self = Self::parse(&new_source)?;
1424
+ self.path = path;
1425
+
1426
+ Ok(())
1427
+ }
1428
+
1429
+ pub fn enforce_key_style(&mut self, style: &QuoteStyle, dot_path: Option<&str>) -> Result<(), YerbaError> {
1430
+ let source = self.root.text().to_string();
1431
+
1432
+ let scope_ranges: Vec<TextRange> = match dot_path {
1433
+ Some(path) if !path.is_empty() => self.navigate_all(path).iter().map(|node| node.text_range()).collect(),
1434
+ _ => vec![self.root.text_range()],
1435
+ };
1436
+
1437
+ let mut edits: Vec<(TextRange, String)> = Vec::new();
1438
+
1439
+ for element in self.root.descendants_with_tokens() {
1440
+ if let Some(token) = element.into_token() {
1441
+ if !scope_ranges
1442
+ .iter()
1443
+ .any(|range| range.contains_range(token.text_range()))
1444
+ {
1445
+ continue;
1446
+ }
1447
+
1448
+ if !is_map_key(&token) {
1449
+ continue;
1450
+ }
1451
+
1452
+ let current_kind = token.kind();
1453
+
1454
+ if !matches!(
1455
+ current_kind,
1456
+ SyntaxKind::PLAIN_SCALAR | SyntaxKind::DOUBLE_QUOTED_SCALAR | SyntaxKind::SINGLE_QUOTED_SCALAR
1457
+ ) {
1458
+ continue;
1459
+ }
1460
+
1461
+ let target_kind = style.to_syntax_kind();
1462
+
1463
+ if current_kind == target_kind {
1464
+ continue;
1465
+ }
1466
+
1467
+ let raw_value = match current_kind {
1468
+ SyntaxKind::DOUBLE_QUOTED_SCALAR => {
1469
+ let text = token.text();
1470
+ unescape_double_quoted(&text[1..text.len() - 1])
1471
+ }
1472
+
1473
+ SyntaxKind::SINGLE_QUOTED_SCALAR => {
1474
+ let text = token.text();
1475
+ unescape_single_quoted(&text[1..text.len() - 1])
1476
+ }
1477
+
1478
+ SyntaxKind::PLAIN_SCALAR => token.text().to_string(),
1479
+
1480
+ _ => continue,
1481
+ };
1482
+
1483
+ let new_text = match style {
1484
+ QuoteStyle::Double => {
1485
+ let escaped = raw_value.replace('\\', "\\\\").replace('"', "\\\"");
1486
+ format!("\"{}\"", escaped)
1487
+ }
1488
+
1489
+ QuoteStyle::Single => {
1490
+ let escaped = raw_value.replace('\'', "''");
1491
+ format!("'{}'", escaped)
1492
+ }
1493
+
1494
+ QuoteStyle::Plain => raw_value,
1495
+
1496
+ _ => continue,
1497
+ };
1498
+
1499
+ if new_text != token.text() {
1500
+ edits.push((token.text_range(), new_text));
1501
+ }
1502
+ }
1503
+ }
1504
+
1505
+ if edits.is_empty() {
1506
+ return Ok(());
1507
+ }
1508
+
1509
+ edits.reverse();
1510
+
1511
+ let mut new_source = source;
1512
+
1513
+ for (range, replacement) in edits {
1514
+ let start: usize = range.start().into();
1515
+ let end: usize = range.end().into();
1516
+
1517
+ new_source.replace_range(start..end, &replacement);
1518
+ }
1519
+
1520
+ let path = self.path.take();
1521
+ *self = Self::parse(&new_source)?;
1522
+ self.path = path;
1523
+
1524
+ Ok(())
1525
+ }
1526
+
1527
+ pub fn enforce_quotes(&mut self, style: &QuoteStyle) -> Result<(), YerbaError> {
1528
+ self.enforce_quotes_at(style, None)
1529
+ }
1530
+
1531
+ pub fn enforce_quotes_at(&mut self, style: &QuoteStyle, dot_path: Option<&str>) -> Result<(), YerbaError> {
1532
+ let source = self.root.text().to_string();
1533
+
1534
+ let scope_ranges: Vec<TextRange> = match dot_path {
1535
+ Some(path) if !path.is_empty() => self.navigate_all(path).iter().map(|node| node.text_range()).collect(),
1536
+ _ => vec![self.root.text_range()],
1537
+ };
1538
+
1539
+ let mut edits: Vec<(TextRange, String)> = Vec::new();
1540
+
1541
+ for element in self.root.descendants_with_tokens() {
1542
+ if let Some(token) = element.into_token() {
1543
+ if !scope_ranges
1544
+ .iter()
1545
+ .any(|range| range.contains_range(token.text_range()))
1546
+ {
1547
+ continue;
1548
+ }
1549
+
1550
+ if is_map_key(&token) {
1551
+ continue;
1552
+ }
1553
+
1554
+ let current_kind = token.kind();
1555
+
1556
+ if !matches!(
1557
+ current_kind,
1558
+ SyntaxKind::PLAIN_SCALAR | SyntaxKind::DOUBLE_QUOTED_SCALAR | SyntaxKind::SINGLE_QUOTED_SCALAR
1559
+ ) {
1560
+ continue;
1561
+ }
1562
+
1563
+ let target_kind = style.to_syntax_kind();
1564
+
1565
+ if current_kind == target_kind {
1566
+ continue;
1567
+ }
1568
+
1569
+ let raw_value = match current_kind {
1570
+ SyntaxKind::DOUBLE_QUOTED_SCALAR => {
1571
+ let text = token.text();
1572
+ unescape_double_quoted(&text[1..text.len() - 1])
1573
+ }
1574
+
1575
+ SyntaxKind::SINGLE_QUOTED_SCALAR => {
1576
+ let text = token.text();
1577
+ unescape_single_quoted(&text[1..text.len() - 1])
1578
+ }
1579
+
1580
+ SyntaxKind::PLAIN_SCALAR => token.text().to_string(),
1581
+
1582
+ _ => continue,
1583
+ };
1584
+
1585
+ if is_yaml_non_string(&raw_value) {
1586
+ continue;
1587
+ }
1588
+
1589
+ let new_text = match style {
1590
+ QuoteStyle::Double => {
1591
+ if raw_value.contains('"') && current_kind == SyntaxKind::SINGLE_QUOTED_SCALAR {
1592
+ continue;
1593
+ }
1594
+
1595
+ let escaped = raw_value.replace('\\', "\\\\").replace('"', "\\\"");
1596
+ format!("\"{}\"", escaped)
1597
+ }
1598
+
1599
+ QuoteStyle::Single => {
1600
+ let escaped = raw_value.replace('\'', "''");
1601
+ format!("'{}'", escaped)
1602
+ }
1603
+
1604
+ QuoteStyle::Plain => {
1605
+ if raw_value.contains('"') || raw_value.contains('\'') || raw_value.contains(':') || raw_value.contains('#')
1606
+ {
1607
+ continue;
1608
+ }
1609
+
1610
+ raw_value
1611
+ }
1612
+
1613
+ _ => continue,
1614
+ };
1615
+
1616
+ if new_text != token.text() {
1617
+ edits.push((token.text_range(), new_text));
1618
+ }
1619
+ }
1620
+ }
1621
+
1622
+ if edits.is_empty() {
1623
+ return Ok(());
1624
+ }
1625
+
1626
+ edits.reverse();
1627
+
1628
+ let mut new_source = source;
1629
+
1630
+ for (range, replacement) in edits {
1631
+ let start: usize = range.start().into();
1632
+ let end: usize = range.end().into();
1633
+
1634
+ new_source.replace_range(start..end, &replacement);
1635
+ }
1636
+
1637
+ let path = self.path.take();
1638
+ *self = Self::parse(&new_source)?;
1639
+ self.path = path;
1640
+
1641
+ Ok(())
1642
+ }
1643
+
1644
+ pub fn save(&self) -> Result<(), YerbaError> {
1645
+ let path = self.path.as_ref().ok_or_else(|| {
1646
+ YerbaError::IoError(std::io::Error::new(
1647
+ std::io::ErrorKind::NotFound,
1648
+ "no file path associated with this document",
1649
+ ))
1650
+ })?;
1651
+
1652
+ fs::write(path, self.to_string())?;
1653
+
1654
+ Ok(())
1655
+ }
1656
+
1657
+ pub fn save_to(&self, path: impl AsRef<Path>) -> Result<(), YerbaError> {
1658
+ fs::write(path, self.to_string())?;
1659
+
1660
+ Ok(())
1661
+ }
1662
+
1663
+ pub fn navigate(&self, dot_path: &str) -> Result<SyntaxNode, YerbaError> {
1664
+ Self::validate_path(dot_path)?;
1665
+
1666
+ if dot_path.is_empty() {
1667
+ let root = Root::cast(self.root.clone()).ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
1668
+
1669
+ let document = root
1670
+ .documents()
1671
+ .next()
1672
+ .ok_or_else(|| YerbaError::PathNotFound(dot_path.to_string()))?;
1673
+
1674
+ return Ok(document.syntax().clone());
1675
+ }
1676
+
1677
+ let nodes = self.navigate_all(dot_path);
1678
+
1679
+ match nodes.len() {
1680
+ 0 => Err(YerbaError::PathNotFound(dot_path.to_string())),
1681
+ 1 => Ok(nodes.into_iter().next().unwrap()),
1682
+ _ => Err(YerbaError::PathNotFound(format!(
1683
+ "{} (matched {} nodes, expected 1)",
1684
+ dot_path,
1685
+ nodes.len()
1686
+ ))),
1687
+ }
1688
+ }
1689
+
1690
+ pub fn validate_path(dot_path: &str) -> Result<(), YerbaError> {
1691
+ if dot_path.ends_with('.') {
1692
+ return Err(YerbaError::ParseError(format!(
1693
+ "invalid path: trailing dot in '{}'",
1694
+ dot_path
1695
+ )));
1696
+ }
1697
+
1698
+ if dot_path.contains("..") {
1699
+ return Err(YerbaError::ParseError(format!(
1700
+ "invalid path: double dot in '{}'",
1701
+ dot_path
1702
+ )));
1703
+ }
1704
+
1705
+ if dot_path.starts_with('.') {
1706
+ return Err(YerbaError::ParseError(format!(
1707
+ "invalid path: leading dot in '{}'",
1708
+ dot_path
1709
+ )));
1710
+ }
1711
+
1712
+ if dot_path.contains('[') && !dot_path.contains(']') {
1713
+ return Err(YerbaError::ParseError(format!(
1714
+ "invalid path: unclosed bracket in '{}'",
1715
+ dot_path
1716
+ )));
1717
+ }
1718
+
1719
+ Ok(())
1720
+ }
1721
+
1722
+ pub fn navigate_all(&self, dot_path: &str) -> Vec<SyntaxNode> {
1723
+ if Document::validate_path(dot_path).is_err() {
1724
+ return Vec::new();
1725
+ }
1726
+
1727
+ let parsed = crate::selector::Selector::parse(dot_path);
1728
+
1729
+ let root = match Root::cast(self.root.clone()) {
1730
+ Some(root) => root,
1731
+ None => return Vec::new(),
1732
+ };
1733
+
1734
+ let document = match root.documents().next() {
1735
+ Some(document) => document,
1736
+ None => return Vec::new(),
1737
+ };
1738
+
1739
+ let mut current_nodes = vec![document.syntax().clone()];
1740
+
1741
+ if parsed.is_empty() {
1742
+ if let Some(sequence) = document.syntax().descendants().find_map(BlockSeq::cast) {
1743
+ current_nodes = sequence.entries().map(|entry| entry.syntax().clone()).collect();
1744
+ }
1745
+
1746
+ return current_nodes;
1747
+ }
1748
+
1749
+ for segment in parsed.segments() {
1750
+ let mut next_nodes = Vec::new();
1751
+
1752
+ for node in &current_nodes {
1753
+ next_nodes.extend(resolve_segment(node, segment));
1754
+ }
1755
+
1756
+ current_nodes = next_nodes;
1757
+
1758
+ if current_nodes.is_empty() {
1759
+ break;
1760
+ }
1761
+ }
1762
+
1763
+ current_nodes
1764
+ }
1765
+
1766
+ fn replace_token(&mut self, token: &SyntaxToken, new_text: &str) -> Result<(), YerbaError> {
1767
+ let range = token.text_range();
1768
+
1769
+ self.apply_edit(range, new_text)
1770
+ }
1771
+
1772
+ fn insert_after_node(&mut self, node: &SyntaxNode, text: &str) -> Result<(), YerbaError> {
1773
+ let position = node.text_range().end();
1774
+ let range = TextRange::new(position, position);
1775
+
1776
+ self.apply_edit(range, text)
1777
+ }
1778
+
1779
+ fn remove_node(&mut self, node: &SyntaxNode) -> Result<(), YerbaError> {
1780
+ let inline_comment = self.find_inline_comment(node);
1781
+ let range = removal_range(node);
1782
+
1783
+ if let Some((comment_text, comment_end)) = inline_comment {
1784
+ let indent = preceding_whitespace_indent(node);
1785
+ let replacement = format!("\n{}{}", indent, comment_text);
1786
+ let expanded_range = TextRange::new(range.start(), comment_end);
1787
+
1788
+ self.apply_edit(expanded_range, &replacement)
1789
+ } else {
1790
+ self.apply_edit(range, "")
1791
+ }
1792
+ }
1793
+
1794
+ fn find_inline_comment(&self, node: &SyntaxNode) -> Option<(String, rowan::TextSize)> {
1795
+ let mut sibling = node.next_sibling_or_token();
1796
+
1797
+ while let Some(ref element) = sibling {
1798
+ match element {
1799
+ rowan::NodeOrToken::Token(token) => {
1800
+ if token.kind() == SyntaxKind::COMMENT {
1801
+ return Some((token.text().to_string(), token.text_range().end()));
1802
+ } else if token.kind() == SyntaxKind::WHITESPACE {
1803
+ if token.text().contains('\n') {
1804
+ return None;
1805
+ }
1806
+ } else {
1807
+ return None;
1808
+ }
1809
+ }
1810
+ _ => return None,
1811
+ }
1812
+
1813
+ sibling = match element {
1814
+ rowan::NodeOrToken::Token(token) => token.next_sibling_or_token(),
1815
+ rowan::NodeOrToken::Node(node) => node.next_sibling_or_token(),
1816
+ };
1817
+ }
1818
+
1819
+ None
1820
+ }
1821
+
1822
+ fn reorder_entries<T>(&mut self, parent: &SyntaxNode, entries: &[T], from: usize, to: usize) -> Result<(), YerbaError>
1823
+ where
1824
+ T: rowan::ast::AstNode<Language = yaml_parser::YamlLanguage>,
1825
+ {
1826
+ let length = entries.len();
1827
+
1828
+ if from >= length {
1829
+ return Err(YerbaError::IndexOutOfBounds(from, length));
1830
+ }
1831
+
1832
+ if to >= length {
1833
+ return Err(YerbaError::IndexOutOfBounds(to, length));
1834
+ }
1835
+
1836
+ let (groups, range) = collect_groups_with_range(parent);
1837
+
1838
+ let mut reordered = groups.clone();
1839
+ let item = reordered.remove(from);
1840
+ reordered.insert(to, item);
1841
+
1842
+ let indent = entries
1843
+ .get(1)
1844
+ .map(|entry| preceding_whitespace_indent(entry.syntax()))
1845
+ .unwrap_or_default();
1846
+
1847
+ let text = rebuild_from_groups(&reordered, &indent);
1848
+
1849
+ self.apply_edit(range, &text)
1850
+ }
1851
+
1852
+ fn apply_edit(&mut self, range: TextRange, replacement: &str) -> Result<(), YerbaError> {
1853
+ let source = self.root.text().to_string();
1854
+ let start: usize = range.start().into();
1855
+ let end: usize = range.end().into();
1856
+
1857
+ let mut new_source = source;
1858
+ new_source.replace_range(start..end, replacement);
1859
+
1860
+ let path = self.path.take();
1861
+ *self = Self::parse(&new_source)?;
1862
+ self.path = path;
1863
+
1864
+ Ok(())
1865
+ }
1866
+ }
1867
+
1868
+ impl std::fmt::Display for Document {
1869
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1870
+ write!(f, "{}", self.root.text())
1871
+ }
1872
+ }
1873
+
1874
+ pub fn node_to_yaml_value(node: &SyntaxNode) -> serde_yaml::Value {
1875
+ if let Some(sequence) = node.descendants().find_map(BlockSeq::cast) {
1876
+ let map_position = node
1877
+ .descendants()
1878
+ .find_map(BlockMap::cast)
1879
+ .map(|map| map.syntax().text_range().start());
1880
+
1881
+ let sequence_position = sequence.syntax().text_range().start();
1882
+
1883
+ if map_position.is_none() || sequence_position <= map_position.unwrap() {
1884
+ let values: Vec<serde_yaml::Value> = sequence
1885
+ .entries()
1886
+ .map(|entry| node_to_yaml_value(entry.syntax()))
1887
+ .collect();
1888
+
1889
+ return serde_yaml::Value::Sequence(values);
1890
+ }
1891
+ }
1892
+
1893
+ if let Some(map) = node.descendants().find_map(BlockMap::cast) {
1894
+ let mut mapping = serde_yaml::Mapping::new();
1895
+
1896
+ for entry in map.entries() {
1897
+ let key = entry
1898
+ .key()
1899
+ .and_then(|key_node| extract_scalar_text(key_node.syntax()))
1900
+ .unwrap_or_default();
1901
+
1902
+ let value = entry
1903
+ .value()
1904
+ .map(|value_node| node_to_yaml_value(value_node.syntax()))
1905
+ .unwrap_or(serde_yaml::Value::Null);
1906
+
1907
+ mapping.insert(serde_yaml::Value::String(key), value);
1908
+ }
1909
+
1910
+ return serde_yaml::Value::Mapping(mapping);
1911
+ }
1912
+
1913
+ if let Some(sequence) = node.descendants().find_map(BlockSeq::cast) {
1914
+ let values: Vec<serde_yaml::Value> = sequence
1915
+ .entries()
1916
+ .map(|entry| node_to_yaml_value(entry.syntax()))
1917
+ .collect();
1918
+
1919
+ return serde_yaml::Value::Sequence(values);
1920
+ }
1921
+
1922
+ if let Some(block_scalar) = node
1923
+ .descendants()
1924
+ .find(|child| child.kind() == SyntaxKind::BLOCK_SCALAR)
1925
+ {
1926
+ let text = block_scalar
1927
+ .descendants_with_tokens()
1928
+ .filter_map(|element| element.into_token())
1929
+ .find(|token| token.kind() == SyntaxKind::BLOCK_SCALAR_TEXT)
1930
+ .map(|token| token.text().to_string())
1931
+ .unwrap_or_default();
1932
+
1933
+ return serde_yaml::Value::String(text);
1934
+ }
1935
+
1936
+ if let Some(scalar) = extract_scalar(node) {
1937
+ use crate::syntax::{detect_yaml_type, is_yaml_truthy, YerbaValueType};
1938
+
1939
+ return match detect_yaml_type(&scalar) {
1940
+ YerbaValueType::Null => serde_yaml::Value::Null,
1941
+ YerbaValueType::Boolean => serde_yaml::Value::Bool(is_yaml_truthy(&scalar.text)),
1942
+
1943
+ YerbaValueType::Integer => scalar
1944
+ .text
1945
+ .parse::<i64>()
1946
+ .map(|n| serde_yaml::Value::Number(serde_yaml::Number::from(n)))
1947
+ .unwrap_or(serde_yaml::Value::String(scalar.text)),
1948
+
1949
+ YerbaValueType::Float => scalar
1950
+ .text
1951
+ .parse::<f64>()
1952
+ .map(|n| serde_yaml::Value::Number(serde_yaml::Number::from(n)))
1953
+ .unwrap_or(serde_yaml::Value::String(scalar.text)),
1954
+
1955
+ YerbaValueType::String => serde_yaml::Value::String(scalar.text),
1956
+ };
1957
+ }
1958
+
1959
+ let text = node.text().to_string();
1960
+
1961
+ serde_yaml::from_str(&text).unwrap_or(serde_yaml::Value::String(text))
1962
+ }
1963
+
1964
+ fn parse_condition(condition: &str) -> Option<(String, &str, String)> {
1965
+ let (left, operator, right) = if let Some(index) = condition.find(" not_contains ") {
1966
+ (
1967
+ condition[..index].trim(),
1968
+ "not_contains",
1969
+ condition[index + 14..].trim(),
1970
+ )
1971
+ } else if let Some(index) = condition.find(" contains ") {
1972
+ (condition[..index].trim(), "contains", condition[index + 10..].trim())
1973
+ } else if let Some(index) = condition.find("!=") {
1974
+ (condition[..index].trim(), "!=", condition[index + 2..].trim())
1975
+ } else if let Some(index) = condition.find("==") {
1976
+ (condition[..index].trim(), "==", condition[index + 2..].trim())
1977
+ } else {
1978
+ return None;
1979
+ };
1980
+
1981
+ let right = right
1982
+ .trim_start_matches('"')
1983
+ .trim_end_matches('"')
1984
+ .trim_start_matches('\'')
1985
+ .trim_end_matches('\'');
1986
+
1987
+ Some((left.to_string(), operator, right.to_string()))
1988
+ }
1989
+
1990
+ fn resolve_segment(node: &SyntaxNode, segment: &crate::selector::SelectorSegment) -> Vec<SyntaxNode> {
1991
+ use crate::selector::SelectorSegment;
1992
+
1993
+ match segment {
1994
+ SelectorSegment::AllItems => {
1995
+ if let Some(sequence) = node.descendants().find_map(BlockSeq::cast) {
1996
+ sequence.entries().map(|entry| entry.syntax().clone()).collect()
1997
+ } else {
1998
+ Vec::new()
1999
+ }
2000
+ }
2001
+
2002
+ SelectorSegment::Index(index) => {
2003
+ if let Some(sequence) = node.descendants().find_map(BlockSeq::cast) {
2004
+ sequence
2005
+ .entries()
2006
+ .nth(*index)
2007
+ .map(|entry| vec![entry.syntax().clone()])
2008
+ .unwrap_or_default()
2009
+ } else {
2010
+ Vec::new()
2011
+ }
2012
+ }
2013
+
2014
+ SelectorSegment::Key(key) => {
2015
+ if let Some(map) = node.descendants().find_map(BlockMap::cast) {
2016
+ if let Some(entry) = find_entry_by_key(&map, key) {
2017
+ if let Some(value) = entry.value() {
2018
+ return vec![value.syntax().clone()];
2019
+ }
2020
+ }
2021
+ }
2022
+
2023
+ Vec::new()
2024
+ }
2025
+ }
2026
+ }
2027
+
2028
+ fn navigate_from_node(node: &SyntaxNode, path: &str) -> Vec<SyntaxNode> {
2029
+ let parsed = crate::selector::Selector::parse(path);
2030
+ let mut current_nodes = vec![node.clone()];
2031
+
2032
+ for segment in parsed.segments() {
2033
+ let mut next_nodes = Vec::new();
2034
+
2035
+ for current in &current_nodes {
2036
+ next_nodes.extend(resolve_segment(current, segment));
2037
+ }
2038
+
2039
+ current_nodes = next_nodes;
2040
+
2041
+ if current_nodes.is_empty() {
2042
+ break;
2043
+ }
2044
+ }
2045
+
2046
+ current_nodes
2047
+ }
2048
+
2049
+ #[derive(Debug, Clone)]
2050
+ struct EntryGroup {
2051
+ separator: String,
2052
+ preceding: String,
2053
+ body: String,
2054
+ }
2055
+
2056
+ impl EntryGroup {
2057
+ fn full_text(&self) -> String {
2058
+ if self.preceding.is_empty() {
2059
+ self.body.clone()
2060
+ } else {
2061
+ format!("{}\n{}", self.preceding, self.body)
2062
+ }
2063
+ }
2064
+ }
2065
+
2066
+ fn collect_entry_groups(parent: &SyntaxNode) -> Vec<EntryGroup> {
2067
+ let mut groups: Vec<EntryGroup> = Vec::new();
2068
+ let mut buffer = String::new();
2069
+
2070
+ for child in parent.children_with_tokens() {
2071
+ let is_entry = child.as_node().is_some()
2072
+ && matches!(
2073
+ child.as_node().unwrap().kind(),
2074
+ SyntaxKind::BLOCK_MAP_ENTRY | SyntaxKind::BLOCK_SEQ_ENTRY
2075
+ );
2076
+
2077
+ if is_entry {
2078
+ let entry_text = child.as_node().unwrap().text().to_string();
2079
+
2080
+ if groups.is_empty() {
2081
+ let preceding = buffer.trim_start_matches('\n').to_string();
2082
+
2083
+ groups.push(EntryGroup {
2084
+ separator: String::new(),
2085
+ preceding,
2086
+ body: entry_text,
2087
+ });
2088
+ } else {
2089
+ let (trailing, separator, preceding) = split_at_blank_line(&buffer);
2090
+
2091
+ if let Some(last) = groups.last_mut() {
2092
+ last.body.push_str(&trailing);
2093
+ }
2094
+
2095
+ groups.push(EntryGroup {
2096
+ separator,
2097
+ preceding,
2098
+ body: entry_text,
2099
+ });
2100
+ }
2101
+
2102
+ buffer.clear();
2103
+ } else {
2104
+ let text = match &child {
2105
+ rowan::NodeOrToken::Node(node) => node.text().to_string(),
2106
+ rowan::NodeOrToken::Token(token) => token.text().to_string(),
2107
+ };
2108
+
2109
+ buffer.push_str(&text);
2110
+ }
2111
+ }
2112
+
2113
+ if let Some(last) = groups.last_mut() {
2114
+ let trimmed = buffer.trim_end_matches(['\n', ' ', '\t']);
2115
+
2116
+ if !trimmed.is_empty() {
2117
+ last.body.push_str(trimmed);
2118
+ }
2119
+ }
2120
+
2121
+ for group in &mut groups {
2122
+ let trimmed = group.body.trim_end_matches(['\n', ' ', '\t']);
2123
+
2124
+ group.body = trimmed.to_string();
2125
+ }
2126
+
2127
+ groups
2128
+ }
2129
+
2130
+ fn split_at_blank_line(text: &str) -> (String, String, String) {
2131
+ if let Some(position) = text.find("\n\n") {
2132
+ let trailing = text[..position].to_string();
2133
+ let rest = &text[position..];
2134
+ let content_start = rest.len() - rest.trim_start_matches('\n').len();
2135
+ let separator = rest[..content_start].to_string();
2136
+ let preceding = rest[content_start..].trim_end_matches(['\n', ' ', '\t']).to_string();
2137
+
2138
+ (trailing, separator, preceding)
2139
+ } else {
2140
+ (text.to_string(), String::new(), String::new())
2141
+ }
2142
+ }
2143
+
2144
+ fn collect_preceding_sibling_comments(parent: &SyntaxNode) -> (String, Option<rowan::TextSize>) {
2145
+ let mut comments: Vec<String> = Vec::new();
2146
+ let mut earliest_start = None;
2147
+ let mut node = parent.clone();
2148
+
2149
+ loop {
2150
+ let mut sibling = node.prev_sibling_or_token();
2151
+
2152
+ while let Some(ref element) = sibling {
2153
+ match element {
2154
+ rowan::NodeOrToken::Token(token) => {
2155
+ if token.kind() == SyntaxKind::COMMENT {
2156
+ comments.push(token.text().to_string());
2157
+ earliest_start = Some(token.text_range().start());
2158
+ } else if token.kind() == SyntaxKind::WHITESPACE {
2159
+ // Keep looking past whitespace
2160
+ } else {
2161
+ break;
2162
+ }
2163
+ }
2164
+ _ => break,
2165
+ }
2166
+
2167
+ sibling = match element {
2168
+ rowan::NodeOrToken::Token(token) => token.prev_sibling_or_token(),
2169
+ rowan::NodeOrToken::Node(node) => node.prev_sibling_or_token(),
2170
+ };
2171
+ }
2172
+
2173
+ if !comments.is_empty() {
2174
+ break;
2175
+ }
2176
+
2177
+ match node.parent() {
2178
+ Some(parent)
2179
+ if parent.kind() == SyntaxKind::BLOCK
2180
+ || parent.kind() == SyntaxKind::DOCUMENT
2181
+ || parent.kind() == SyntaxKind::BLOCK_MAP_VALUE
2182
+ || parent.kind() == SyntaxKind::BLOCK_SEQ_ENTRY =>
2183
+ {
2184
+ node = parent
2185
+ }
2186
+ _ => break,
2187
+ }
2188
+ }
2189
+
2190
+ comments.reverse();
2191
+ (comments.join("\n"), earliest_start)
2192
+ }
2193
+
2194
+ fn collect_groups_with_range(parent: &SyntaxNode) -> (Vec<EntryGroup>, TextRange) {
2195
+ let mut groups = collect_entry_groups(parent);
2196
+
2197
+ let (sibling_comments, earliest_start) = collect_preceding_sibling_comments(parent);
2198
+
2199
+ if !sibling_comments.is_empty() {
2200
+ if let Some(first) = groups.first_mut() {
2201
+ if first.preceding.is_empty() {
2202
+ first.preceding = sibling_comments;
2203
+ } else {
2204
+ first.preceding = format!("{}\n{}", sibling_comments, first.preceding);
2205
+ }
2206
+ }
2207
+ }
2208
+
2209
+ let range = match earliest_start {
2210
+ Some(start) => TextRange::new(start, parent.text_range().end()),
2211
+ None => parent.text_range(),
2212
+ };
2213
+
2214
+ (groups, range)
2215
+ }
2216
+
2217
+ fn rebuild_from_groups(groups: &[EntryGroup], indent: &str) -> String {
2218
+ let default_separator = groups
2219
+ .iter()
2220
+ .find(|group| !group.separator.is_empty())
2221
+ .map(|group| group.separator.clone())
2222
+ .unwrap_or_else(|| "\n".to_string());
2223
+
2224
+ groups
2225
+ .iter()
2226
+ .enumerate()
2227
+ .map(|(index, group)| {
2228
+ if index == 0 {
2229
+ group.full_text()
2230
+ } else if group.preceding.is_empty() {
2231
+ format!("{}{}{}", default_separator, indent, group.body)
2232
+ } else {
2233
+ format!("{}{}\n{}{}", default_separator, group.preceding, indent, group.body)
2234
+ }
2235
+ })
2236
+ .collect()
2237
+ }