clitest-lib 0.2.6

CLI-based testing library.
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
use crate::command::CommandLine;
use crate::parser::v0::ESCAPED_MULTILINE;
use crate::parser::v0::LITERAL_MULTILINE;
use crate::parser::v0::REGEX_MULTILINE;
use crate::script::*;
use crate::util::ShellBit;
use crate::util::shell_split;

#[derive(Debug, Clone, derive_more::IsVariant, derive_more::Unwrap)]
pub enum BlockType {
    /// A command block.
    Command(CommandLine),
    /// Comments and whitespace lines.
    Ineffectual,
    /// Pattern lines.
    Pattern,
    /// Meta lines (`%EXPECT_FAILURE`, `%EXIT`, etc.).
    Meta,
    /// Any (`*`) block
    Any,
}

impl BlockType {
    pub fn is_same_type_as(&self, other: &Self) -> bool {
        matches!(
            (self, other),
            (BlockType::Command(_), BlockType::Command(_))
                | (BlockType::Ineffectual, BlockType::Ineffectual)
                | (BlockType::Pattern, BlockType::Pattern)
                | (BlockType::Meta, BlockType::Meta)
                | (BlockType::Any, BlockType::Any)
        )
    }
}

pub struct ScriptV0Block {
    pub location: ScriptLocation,
    pub block_type: BlockType,
    pub lines: Vec<ScriptLine>,
}

impl ScriptV0Block {
    /// Take the current block, replacing with an empty block at the given location.
    pub fn take(&mut self, location: ScriptLocation, block_type: BlockType) -> Self {
        Self {
            location: std::mem::replace(&mut self.location, location),
            block_type: std::mem::replace(&mut self.block_type, block_type),
            lines: std::mem::take(&mut self.lines),
        }
    }

    /// Split the first pattern line from the rest. If not a pattern block,
    /// return None. May leave an empty block if the first line is the only line.
    pub fn split_first(&mut self) -> Option<Self> {
        match self.block_type {
            BlockType::Pattern => {
                let lines = &mut self.lines;
                if lines.is_empty() {
                    debug_assert!(false, "split_first called on empty pattern block");
                    return None;
                }
                let first = lines.remove(0);
                Some(Self {
                    location: first.location.clone(),
                    block_type: BlockType::Pattern,
                    lines: vec![first],
                })
            }
            _ => None,
        }
    }
}

impl std::fmt::Debug for ScriptV0Block {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if f.alternate() {
            let indent = f.width().unwrap_or_default();
            let indent = " ".repeat(indent);
            // HACK: Repurpose width as indent
            // Left-pad by "indent" spaces
            let c = match self.block_type {
                BlockType::Command(_) => "$",
                BlockType::Ineffectual => "#",
                BlockType::Pattern => "",
                BlockType::Meta => "%",
                BlockType::Any => "*",
            };
            writeln!(f, "{indent}:{} {c}[", self.location.line)?;
            for line in &self.lines {
                writeln!(f, "{indent}  {:?}", line.text())?;
            }
            write!(f, "{indent}]")?;
            Ok(())
        } else {
            f.debug_struct("ScriptBlock")
                .field("location", &self.location)
                .field("block_type", &self.block_type)
                .field("lines", &self.lines)
                .finish()
        }
    }
}

/// A segment of a script. This is the first stage of parsing, where we split
/// the script.
pub enum ScriptV0Segment {
    Block(ScriptV0Block),
    SubBlock(ScriptLocation, String, Vec<ShellBit>, Vec<ScriptV0Segment>),
    Semi(ScriptLocation, String, Vec<ShellBit>),
}

impl std::fmt::Debug for ScriptV0Segment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if f.alternate() {
            let indent = f.width().unwrap_or_default();
            let indent_str = " ".repeat(indent);
            // HACK: Indent the segments by using width, but don't print indent here
            match self {
                ScriptV0Segment::Block(block) => writeln!(f, "{block:#indent$?}"),
                ScriptV0Segment::SubBlock(location, text, args, segments) => {
                    writeln!(f, "{indent_str}:{} {text:?}{args:?} {{", location.line)?;
                    for segment in segments {
                        write!(f, "{segment:#indent$?}", indent = indent + 2)?;
                    }
                    writeln!(f, "{indent_str}}}")?;
                    Ok(())
                }
                ScriptV0Segment::Semi(location, text, args) => {
                    writeln!(f, "{indent_str}:{} {text:?}{args:?};", location.line)?;
                    Ok(())
                }
            }
        } else {
            match self {
                ScriptV0Segment::Block(block) => f
                    .debug_struct("Block")
                    .field("location", &block.location)
                    .field("block_type", &block.block_type)
                    .field("lines", &block.lines)
                    .finish(),
                ScriptV0Segment::SubBlock(location, text, args, segments) => f
                    .debug_struct("SubBlock")
                    .field("location", &location)
                    .field("text", &text)
                    .field("args", &args)
                    .field("segments", &segments)
                    .finish(),
                ScriptV0Segment::Semi(location, text, args) => f
                    .debug_struct("Semi")
                    .field("location", &location)
                    .field("text", &text)
                    .field("args", &args)
                    .finish(),
            }
        }
    }
}

