ninja-core 1.14.1

A powerful, cross-platform package manager and runtime for managing tools and plugins (shurikens)
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use crate::scripting::NinjaEngine;
use crate::{common::types::FieldValue, manager::ShurikenManager};
use anyhow::{Error, Result, bail};
use either::Either;
use log::debug;
use shlex::split;
use std::env;
use std::sync::Arc;
use std::{io, path::PathBuf, process::Stdio};
use tokio::process::Command as SubprocessCommand;
use tokio::sync::RwLock;

/// Commands that can be executed within the Ninja DSL.
///
/// These commands are parsed from DSL scripts and executed to manage Shurikens.
#[derive(Debug, Clone)]
pub enum Command {
    /// Start an HTTP API server on the specified port
    HttpStart(u16),
    /// Start the currently selected Shuriken
    Start,
    /// Stop the currently selected Shuriken
    Stop,
    /// Select a Shuriken by name for subsequent operations
    Select(String),
    /// Get a configuration value by key
    Get(String),
    /// Deselect the current Shuriken
    Exit,
    /// Configure the currently selected Shuriken
    Configure,
    /// Configure the currently selected Shuriken with specific key-value pairs
    ConfigureBlock(Vec<(String, FieldValue)>),
    /// Set a configuration key to a value
    Set { key: String, value: FieldValue },
    /// List all available Shurikens
    List,
    /// List all Shurikens with their current states
    ListState,
    /// Install a new Shuriken from a URL, registry entry, or file path
    Install(String),
    /// Toggle a boolean configuration value
    Toggle(String),
    /// Execute a Ninja script file
    Execute(PathBuf),
    /// Display help information
    Help,
    /// No-op command
    None,
}

// -----------------
// Parsing helpers
// -----------------

/// Removes single-line comments from a line of code.
///
/// Supports both `//` and `#` comment delimiters.
/// Returns the text up to the first comment marker.
fn strip_comments(line: &str) -> &str {
    if let Some(i) = line.find("//") {
        &line[..i]
    } else if let Some(i) = line.find('#') {
        &line[..i]
    } else {
        line
    }
}

/// Parses a raw string into a typed `FieldValue`.
///
/// Supports quoted strings, booleans (`true`/`false`), and integers.
/// Falls back to a string if no specific type matches.
fn parse_value(raw: &str) -> FieldValue {
    let v = raw.trim();

    // quoted string support
    if (v.starts_with('"') && v.ends_with('"')) || (v.starts_with('\'') && v.ends_with('\'')) {
        let inner = &v[1..v.len() - 1];
        return FieldValue::String(inner.to_string());
    }

    // boolean
    match v.to_ascii_lowercase().as_str() {
        "true" => return FieldValue::Bool(true),
        "false" => return FieldValue::Bool(false),
        _ => {}
    }

    // integer (i64)
    if let Ok(i) = v.parse::<i64>() {
        return FieldValue::Number(i);
    }

    // fallback: raw string
    FieldValue::String(v.to_string())
}

/// Parses a single key-value assignment (e.g., `key = value`).
///
/// # Returns
/// - `Ok(Some((key, value)))` if a valid assignment is found
/// - `Ok(None)` if the line is empty or not an assignment
/// - `Err` if the assignment is malformed (e.g., empty key)
fn parse_kv(text: &str) -> Result<Option<(String, FieldValue)>> {
    let t = text.trim();
    if t.is_empty() {
        return Ok(None);
    }

    if let Some((left, right)) = t.split_once('=') {
        let key = left.trim();
        let val = right.trim();

        if key.is_empty() {
            bail!("Invalid assignment (empty key): `{}`", text);
        }

        // support trailing semicolon being present on the right side
        let val = val.trim_end_matches(';').trim();
        Ok(Some((key.to_string(), parse_value(val))))
    } else {
        // not an assignment (maybe a standalone token) — ignore gracefully
        Ok(None)
    }
}

