parsm 0.2.0

Multi-format data processor that understands structured text better than sed or awk. Supports JSON, CSV, YAML, TOML, logfmt, and plain text with powerful filtering and templating.
Documentation
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
use clap::{Arg, Command};
use std::io;

use parsm::{
    parse_command, parse_separate_expressions, process_stream, FilterEngine, ParsedDSL, ParsedLine,
};

/// Main entry point for the parsm command-line tool.
///
/// Parsm is a multi-format data processor that understands structured text better than sed or awk.
/// It can parse JSON, CSV, TOML, YAML, logfmt, and plain text, applying filters and templates
/// to transform and extract data.
fn main() {
    let matches = Command::new(env!("CARGO_PKG_NAME"))
        .version(env!("CARGO_PKG_VERSION"))
        .author(env!("CARGO_PKG_AUTHORS"))
        .about("Understands structured text better than sed or awk")
        .arg(
            Arg::new("filter")
                .help("Filter expression (optional)")
                .value_name("FILTER")
                .index(1),
        )
        .arg(
            Arg::new("template")
                .help("Template expression for output formatting (optional)")
                .value_name("TEMPLATE")
                .index(2),
        )
        .arg(
            Arg::new("help-examples")
                .long("examples")
                .help("Show usage examples")
                .action(clap::ArgAction::SetTrue),
        )
        .get_matches();

    if matches.get_flag("help-examples") {
        print_usage_examples();
        return;
    }

    let filter_expr = matches.get_one::<String>("filter");
    let template_expr = matches.get_one::<String>("template");

    match (filter_expr, template_expr) {
        (Some(filter), Some(template)) if !filter.trim().is_empty() => {
            let parsed_dsl = match parse_separate_expressions(Some(filter), Some(template)) {
                Ok(dsl) => dsl,
                Err(e) => {
                    eprintln!("Error parsing filter and template expression: {e}");
                    std::process::exit(1);
                }
            };
            if let Err(e) = process_stream_with_filter(parsed_dsl) {
                eprintln!("Error processing stream: {e}");
                std::process::exit(1);
            }
        }
        (Some(_), Some(template)) => {
            let parsed_dsl = match parse_separate_expressions(None, Some(template)) {
                Ok(dsl) => dsl,
                Err(e) => {
                    eprintln!("Error parsing template expression: {e}");
                    std::process::exit(1);
                }
            };
            if let Err(e) = process_stream_with_filter(parsed_dsl) {
                eprintln!("Error processing stream: {e}");
                std::process::exit(1);
            }
        }
        (Some(filter), None) => {
            let parsed_dsl = match parse_command(filter) {
                Ok(dsl) => dsl,
                Err(e) => {
                    eprintln!("Error parsing expression: {e}");
                    std::process::exit(1);
                }
            };
            if let Err(e) = process_stream_with_filter(parsed_dsl) {
                eprintln!("Error processing stream: {e}");
                std::process::exit(1);
            }
        }
        (None, Some(template)) => {
            let parsed_dsl = match parse_separate_expressions(None, Some(template)) {
                Ok(dsl) => dsl,
                Err(e) => {
                    eprintln!("Error parsing template expression: {e}");
                    std::process::exit(1);
                }
            };
            if let Err(e) = process_stream_with_filter(parsed_dsl) {
                eprintln!("Error processing stream: {e}");
                std::process::exit(1);
            }
        }
        (None, None) => {
            let stdin = io::stdin();
            let mut stdout = io::stdout();

            if let Err(e) = process_stream(stdin.lock(), &mut stdout) {
                eprintln!("Error processing stream: {e}");
                std::process::exit(1);
            }
        }
    }
}