impl ScriptV0Segment {
    pub fn is_empty(&self) -> bool {
        match self {
            ScriptV0Segment::Block(block) => block.lines.is_empty(),
            ScriptV0Segment::SubBlock(_, text, _args, segments) => {
                text != "*"
                    && (segments.is_empty() || segments.iter().all(|segment| segment.is_empty()))
            }
            ScriptV0Segment::Semi(..) => false,
        }
    }

    /// Used by wildcard handling.
    pub fn split_first(&mut self) -> Option<Self> {
        match self {
            ScriptV0Segment::Block(block) => block.split_first().map(ScriptV0Segment::Block),
            &mut ScriptV0Segment::SubBlock(ref location, ..) => {
                if self.is_command_block() {
                    None
                } else {
                    Some(std::mem::replace(
                        self,
                        ScriptV0Segment::Block(ScriptV0Block {
                            location: location.clone(),
                            block_type: BlockType::Ineffectual,
                            lines: vec![],
                        }),
                    ))
                }
            }
            ScriptV0Segment::Semi(..) => None,
        }
    }

    /// Returns true if this segment is a command block, or the first block it
    /// contains is a command block. Note that this should only be called on
    /// normalized segments.
    pub fn is_command_block(&self) -> bool {
        match self {
            ScriptV0Segment::Block(block) => block.block_type.is_command(),
            ScriptV0Segment::SubBlock(.., segments) => segments
                .iter()
                .any(|segment: &ScriptV0Segment| segment.is_command_block()),
            ScriptV0Segment::Semi(..) => true,
        }
    }

    pub fn location(&self) -> &ScriptLocation {
        match self {
            ScriptV0Segment::Block(block) => &block.location,
            ScriptV0Segment::SubBlock(location, ..) => location,
            ScriptV0Segment::Semi(location, ..) => location,
        }
    }

    #[allow(unused)]
    pub fn last_location(&self) -> &ScriptLocation {
        match self {
            ScriptV0Segment::Block(block) => &block.lines.last().unwrap().location,
            ScriptV0Segment::SubBlock(location, .., segments) => {
                if let Some(last) = segments.last() {
                    last.last_location()
                } else {
                    location
                }
            }
            ScriptV0Segment::Semi(location, ..) => location,
        }
    }
}