/// Collects the content of a block delimited by `{` and `}`.
///
/// Supports both inline blocks (`{ content }`) and multiline blocks.
/// Skips comments while collecting lines.
///
/// # Arguments
/// - `first_after_brace`: Content on the same line after the opening `{`
/// - `lines`: Iterator over remaining lines
///
/// # Returns
/// - `Ok(content)` if the block was successfully collected
/// - `Err` if no closing `}` is found
fn collect_block<'a, I>(first_after_brace: &'a str, lines: &mut I) -> Result<String>
where
    I: Iterator<Item = &'a str>,
{
    // If the `first_after_brace` already contains the closing brace on same line
    let trimmed_after = first_after_brace.trim();

    if let Some(inner) = trimmed_after.strip_suffix("}") {
        // slice out trailing `}` and return
        return Ok(inner.trim().to_string());
    }

    // Start with what's after the brace on the first line
    let mut collected = String::new();
    if !trimmed_after.is_empty() {
        collected.push_str(trimmed_after);
        collected.push('\n');
    }

    // gather until we find a line containing a `}` (allow trailing whitespace)
    for next in lines {
        let stripped = strip_comments(next).trim();
        if let Some(inner) = stripped.strip_suffix('}') {
            if !inner.trim().is_empty() {
                collected.push_str(inner.trim());
            }
            return Ok(collected.trim().to_string());
        } else if !stripped.is_empty() {
            collected.push_str(stripped);
            collected.push('\n');
        }
    }

    // If we get here: no closing brace found
    bail!("Missing closing '}}' for block");
}

/// Parses a DSL script into a sequence of `Command` objects.
///
/// Handles comments, block syntax for configure, and token-based command parsing.
/// Supports both legacy and rich configure block syntax.
///
/// # Returns
/// - `Ok(commands)` with the parsed command sequence
/// - `Err` if parsing fails
fn command_parser(script: &str) -> Result<Vec<Command>> {
    let mut commands = Vec::new();

    // iterate over raw lines but keep ownership as &str slices from script.lines()
    let mut lines = script.lines();

    // We need an iterator that allows peeking; we'll manually consume lines as needed
    while let Some(raw_line) = lines.next() {
        // remove comments first
        let no_comment = strip_comments(raw_line);
        let trimmed = no_comment.trim();
        if trimmed.is_empty() {
            continue;
        }

        // ---------- CONFIGURE BLOCK detection ----------
        // handle: configure { ... }  (inline or multiline)
        if trimmed.starts_with("configure") {
            // after the word `configure`, find '{' if present
            if let Some((_, after_brace)) = trimmed.split_once('{') {
                // collect inner content (inline or multiline)
                let block_content = collect_block(after_brace, &mut lines)?;
                // split by semicolons or newlines and parse assignments
                let mut kvs: Vec<(String, FieldValue)> = Vec::new();

                for chunk in block_content.split([';', '\n']) {
                    if let Some((k, v)) = parse_kv(chunk)? {
                        kvs.push((k, v));
                    }
                }

                commands.push(Command::ConfigureBlock(kvs));
                continue;
            } else {
                // no brace on this line — treat as `configure` (legacy)
                commands.push(Command::Configure);
                continue;
            }
        }

        // ---------- FALLBACK: use shlex tokenization like before ----------
        // allow tokens with quotes and splitting similar to previous implementation
        if let Some(tokens) = split(trimmed) {
            let tokens: Vec<String> = tokens
                .into_iter()
                .filter(|token| {
                    let token = token.trim();
                    !token.is_empty() && token != "="
                })
                .collect();

            if tokens.is_empty() {
                continue;
            }

            let cmd = match tokens[0].as_str() {
                "http" => Command::HttpStart(tokens[1].parse().unwrap_or(80)),
                "start" => Command::Start,
                "stop" => Command::Stop,
                "select" => {
                    if tokens.len() > 1 {
                        Command::Select(tokens[1].clone())
                    } else {
                        Command::None
                    }
                }
                "help" => Command::Help,
                "get" => {
                    if tokens.len() > 1 {
                        Command::Get(tokens[1].clone())
                    } else {
                        Command::None
                    }
                }
                "set" => {
                    if tokens.len() > 2 {
                        Command::Set {
                            key: tokens[1].clone(),
                            value: parse_value(tokens[2].as_str()),
                        }
                    } else {
                        Command::None
                    }
                }
                "list" => {
                    if tokens.len() > 1 && tokens[1].eq_ignore_ascii_case("state") {
                        Command::ListState
                    } else {
                        Command::List
                    }
                }
                "install" => {
                    if tokens.len() > 1 {
                        Command::Install(tokens[1].clone())
                    } else {
                        Command::None
                    }
                }
                "toggle" => {
                    if tokens.len() > 1 {
                        Command::Toggle(tokens[1].clone())
                    } else {
                        Command::None
                    }
                }
                "execute" => {
                    if tokens.len() > 1 {
                        Command::Execute(PathBuf::from(tokens[1].clone()))
                    } else {
                        Command::None
                    }
                }
                "exit" => Command::Exit,
                "configure" => Command::Configure, // fallback if no {}
                _ => Command::None,
            };

            commands.push(cmd);
        }
    }

    Ok(commands)
}