/// Process input stream with the parsed DSL (filters, templates, field selectors).
///
/// This function handles different processing modes:
/// - Field selection: Extract specific fields from JSON objects/arrays
/// - Filtering: Apply boolean expressions to filter input lines
/// - Templates: Format output using template expressions
///
/// # Arguments
/// * `dsl` - Parsed DSL containing optional filter, template, and field selector
///
/// # Returns
/// * `Ok(())` on successful processing
/// * `Err(Box<dyn std::error::Error>)` on processing errors
fn process_stream_with_filter(dsl: ParsedDSL) -> Result<(), Box<dyn std::error::Error>> {
    use parsm::StreamingParser;
    use std::io::{BufRead, Read, Write};
    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut writer = stdout.lock();

    // Only read entire input for field selectors, templates, or when necessary for document parsing
    if dsl.field_selector.is_some() || dsl.template.is_some() {
        // Field selectors and templates need the entire input to handle structured documents
        let mut input = String::new();
        stdin.lock().read_to_string(&mut input)?;

        // Try JSON array parsing first
        if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&input) {
            match &json_value {
                serde_json::Value::Array(arr) => {
                    if let Some(ref field_selector) = dsl.field_selector {
                        for item in arr {
                            if let Some(extracted) = field_selector.extract_field(item) {
                                writeln!(writer, "{extracted}")?;
                            }
                        }
                        return Ok(());
                    } else {
                        // For templates, process each array item
                        for item in arr {
                            let mut item_with_original = item.clone();
                            if let serde_json::Value::Object(ref mut obj) = item_with_original {
                                obj.insert(
                                    "$0".to_string(),
                                    serde_json::Value::String(input.trim().to_string()),
                                );
                            }
                            process_single_value(&item_with_original, &dsl, &mut writer)?;
                        }
                        return Ok(());
                    }
                }
                _ => {
                    if let Some(ref field_selector) = dsl.field_selector {
                        if let Some(extracted) = field_selector.extract_field(&json_value) {
                            writeln!(writer, "{extracted}")?;
                        }
                        return Ok(());
                    } else {
                        // For templates, process the single value
                        let mut value_with_original = json_value.clone();
                        if let serde_json::Value::Object(ref mut obj) = value_with_original {
                            obj.insert(
                                "$0".to_string(),
                                serde_json::Value::String(input.trim().to_string()),
                            );
                        }
                        process_single_value(&value_with_original, &dsl, &mut writer)?;
                        return Ok(());
                    }
                }
            }
        }

        // Try other document formats
        if try_parse_as_toml(&input, &dsl, &mut writer)?.is_some() {
            return Ok(());
        }

        if try_parse_as_yaml(&input, &dsl, &mut writer)?.is_some() {
            return Ok(());
        }

        // Fall back to line-by-line processing for field selectors
        if let Some(ref field_selector) = dsl.field_selector {
            let lines = input.lines();
            let mut parser = StreamingParser::new();
            let mut line_count = 0;

            for line in lines {
                line_count += 1;

                if line.trim().is_empty() {
                    continue;
                }

                match parser.parse_line(line) {
                    Ok(parsed_line) => {
                        let json_value = convert_parsed_line_to_json(parsed_line, line)?;
                        if let Some(extracted) = field_selector.extract_field(&json_value) {
                            writeln!(writer, "{extracted}")?;
                        } else {
                            writeln!(writer)?;
                            eprintln!(
                                "Warning: Field '{}' not found in line {}",
                                field_selector.parts.join("."),
                                line_count
                            );
                        }
                    }
                    Err(e) => {
                        if line_count == 1 {
                            return Err(Box::new(e));
                        } else {
                            eprintln!("Warning: Failed to parse line {line_count}: {e}");
                            eprintln!("Line content: {line}");
                        }
                    }
                }
            }
        } else {
            // For templates, fall back to line-by-line processing
            let lines = input.lines();
            let mut parser = StreamingParser::new();
            let mut line_count = 0;

            for line in lines {
                line_count += 1;

                if line.trim().is_empty() {
                    continue;
                }

                match parser.parse_line(line) {
                    Ok(parsed_line) => {
                        let json_value = convert_parsed_line_to_json(parsed_line, line)?;
                        process_single_value(&json_value, &dsl, &mut writer)?;
                    }
                    Err(e) => {
                        if line_count == 1 {
                            return Err(Box::new(e));
                        } else {
                            eprintln!("Warning: Failed to parse line {line_count}: {e}");
                            eprintln!("Line content: {line}");
                        }
                    }
                }
            }
        }
    } else {
        // For filters and templates, use true streaming (line-by-line processing)
        let reader = stdin.lock();
        let mut parser = StreamingParser::new();
        let mut line_count = 0;

        for line_result in reader.lines() {
            let line = line_result?;
            line_count += 1;

            if line.trim().is_empty() {
                continue;
            }

            match parser.parse_line(&line) {
                Ok(parsed_line) => {
                    let json_value = convert_parsed_line_to_json(parsed_line, &line)?;

                    let passes_filter = if let Some(ref filter) = dsl.filter {
                        FilterEngine::evaluate(filter, &json_value)
                    } else {
                        true
                    };

                    if passes_filter {
                        let output = if let Some(ref template) = dsl.template {
                            template.render(&json_value)
                        } else {
                            serde_json::to_string(&json_value)?
                        };
                        writeln!(writer, "{output}")?;
                    }
                }
                Err(e) => {
                    if line_count == 1 {
                        return Err(Box::new(e));
                    } else {
                        eprintln!("Warning: Failed to parse line {line_count}: {e}");
                        eprintln!("Line content: {line}");
                    }
                }
            }
        }
    }

    Ok(())
}