/// Split the script into parsing segments. These allow us to more easily parse
/// in later phases because we avoid having to check for block boundaries.
pub fn segment_script(
    top_level: bool,
    lines_slice: &mut &[ScriptLine],
) -> Result<Vec<ScriptV0Segment>, ScriptError> {
    let mut segments = Vec::new();
    let mut current_segment = None;

    fn is_subblock(text: &str) -> Result<Option<(bool, &str, &str)>, ScriptErrorType> {
        // Workaround for missing let chains
        if text.starts_with(|c: char| c.is_alphabetic()) {
            let is_semi = text.ends_with(';');
            let Some(text) = text.strip_suffix(|c: char| c == '{' || c == ';') else {
                return Err(ScriptErrorType::ExpectedBlockOrSemi);
            };
            if let Some((block_type, args)) = text.trim().split_once(char::is_whitespace) {
                Ok(Some((is_semi, block_type.trim(), args.trim())))
            } else {
                Ok(Some((is_semi, text.trim(), "")))
            }
        } else {
            Ok(None)
        }
    }

    let mut lines = lines_slice.iter();
    let orig_slice = *lines_slice;
    let mut multiline_terminator = None;
    while let Some(line) = lines.next() {
        if let Some(terminator) = multiline_terminator {
            if line.text() == terminator {
                multiline_terminator = None;
            }
        } else if line.text() == ESCAPED_MULTILINE {
            multiline_terminator = Some(ESCAPED_MULTILINE);
        } else if line.text() == REGEX_MULTILINE {
            multiline_terminator = Some(REGEX_MULTILINE);
        } else if line.text() == LITERAL_MULTILINE {
            multiline_terminator = Some(LITERAL_MULTILINE);
        }

        if multiline_terminator.is_some() {
            let segment = current_segment.get_or_insert(ScriptV0Block {
                block_type: BlockType::Pattern,
                lines: Vec::new(),
                location: line.location.clone(),
            });
            if !segment.block_type.is_same_type_as(&BlockType::Pattern) {
                segments.push(ScriptV0Segment::Block(
                    segment.take(line.location.clone(), BlockType::Pattern),
                ));
            }
            segment.lines.push(line.clone());
            continue;
        }

        // For commands, we greedily consume all lines until we successfully
        // parse a command (or fail to parse).
        if line.starts_with("$") {
            if let Some(segment) = current_segment.take() {
                segments.push(ScriptV0Segment::Block(segment));
            }
            let mut block_lines = vec![line.clone()];
            let mut command = line.text()[1..].trim().to_string();
            let mut line_count = 1;
            let command = loop {
                match parse_command_line(line.location.clone(), line_count, &command) {
                    Ok(command) => break command,
                    Err(e @ ScriptErrorType::UnclosedQuote)
                    | Err(e @ ScriptErrorType::UnclosedBackslash) => match lines.next() {
                        Some(line) => {
                            block_lines.push(line.clone());
                            command.push('\n');
                            command.push_str(line.text());
                            line_count += 1;
                        }
                        None => {
                            return Err(ScriptError::new(e, line.location.clone()));
                        }
                    },
                    Err(e) => {
                        return Err(ScriptError::new(e, line.location.clone()));
                    }
                }
            };

            segments.push(ScriptV0Segment::Block(ScriptV0Block {
                block_type: BlockType::Command(command),
                lines: block_lines,
                location: line.location.clone(),
            }));
        } else if let Some((is_semi, block_type, args)) =
            is_subblock(line.text()).map_err(|e| ScriptError::new(e, line.location.clone()))?
        {
            if let Some(segment) = current_segment.take() {
                segments.push(ScriptV0Segment::Block(segment));
            }

            let args = shell_split(args).map_err(|_| {
                ScriptError::new_with_data(
                    ScriptErrorType::InvalidBlockArgs,
                    line.location.clone(),
                    format!("{block_type} {args}"),
                )
            })?;

            if is_semi {
                segments.push(ScriptV0Segment::Semi(
                    line.location.clone(),
                    block_type.to_string(),
                    args,
                ));
            } else {
                // Temporaraliy swap from iterator to slice
                let mut rest = lines.as_slice();
                if rest.is_empty() {
                    return Err(ScriptError::new(
                        ScriptErrorType::InvalidBlockEnd,
                        line.location.clone(),
                    ));
                }

                segments.push(ScriptV0Segment::SubBlock(
                    line.location.clone(),
                    block_type.to_string(),
                    args,
                    segment_script(false, &mut rest)?,
                ));
                lines = rest.iter();
            }
        } else if line.text() == "}" {
            // Note that the closing brace is not included in the current
            // segment, we omit these lines from the segment tree.
            if top_level {
                return Err(ScriptError::new(
                    ScriptErrorType::InvalidBlockEnd,
                    line.location.clone(),
                ));
            }
            *lines_slice = lines.as_slice();
            if let Some(segment) = current_segment.take() {
                segments.push(ScriptV0Segment::Block(segment));
            }
            return Ok(segments);
        } else {
            // Split into ineffectual and non-ineffectual lines
            let block_type = if multiline_terminator.is_some() {
                BlockType::Pattern
            } else if line.starts_with("#") || line.is_empty() {
                BlockType::Ineffectual
            } else if line.starts_with("%") {
                BlockType::Meta
            } else if line.starts_with("*") {
                BlockType::Any
            } else {
                BlockType::Pattern
            };

            let segment = current_segment.get_or_insert(ScriptV0Block {
                block_type: block_type.clone(),
                lines: Vec::new(),
                location: line.location.clone(),
            });
            if !segment.block_type.is_same_type_as(&block_type) {
                segments.push(ScriptV0Segment::Block(
                    segment.take(line.location.clone(), block_type),
                ));
            }
            segment.lines.push(line.clone());
        }
    }

    if !top_level {
        return Err(ScriptError::new(
            ScriptErrorType::InvalidBlockEnd,
            orig_slice.last().unwrap().location.clone(),
        ));
    }

    if let Some(segment) = current_segment.take() {
        segments.push(ScriptV0Segment::Block(segment));
    }

    Ok(segments)
}