// ==================
// Helper Function
// ==================

/// Locates the ninja CLI executable (`shurikenctl` or `shurikenctl.exe`).
///
/// Searches in the same directory as the current executable.
///
/// # Returns
/// - `Ok(path)` if the CLI executable is found
/// - `Err` if the executable cannot be found or the current executable location is unknown
fn locate_ninja_cli() -> Result<PathBuf> {
    let exe_path = env::current_exe()?;
    if let Some(root) = exe_path.parent() {
        let cli_path = if cfg!(windows) {
            root.join("shurikenctl.exe")
        } else {
            root.join("shurikenctl")
        };

        if !cli_path.exists() {
            return Err(Error::msg("No ninja CLI found"));
        }

        Ok(cli_path)
    } else {
        Err(Error::msg(
            "No parent directory? where and how did you run this? please email me i'm genuinely curious. -- Hannan \"tunafysh\" Smani",
        ))
    }
}

/// Context for executing Ninja DSL commands.
///
/// Maintains the manager reference and currently selected Shuriken.
pub struct DslContext {
    /// Reference to the Shuriken manager
    pub manager: ShurikenManager,
    /// Currently selected Shuriken name (if any)
    pub selected: Arc<RwLock<Option<String>>>,
}

impl DslContext {
    /// Creates a new DSL context with the given manager.
    ///
    /// # Arguments
    /// - `manager`: The Shuriken manager
    ///
    /// # Returns
    /// A new `DslContext` with no Shuriken selected
    pub fn new(manager: ShurikenManager) -> Self {
        Self {
            manager,
            selected: Arc::new(RwLock::new(None)),
        }
    }
}