/// Convert a parsed line to a JSON value.
///
/// This function takes a `ParsedLine` from the parser and converts it to a `serde_json::Value`
/// for consistent processing. It also adds the original input as a special `$$` field.
///
/// # Arguments
/// * `parsed_line` - The parsed line data structure
/// * `original_input` - The original input string that was parsed
///
/// # Returns
/// * `Ok(serde_json::Value)` - The converted JSON value
/// * `Err(Box<dyn std::error::Error>)` - Conversion error
fn convert_parsed_line_to_json(
    parsed_line: ParsedLine,
    original_input: &str,
) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    use serde_json::Value;

    let json_value = match parsed_line {
        ParsedLine::Json(mut val) => {
            if let Value::Object(ref mut obj) = val {
                obj.insert("$0".to_string(), Value::String(original_input.to_string()));
            }
            val
        }
        ParsedLine::Csv(record) => {
            let mut obj = serde_json::Map::new();
            obj.insert("$0".to_string(), Value::String(original_input.to_string()));
            for (i, field) in record.iter().enumerate() {
                obj.insert(format!("field_{i}"), Value::String(field.to_string()));
            }
            let values: Vec<Value> = record
                .iter()
                .map(|field| Value::String(field.to_string()))
                .collect();
            obj.insert("_array".to_string(), Value::Array(values));
            Value::Object(obj)
        }
        ParsedLine::Toml(val) => {
            let mut json_val = serde_json::to_value(val)?;
            if let Value::Object(ref mut obj) = json_val {
                obj.insert("$0".to_string(), Value::String(original_input.to_string()));
            }
            json_val
        }
        ParsedLine::Yaml(val) => {
            let mut json_val = serde_json::to_value(val)?;
            if let Value::Object(ref mut obj) = json_val {
                obj.insert("$0".to_string(), Value::String(original_input.to_string()));
            }
            json_val
        }
        ParsedLine::Logfmt(mut val) => {
            if let Value::Object(ref mut obj) = val {
                obj.insert("$0".to_string(), Value::String(original_input.to_string()));
            }
            val
        }
        ParsedLine::Text(words) => {
            let mut obj = serde_json::Map::new();
            obj.insert("$0".to_string(), Value::String(original_input.to_string()));
            for (i, word) in words.iter().enumerate() {
                obj.insert(format!("word_{i}"), Value::String(word.clone()));
            }
            let values: Vec<Value> = words.into_iter().map(Value::String).collect();
            obj.insert("_array".to_string(), Value::Array(values));
            Value::Object(obj)
        }
    };
    Ok(json_value)
}