fn insert_virtual_end_block(location: ScriptLocation, segments: &mut Vec<ScriptV0Segment>) {
    let line = ScriptLine::new(location.file.clone(), location.line - 1, "end");

    segments.push(ScriptV0Segment::Block(ScriptV0Block {
        location: line.location.clone(),
        block_type: BlockType::Pattern,
        lines: vec![line],
    }));
}

/// Remove all ineffectual blocks, and merge consecutive blocks that are of the same type.
pub fn normalize_segments(segments: Vec<ScriptV0Segment>) -> Vec<ScriptV0Segment> {
    let mut new_segments = vec![];
    let mut command_needs_end = false;

    let Some(last_line) = segments.last().map(|segment| segment.location().clone()) else {
        return segments;
    };

    for mut segment in segments {
        if segment.is_command_block() && command_needs_end {
            insert_virtual_end_block(segment.location().clone(), &mut new_segments);
            command_needs_end = false;
        }
        match segment {
            ScriptV0Segment::Block(ref mut block) => {
                debug_assert!(
                    !block.lines.is_empty(),
                    "empty blocks should not exist here"
                );
                if block.block_type.is_ineffectual() {
                    continue;
                }
                if block.block_type.is_command() {
                    command_needs_end = true;
                }
                if let Some(ScriptV0Segment::Block(last_block)) = new_segments.last_mut() {
                    if block.block_type.is_command() {
                        new_segments.push(segment);
                    } else if block.block_type.is_same_type_as(&last_block.block_type) {
                        last_block.lines.extend(std::mem::take(&mut block.lines));
                    } else {
                        new_segments.push(segment);
                    }
                } else {
                    new_segments.push(segment);
                }
            }
            ScriptV0Segment::SubBlock(location, text, args, segments) => {
                let normalized = normalize_segments(segments);
                new_segments.push(ScriptV0Segment::SubBlock(location, text, args, normalized));
            }
            ScriptV0Segment::Semi(location, text, args) => {
                new_segments.push(ScriptV0Segment::Semi(location, text, args));
            }
        }
    }

    // Add a virtual "end" block to the end of the last command block.
    if command_needs_end {
        insert_virtual_end_block(last_line, &mut new_segments);
    }

    // Pass 2: Convert any "any"-type blocks to sub-blocks and steal the next line or non-command subblock.
    let mut i = 0;
    while i < new_segments.len() {
        if let ScriptV0Segment::Block(block) = &mut new_segments[i]
            && block.block_type.is_any()
        {
            let location = block.location.clone();
            new_segments[i] =
                ScriptV0Segment::SubBlock(location.clone(), "*".to_string(), vec![], vec![]);

            if i + 1 < new_segments.len()
                && let Some(first) = new_segments[i + 1].split_first()
            {
                new_segments[i] = ScriptV0Segment::SubBlock(
                    location.clone(),
                    "*".to_string(),
                    vec![],
                    vec![first],
                );
            }
        }
        if new_segments[i].is_empty() {
            new_segments.remove(i);
        } else {
            i += 1;
        }
    }

    new_segments
}