/// Parses and executes a series of DSL commands.
///
/// Processes the DSL script, executing each command in sequence
/// and collecting output messages.
///
/// # Arguments
/// - `ctx`: DSL execution context with manager and selected Shuriken
/// - `script`: The DSL script string to execute
///
/// # Returns
/// - `Ok(output)` with a vector of output messages from command execution
/// - `Err` if parsing or execution fails
pub async fn execute_commands(ctx: &DslContext, script: String) -> Result<Vec<String>> {
    let parsed_commands = command_parser(script.as_str())?;

    let mut output: Vec<String> = Vec::new();

    for command in parsed_commands {
        match command {
            // HTTP server
            Command::HttpStart(port) => {
                let path = locate_ninja_cli()?;
                SubprocessCommand::new(path)
                    .arg("api")
                    .arg(port.to_string())
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit())
                    .stdin(Stdio::inherit())
                    .status()
                    .await?;
                output.push(format!("HTTP server started on port {}", port));
            }

            // Select shuriken
            Command::Select(name) => {
                debug!("Shurikens: {:#?}", ctx.manager.shurikens.read().await);
                if ctx.manager.shurikens.read().await.contains_key(&name) {
                    *ctx.selected.write().await = Some(name.clone());
                    output.push(format!("Selected shuriken '{}'", name));
                } else {
                    output.push(format!("No such shuriken: {}", name));
                }
            }

            // simple legacy configure
            Command::Configure => {
                if let Some(name) = &*ctx.selected.read().await {
                    let mut shurikens = ctx.manager.shurikens.write().await;
                    if let Some(shuriken) = shurikens.get_mut(name) {
                        let path = &ctx.manager.root_path;
                        shuriken
                            .configure(
                                path,
                                &*ctx.manager.engine.lock().await,
                                Some(ctx.manager.clone()),
                            )
                            .await
                            .map_err(Error::msg)?;

                        output.push(format!(
                            "Generated configuration for shuriken {} successfully.",
                            &name
                        ));
                    }
                }
            }

            // New: configure block
            Command::ConfigureBlock(kvs) => {
                if let Some(shuriken_name) = &*ctx.selected.read().await {
                    let mut shurikens = ctx.manager.shurikens.write().await;
                    if let Some(shuriken) = shurikens.get_mut(shuriken_name)
                        && let Some(cfg) = &mut shuriken.config
                    {
                        let partial_options = cfg.options.get_or_insert_with(Default::default);
                        for (k, v) in kvs {
                            partial_options.insert(k.clone(), v.clone());
                            output.push(format!(
                                "Set {} = {} for {}",
                                k,
                                v.render(),
                                shuriken_name
                            ));
                        }
                    } else {
                        output.push("No selected shuriken or missing config while applying configure block.".to_string());
                    }
                } else {
                    output.push("No shuriken selected — configure block ignored.".into());
                }
            }

            Command::Help => {
                output.push(
                    "Available commands:
                  http start <port>        - Start the HTTP server
                  select <name>            - Select a shuriken
                  configure                - Generate configuration for the selected shuriken
                  configure { k = v }      - Apply config assignments to the selected shuriken
                  set <key> <value>        - Set a config key for the selected shuriken
                  get <key>                - Get a config key's value
                  toggle <key>             - Toggle a boolean config key
                  start                    - Start the selected shuriken
                  stop                     - Stop the selected shuriken
                  install <url | registry_entry | path>           - Install a new shuriken from a file, url or a registry entry
                  list                     - List all shurikens
                  list state               - List shurikens with their states
                  execute <script>         - Run a Ninja script file
                  exit                     - Deselect current shuriken
                  help                     - Show this message"
                        .to_string(),
                );
            }

            // Config commands
            Command::Set { key, value } => {
                if let Some(shuriken_name) = &*ctx.selected.read().await {
                    let mut shurikens = ctx.manager.shurikens.write().await;
                    if let Some(shuriken) = shurikens.get_mut(shuriken_name)
                        && let Some(cfg) = &mut shuriken.config
                    {
                        let cloned_value: FieldValue = value.clone();
                        if let Some(partial_options) = &mut cfg.options {
                            partial_options.insert(key.clone(), FieldValue::from(value.render()));
                        }

                        output.push(format!(
                            "Set {} = {} for {}",
                            key,
                            cloned_value.render(),
                            shuriken_name
                        ));
                    }
                }
            }

            Command::Get(key) => {
                if let Some(shuriken_name) = &*ctx.selected.read().await {
                    let shurikens = ctx.manager.shurikens.read().await;
                    if let Some(shuriken) = shurikens.get(shuriken_name)
                        && let Some(cfg) = &shuriken.config
                        && let Some(options) = &cfg.options
                    {
                        output.push(format!("{:?} = {:?}", key, options.get(&key)));
                    }
                }
            }

            Command::Toggle(key) => {
                if let Some(shuriken_name) = &*ctx.selected.read().await {
                    let mut shurikens = ctx.manager.shurikens.write().await;
                    if let Some(shuriken) = shurikens.get_mut(shuriken_name)
                        && let Some(cfg) = &mut shuriken.config
                        && let Some(options) = &mut cfg.options
                        && let Some(FieldValue::Bool(value)) = options.get_mut(&key)
                    {
                        *value = !*value;
                        output.push(format!("Toggled {} to {}", key, value));
                    }
                }
            }

            // Shuriken management
            Command::List => {
                if let Either::Right(names) = ctx.manager.list(false).await? {
                    output.push(format!("Shurikens: {:?}", names))
                }
            }
            Command::ListState => {
                if let Either::Left(states) = ctx.manager.list(true).await? {
                    for (name, state) in states {
                        output.push(format!("{} -> {:?}", name, state));
                    }
                }
            }

            Command::Start => {
                if let Some(name) = &*ctx.selected.read().await {
                    match ctx.manager.start(name).await {
                        Ok(_) => output.push(format!("Started {}", name)),
                        Err(e) => output.push(format!("Error: {}", e)),
                    }
                }
            }
            Command::Stop => {
                if let Some(name) = &*ctx.selected.read().await {
                    match ctx.manager.stop(name).await {
                        Ok(_) => output.push(format!("Stopped {}", name)),
                        Err(e) => output.push(format!("Error: {}", e)),
                    }
                }
            }

            Command::Execute(script_path) => {
                let engine = NinjaEngine::new()
                    .await
                    .map_err(|e| io::Error::other(e.to_string()))?;
                engine
                    .execute_file(&script_path, None, Some(ctx.manager.clone()))
                    .await
                    .map_err(|e| io::Error::other(e.to_string()))?;
            }
            Command::Install(file_path) => match ctx.manager.install(&file_path).await {
                Ok(_) => output.push("Installed successfully".into()),
                Err(e) => output.push(format!("Install failed: {}", e)),
            },

            // Exit the shuriken
            Command::Exit => {
                if ctx.selected.write().await.is_some() {
                    *ctx.selected.write().await = None;
                    output.push("Discarded current shuriken".into());
                } else {
                    output.push("Cannot exit when there's no shuriken to discard.".into());
                }
            }

            // Unsupported
            Command::None => {
                output.push("Invalid or unsupported command.".to_string());
            }
        }
    }

    Ok(output)
}

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

    #[test]
    fn test_strip_comments() {
        // Test with // comment
        assert_eq!(strip_comments("code // comment"), "code ");

        // Test with # comment
        assert_eq!(strip_comments("code # comment"), "code ");

        // Test with no comment
        assert_eq!(strip_comments("code"), "code");

        // Test with empty line
        assert_eq!(strip_comments(""), "");

        // Test with only comment
        assert_eq!(strip_comments("// comment"), "");
        assert_eq!(strip_comments("# comment"), "");
    }

    #[test]
    fn test_parse_value() {
        // Test string with double quotes
        let val = parse_value("\"hello\"");
        match val {
            FieldValue::String(s) => assert_eq!(s, "hello"),
            _ => panic!("Expected String"),
        }

        // Test string with single quotes
        let val = parse_value("'world'");
        match val {
            FieldValue::String(s) => assert_eq!(s, "world"),
            _ => panic!("Expected String"),
        }

        // Test boolean true
        let val = parse_value("true");
        match val {
            FieldValue::Bool(b) => assert!(b),
            _ => panic!("Expected Bool"),
        }

        // Test boolean false
        let val = parse_value("false");
        match val {
            FieldValue::Bool(b) => assert!(!b),
            _ => panic!("Expected Bool"),
        }

        // Test integer
        let val = parse_value("42");
        match val {
            FieldValue::Number(n) => assert_eq!(n, 42),
            _ => panic!("Expected Number"),
        }

        // Test fallback to string
        let val = parse_value("unquoted");
        match val {
            FieldValue::String(s) => assert_eq!(s, "unquoted"),
            _ => panic!("Expected String"),
        }
    }

    #[test]
    fn test_parse_kv() {
        // Test valid key-value pair
        let result = parse_kv("key = value").unwrap();
        assert!(result.is_some());
        let (k, v) = result.unwrap();
        assert_eq!(k, "key");
        match v {
            FieldValue::String(s) => assert_eq!(s, "value"),
            _ => panic!("Expected String"),
        }

        // Test with trailing semicolon
        let result = parse_kv("key = value;").unwrap();
        assert!(result.is_some());
        let (k, _) = result.unwrap();
        assert_eq!(k, "key");

        // Test empty line
        let result = parse_kv("").unwrap();
        assert!(result.is_none());

        // Test empty key (should fail)
        let result = parse_kv("= value");
        assert!(result.is_err());

        // Test no equals sign (should return None)
        let result = parse_kv("standalone").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_collect_block_inline() {
        let lines_vec: Vec<&str> = vec![];
        let mut lines = lines_vec.iter().copied();

        // Test inline block with closing brace on same line
        let result = collect_block("key = value }", &mut lines);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "key = value");
    }

    #[test]
    fn test_collect_block_multiline() {
        let lines_vec = vec!["line2", "line3 }"];
        let mut lines = lines_vec.iter().copied();

        // Test multiline block
        let result = collect_block("line1", &mut lines);
        assert!(result.is_ok());
        let content = result.unwrap();
        assert!(content.contains("line1"));
        assert!(content.contains("line2"));
        assert!(content.contains("line3"));
    }

    #[test]
    fn test_collect_block_missing_closing() {
        let lines_vec = vec!["line2", "line3"];
        let mut lines = lines_vec.iter().copied();

        // Test missing closing brace
        let result = collect_block("line1", &mut lines);
        assert!(result.is_err());
    }

    #[test]
    fn test_command_parser_simple() {
        // Test simple commands
        let script = "start\nstop\nlist";
        let result = command_parser(script).unwrap();
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_command_parser_with_comments() {
        // Test commands with comments
        let script = "start // start the service\nstop # stop it";
        let result = command_parser(script).unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_command_parser_configure_block() {
        // Test configure block parsing
        let script = "configure { key1 = value1; key2 = 42 }";
        let result = command_parser(script).unwrap();
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::ConfigureBlock(kvs) => {
                assert_eq!(kvs.len(), 2);
                assert_eq!(kvs[0].0, "key1");
            }
            _ => panic!("Expected ConfigureBlock"),
        }
    }

    #[test]
    fn test_command_parser_empty_lines() {
        // Test handling of empty lines
        let script = "\n\nstart\n\n\nstop\n\n";
        let result = command_parser(script).unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_command_parser_select() {
        // Test select command
        let script = "select myservice";
        let result = command_parser(script).unwrap();
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Select(name) => assert_eq!(name, "myservice"),
            _ => panic!("Expected Select"),
        }
    }

    #[test]
    fn test_command_parser_set() {
        // Test set command
        let script = "set key value";
        let result = command_parser(script).unwrap();
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Set { key, .. } => assert_eq!(key, "key"),
            _ => panic!("Expected Set"),
        }
    }
}