/// Print comprehensive usage examples and help documentation.
///
/// This function displays detailed examples of how to use parsm for various data processing
/// tasks including filtering, field selection, template formatting, and format conversion.
fn print_usage_examples() {
    println!("parsm - Multi-format data processor");
    println!();
    println!("EXAMPLES:");
    println!();
    println!("  # Filter JSON by field value:");
    println!(r#"  echo '{{"name": "Alice", "age": 30}}' | parsm 'name == "Alice"'"#);
    println!();
    println!("  # Field selection:");
    println!(r#"  echo '{{"name": "Alice", "age": 30}}' | parsm 'name'"#);
    println!();
    println!("  # Filter and format output (combined):");
    println!(
        r#"  echo '{{"name": "Alice", "age": 30}}' | parsm 'age > 25 {{${{name}} is ${{age}} years old}}'"#
    );
    println!();
    println!("  # Filter and format output (separate arguments):");
    println!(
        r#"  echo '{{"name": "Alice", "age": 30}}' | parsm 'age > 25' '${{name}} is ${{age}} years old'"#
    );
    println!();
    println!("  # Simple template variables:");
    println!(r#"  echo '{{"name": "Alice", "age": 30}}' | parsm '$name is $age years old'"#);
    println!();
    println!("  # Include original input with $0:");
    println!(r#"  echo 'Alice,30' | parsm '${{0}} → ${{1}} is ${{2}}'"#);
    println!();
    println!("  # Filter CSV data (fields accessible as field_0, field_1, etc.):");
    println!(
        r#"  echo 'Alice,30,Engineer' | parsm 'field_1 > "25" {{${{field_0}} - ${{field_2}}}}'"#
    );
    println!();
    println!("  # Filter logfmt logs:");
    println!(
        r#"  echo 'level=error msg="DB error" service=api' | parsm 'level == "error" {{[${{level}}] ${{msg}}}}'"#
    );
    println!();
    println!("  # Complex conditions:");
    println!(r#"  parsm 'name == "Alice" && age > 25 {{${{name}}: active}}'"#);
    println!();
    println!("  # Just convert formats (no filter):");
    println!("  echo 'name: Alice' | parsm  # YAML to JSON");
    println!();
    println!("OPERATORS:");
    println!("  ==, !=, <, <=, >, >=        # Comparison");
    println!("  contains, startswith, endswith  # String operations");
    println!("  &&, ||, !                   # Boolean logic");
    println!();
    println!("FIELD ACCESS:");
    println!("  name                        # Field selection (bare identifier)");
    println!("  \"name\"                      # Field selection (quoted)");
    println!("  user.email                  # Nested field");
    println!("  field_0, field_1            # CSV columns");
    println!("  word_0, word_1              # Text words");
    println!();
    println!("TEMPLATE VARIABLES:");
    println!("  ${{0}}                        # Entire original input");
    println!("  ${{1}}, ${{2}}, ${{3}}              # Indexed fields (1-based, requires braces)");
    println!("  $name, ${{user.email}}        # Named fields ($simple or ${{complex}})");
    println!("  $100                        # Literal dollar amounts (invalid variable names)");
    println!();
}

fn is_likely_toml(input: &str) -> bool {
    let lines: Vec<&str> = input.lines().take(10).collect(); // Check first 10 lines

    for line in &lines {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        // Look for key = value pattern typical of TOML
        if trimmed.contains(" = ") && !trimmed.starts_with('"') {
            return true;
        }

        // Look for TOML section headers
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            return true;
        }
    }

    false
}

/// Check if content looks like YAML format
fn is_likely_yaml(input: &str) -> bool {
    let lines: Vec<&str> = input.lines().take(10).collect(); // Check first 10 lines

    // YAML document start indicator
    if input.trim_start().starts_with("---") {
        return true;
    }

    let mut has_yaml_structure = false;

    for line in &lines {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        // Look for YAML key: value pattern (with colon and space)
        if trimmed.contains(": ") && !trimmed.starts_with('"') {
            has_yaml_structure = true;
        }

        // Look for YAML list items
        if trimmed.starts_with("- ") {
            has_yaml_structure = true;
        }

        // Look for indented structure (common in YAML)
        if line.starts_with("  ") && (line.contains(": ") || line.trim().starts_with("- ")) {
            return true; // Strong indicator of YAML structure
        }
    }

    has_yaml_structure
}

/// Try to parse input as TOML and process it
fn try_parse_as_toml(
    input: &str,
    dsl: &ParsedDSL,
    writer: &mut std::io::StdoutLock,
) -> Result<Option<()>, Box<dyn std::error::Error>> {
    // Only try TOML parsing if the input actually looks like TOML
    if !is_likely_toml(input) {
        return Ok(None);
    }

    if let Ok(toml_value) = toml::from_str::<toml::Value>(input) {
        let json_value = serde_json::to_value(toml_value)?;
        process_structured_value(json_value, input, dsl, writer)?;
        Ok(Some(()))
    } else {
        Ok(None)
    }
}

/// Try to parse input as YAML and process it
fn try_parse_as_yaml(
    input: &str,
    dsl: &ParsedDSL,
    writer: &mut std::io::StdoutLock,
) -> Result<Option<()>, Box<dyn std::error::Error>> {
    // Only try YAML parsing if the input actually looks like YAML
    if !is_likely_yaml(input) {
        return Ok(None);
    }

    if let Ok(yaml_value) = serde_yaml::from_str::<serde_yaml::Value>(input) {
        let json_value = serde_json::to_value(yaml_value)?;
        process_structured_value(json_value, input, dsl, writer)?;
        Ok(Some(()))
    } else {
        Ok(None)
    }
}

/// Process a structured value (JSON object/array, converted TOML/YAML)
fn process_structured_value(
    json_value: serde_json::Value,
    original_input: &str,
    dsl: &ParsedDSL,
    writer: &mut std::io::StdoutLock,
) -> Result<(), Box<dyn std::error::Error>> {
    match &json_value {
        serde_json::Value::Array(arr) => {
            // Process each item in array
            for item in arr {
                let mut item_with_original = item.clone();
                if let serde_json::Value::Object(ref mut obj) = item_with_original {
                    obj.insert(
                        "$0".to_string(),
                        serde_json::Value::String(original_input.trim().to_string()),
                    );
                }

                process_single_value(&item_with_original, dsl, writer)?;
            }
        }
        _ => {
            // Single object/value
            let mut value_with_original = json_value.clone();
            if let serde_json::Value::Object(ref mut obj) = value_with_original {
                obj.insert(
                    "$0".to_string(),
                    serde_json::Value::String(original_input.trim().to_string()),
                );
            }

            process_single_value(&value_with_original, dsl, writer)?;
        }
    }
    Ok(())
}

/// Process a single value with filter and template/field selector
fn process_single_value(
    value: &serde_json::Value,
    dsl: &ParsedDSL,
    writer: &mut std::io::StdoutLock,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::io::Write;

    let passes_filter = if let Some(ref filter) = dsl.filter {
        FilterEngine::evaluate(filter, value)
    } else {
        true
    };

    if passes_filter {
        if let Some(ref field_selector) = dsl.field_selector {
            if let Some(extracted) = field_selector.extract_field(value) {
                writeln!(writer, "{extracted}")?;
            }
        } else {
            let output = if let Some(ref template) = dsl.template {
                template.render(value)
            } else {
                serde_json::to_string(value)?
            };
            writeln!(writer, "{output}")?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Test JSON filtering with equality comparison.
    #[test]
    fn test_json_filtering() {
        let dsl = parse_command(r#"name == "Alice""#).unwrap();

        let json_data = json!({"name": "Alice", "age": 30});

        let passes = if let Some(ref filter) = dsl.filter {
            FilterEngine::evaluate(filter, &json_data)
        } else {
            true
        };

        assert!(passes);
    }

    /// Test template rendering with named field variables.
    #[test]
    fn test_template_rendering() {
        let dsl = parse_command(r#"name == "Alice" {${name} is ${age} years old}"#).unwrap();

        let json_data = json!({"name": "Alice", "age": 30});

        if let Some(ref template) = dsl.template {
            let output = template.render(&json_data);
            assert_eq!(output, "Alice is 30 years old");
        } else {
            panic!("Expected template");
        }
    }

    /// Test CSV data conversion to JSON format.
    #[test]
    fn test_csv_conversion() {
        use parsm::StreamingParser;

        let mut parser = StreamingParser::new();
        let csv_line = "Alice,30,Engineer";

        let result = parser.parse_line(csv_line).unwrap();
        let json_value = convert_parsed_line_to_json(result, csv_line).unwrap();

        assert_eq!(json_value["field_0"], "Alice");
        assert_eq!(json_value["field_1"], "30");
        assert_eq!(json_value["field_2"], "Engineer");
    }

    /// Test field selection parsing and extraction.
    #[test]
    fn test_field_selection() {
        let dsl = parse_command("\"State\"").unwrap();

        // Test that we have a field selector and no filter/template
        assert!(dsl.field_selector.is_some());
        assert!(dsl.filter.is_none());
        assert!(dsl.template.is_none());

        let field_selector = dsl.field_selector.unwrap();
        assert_eq!(field_selector.parts, vec!["State"]);

        let json_data = json!({
            "Id": "123",
            "State": {
                "Status": "running",
                "Running": true,
                "Pid": 2034
            },
            "Name": "container"
        });

        let extracted = field_selector.extract_field(&json_data).unwrap();
        let parsed_extracted: serde_json::Value = serde_json::from_str(&extracted).unwrap();

        assert_eq!(parsed_extracted["Status"], "running");
        assert_eq!(parsed_extracted["Running"], true);
        assert_eq!(parsed_extracted["Pid"], 2034);
    }

    /// Test nested field selection (e.g., "State.Status").
    #[test]
    fn test_nested_field_selection() {
        let dsl = parse_command("\"State.Status\"").unwrap();

        assert!(dsl.field_selector.is_some());
        let field_selector = dsl.field_selector.unwrap();
        assert_eq!(field_selector.parts, vec!["State", "Status"]);

        let json_data = json!({
            "State": {
                "Status": "running",
                "Running": true
            }
        });

        let extracted = field_selector.extract_field(&json_data).unwrap();
        assert_eq!(extracted, "running");
    }

    /// Test field selection behavior when field doesn't exist.
    #[test]
    fn test_field_selection_not_found() {
        let dsl = parse_command("\"NonExistent\"").unwrap();
        let field_selector = dsl.field_selector.unwrap();

        let json_data = json!({
            "State": {
                "Status": "running"
            }
        });

        let result = field_selector.extract_field(&json_data);
        assert!(result.is_none());
    }
}