/// This does a light-weight parse of a command-line to most determine the
/// extent of the command-line. The shell is currently responsible for actual
/// validation and running of the command.
///
/// Important rules:
///
///  - Backslashes escape the next character, except within a single-quoted
///    string
///  - Newlines within quoted strings or after a backslash continue the shell
///    command to the next line
///  - Outside of a quoted string, a comment always ends the command-line
///
/// Returns:
///
///  - UnclosedQuote if the command-line is unclosed because of a missing quote
///  - UnclosedBackslash if the command-line is unclosed because of a missing
///    backslash
///  - IllegalShellCommand if the command-line is invalid
///  - BackgroundProcessNotAllowed if the command-line contains a background
///    process
///  - UnsupportedRedirection if the command-line contains an unsupported
///    redirection
pub fn parse_command_line(
    location: ScriptLocation,
    line_count: usize,
    command: &str,
) -> Result<CommandLine, ScriptErrorType> {
    let command_str = command.to_string();
    // Process the accumulated command
    const SEPARATORS: &[&[u8; 2]] = &[b"&&", b"||", b">&"];

    const SEPARATOR_CHARS: &[char] = &['>', '<', '&', '|', ';', '(', ')', '='];

    enum State {
        GroundFirst,
        Ground,
        Separator,
        SingleQuoted,
        DoubleQuoted,
        DoubleQuotedBackslash,
        Backslash,
        Comment,
    }

    let mut state = State::Ground;
    let mut last_char = '\0';

    for c in command.chars() {
        match state {
            State::GroundFirst => {
                if c == '\'' {
                    state = State::SingleQuoted;
                } else if c == '"' {
                    state = State::DoubleQuoted;
                } else if c == '\\' {
                    state = State::Backslash;
                } else if c == '\n' {
                    unreachable!("newline in ground state");
                } else if SEPARATOR_CHARS.contains(&c) {
                    state = State::Separator;
                } else if !c.is_ascii_whitespace() {
                    state = State::Ground;
                }
            }
            State::Ground => {
                if c == '\'' {
                    state = State::SingleQuoted;
                } else if c == '"' {
                    state = State::DoubleQuoted;
                } else if c == '\\' {
                    state = State::Backslash;
                } else if c == '#' {
                    state = State::Comment;
                } else if c == '\n' {
                    unreachable!("newline in ground state");
                } else if c.is_ascii_whitespace() {
                    state = State::GroundFirst;
                }
            }
            State::Separator => {
                let potential = [last_char as u8, c as u8];
                if c.is_ascii() && SEPARATORS.contains(&&potential) {
                    if &potential == b">&" {
                        return Err(ScriptErrorType::UnsupportedRedirection);
                    }
                    state = State::GroundFirst;
                } else {
                    if last_char == '&' {
                        return Err(ScriptErrorType::BackgroundProcessNotAllowed);
                    }
                    if c == '\'' {
                        state = State::SingleQuoted;
                    } else if c == '"' {
                        state = State::DoubleQuoted;
                    } else if c == '\\' {
                        state = State::Backslash;
                    } else if c == '#' {
                        state = State::Comment;
                    } else if c == '\n' {
                        unreachable!("newline in ground state");
                    } else if c.is_ascii_whitespace() {
                        state = State::GroundFirst;
                    }
                }
            }
            State::SingleQuoted => {
                if c == '\'' {
                    state = State::Ground;
                }
            }
            State::DoubleQuoted => {
                if c == '"' {
                    state = State::Ground;
                } else if c == '\\' {
                    state = State::DoubleQuotedBackslash;
                }
            }
            State::DoubleQuotedBackslash => {
                // Treat the next character as "not special"
                state = State::DoubleQuoted;
            }
            State::Backslash => {
                state = State::Ground;
            }
            State::Comment => {
                if c == '\n' {
                    state = State::Ground;
                }
            }
        }
        last_char = c;
    }

    match state {
        State::SingleQuoted | State::DoubleQuoted => Err(ScriptErrorType::UnclosedQuote),
        State::Separator if last_char == '&' => Err(ScriptErrorType::BackgroundProcessNotAllowed),
        State::Separator if last_char != ';' => Err(ScriptErrorType::IllegalShellCommand),
        State::Backslash | State::DoubleQuotedBackslash => Err(ScriptErrorType::UnclosedBackslash),
        State::Comment | State::Ground | State::GroundFirst | State::Separator => {
            Ok(CommandLine::new(command_str, location, line_count))
        }
    }
}

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

    #[test]
    fn test_segments() {
        let script = r#"
ignore {
  ! pattern
}
$ echo "hello"
ignore {
  ! pattern
}
$ echo "world"
"#;
        let lines = ScriptLine::parse(ScriptFile::new("test"), script);

        let segments = segment_script(true, &mut lines.as_slice()).unwrap();
        eprintln!("{segments:#?}");
        let normalized = normalize_segments(segments);
        eprintln!("{normalized:#?}");
    }

    #[test]
    fn test_parse_command_line() {
        let location = ScriptLocation::new(ScriptFile::new("test"), 1);

        let command = "echo 'hello' && echo 'world'";
        let command = parse_command_line(location.clone(), 1, command).unwrap();
        assert_eq!(command.command, "echo 'hello' && echo 'world'");

        let command = r#"echo "hello\n" && echo 'world'"#;
        let command = parse_command_line(location.clone(), 1, command).unwrap();
        assert_eq!(command.command, r#"echo "hello\n" && echo 'world'"#);

        let command = r#"echo "hello\x1b" && echo 'world'"#;
        let command = parse_command_line(location.clone(), 1, command).unwrap();
        assert_eq!(command.command, r#"echo "hello\x1b" && echo 'world'"#);
    }
}