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
//! This is a Rust crate to do "command line parsing". No, I'm not talking
//! about parsing command line *arguments* that were passed to your program;
//! for that purpose, I recommend the excellent [Clap][1] crate (with features
//! `wrap_help` and `derive` enabled). What this crate does is take a *line of
//! text* and parse it like a command line. In other words, it parses shellish.
//!
//! This is useful if you're implementing any kind of interactive system where
//! a user needs to be able to input commands.
//!
//! [1]: https://crates.io/crates/clap
//!
//! # Usage
//!
//! Add `shellish_parse` to your `Cargo.toml`:
//!
//! ```toml
//! shellish_parse = "2.2"
//! ```
//!
//! Use `shellish_parse::parse` to parse some shellish:
//!
//! ```rust
//! let line = "Hello World";
//! assert_eq!(shellish_parse::parse(line, false).unwrap(), &[
//! "Hello", "World"
//! ]);
//! ```
//!
//! The first parameter, a `&str`, is the line to parse. The second parameter,
//! a can be a `bool`, indicating whether an unrecognized escape sequence
//! should be an error:
//!
//! ```rust
//! let line = r#"In\mvalid"#; // note: raw string
//! assert_eq!(shellish_parse::parse(line, false).unwrap(), &[
//! "In�valid"
//! ]);
//! assert_eq!(shellish_parse::parse(line, true).unwrap_err(),
//! shellish_parse::ParseError::UnrecognizedEscape("\\m".to_string()));
//! ```
//!
//! Or a [`ParseOptions`](struct.ParseOptions.html), giving you more control
//! (see that struct's documentation for more details):
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! let line = r#"In\mvalid"#; // note: raw string
//! let options = ParseOptions::new().no_strict_escapes();
//! assert_eq!(shellish_parse::parse(line, options).unwrap(), &[
//! "In�valid"
//! ]);
//! let options = ParseOptions::new();
//! assert_eq!(shellish_parse::parse(line, options).unwrap_err(),
//! shellish_parse::ParseError::UnrecognizedEscape("\\m".to_string()));
//! ```
//!
//! You may want to use an alias to make calling this function more convenient
//! if you're using it in a lot of places:
//!
//! ```rust
//! use shellish_parse::parse as parse_shellish;
//! let line = "Hello World";
//! assert_eq!(parse_shellish(line, false).unwrap(), &[
//! "Hello", "World"
//! ]);
//! ```
//!
//! And putting your preferred `ParseOptions` into a `const` can save you some
//! typing:
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new()
//! .allow_comments_within_elements();
//! use shellish_parse::parse as parse_shellish;
//! let line = "This line contains a com#ment";
//! assert_eq!(parse_shellish(line, SHELLISH_OPTIONS).unwrap(), &[
//! "This", "line", "contains", "a", "com"
//! ]);
//! ```
//!
//! Regular parse is great and everything, but sometimes you want to be able
//! to chain multiple commands on the same line. That's where `multiparse`
//! comes in:
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = "Hello World; How are you?";
//! assert_eq!(shellish_parse::multiparse(line, SHELLISH_OPTIONS, &[";"])
//! .unwrap(), &[
//! (vec!["Hello".to_string(), "World".to_string()], Some(0)),
//! (vec!["How".to_string(), "are".to_string(), "you?".to_string()], None),
//! ]);
//! ```
//!
//! (Since it returns a vec of tuples, it's rather awkward to phrase in tests.)
//!
//! You pass the separators you want to use. A single semicolon is probably
//! all you want. If you want to get really fancy, you can add arbitrarily many
//! different separators. Each command returned comes with the index of the
//! separator that terminated it:
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = "test -f foo && pv foo | bar || echo no foo & echo wat";
//! assert_eq!(shellish_parse::multiparse(line, SHELLISH_OPTIONS,
//! &["&&", "||", "&", "|", ";"])
//! .unwrap(), &[
//! (vec!["test".to_string(), "-f".to_string(), "foo".to_string()], Some(0)),
//! (vec!["pv".to_string(), "foo".to_string()], Some(3)),
//! (vec!["bar".to_string()], Some(1)),
//! (vec!["echo".to_string(), "no".to_string(), "foo".to_string()], Some(2)),
//! (vec!["echo".to_string(), "wat".to_string()], None),
//! ]);
//! ```
//!
//! Since the separators are checked in the order passed, put longer
//! separators before shorter ones. If `"&"` preceded `"&&"` in the above call,
//! `"&"` would always be recognized first, and `"&&"` would never be
//! recognized.
//!
//! Extremely shellish things, like redirection or using parentheses to group
//! commands, are out of scope of this crate. If you want those things, you
//! might be writing an actual shell, and not just something shellish.
//!
//! # Syntax
//!
//! The syntax is heavily inspired by the UNIX Bourne shell. Quotation works
//! exactly like in said shell. Backslashes can also be used for escaping (and
//! more advanced usage, more like Rust strings than shellish). Unlike the real
//! Bourne shell, `parse_shellish` contains no form of variable substitution.
//!
//! ## Whitespace
//!
//! Elements are separated by one or more whitespace characters.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = "Hello there!";
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "Hello", "there!",
//! ])
//! ```
//!
//! Whitespace consists of spaces, tabs, or newlines. Whitespace before and
//! after the command line is ignored. Any combination and quantity of
//! whitespace between elements acts the same as a single space.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = "\tHello\n\t there! \n\n";
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "Hello", "there!",
//! ])
//! ```
//!
//! ## Backslash escapes
//!
//! (All example input strings in this section are given as raw strings. The
//! backslashes and quotation marks you see in them are literal.)
//!
//! You may escape any character with backslash.
//!
//! Backslash followed by an ASCII letter (26 letters `'A'` through `'Z'` and
//! `'a'` through `'z'`) or digit (`'0'` through `'9'`) has a special meaning.
//!
//! - `'n'`: Newline (U+000A LINE FEED)
//! - `'t'`: Tab (U+0009 CHARACTER TABULATION)
//! - Any other letter (and any digit) will either insert a � (U+FFFD
//! REPLACEMENT CHARACTER) or cause a parse error, depending on the value you
//! pass as the second parameter to `parse`.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = r#"General\t Kenobi\n"#;
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "General\t", "Kenobi\n",
//! ])
//! ```
//!
//! Backslash followed by a newline followed by any number of unescaped tabs or
//! spaces will give nothing, just like in Rust strings. (i.e. you may continue
//! a command line onto another line by preceding the linebreak with a
//! backslash)
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = r#"You will die br\
//! aver than most."#;
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "You", "will", "die", "braver", "than", "most."
//! ])
//! ```
//!
//! Backslash followed by anything else will give that character, ignoring any
//! special meaning it might otherwise have had.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = r#"Four\-score\ and\ seven \"years\" ago"#;
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "Four-score and seven", "\"years\"", "ago"
//! ])
//! ```
//!
//! Future versions may add more special characters. These will only be denoted
//! by letter(s) or digit(s). For all other characters, the handling of
//! backslash is guaranteed not to change.
//!
//! ## Quoting
//!
//! (All example input strings in this section are given as raw strings. The
//! backslashes and quotation marks you see in them are literal.)
//!
//! You may quote parts of the command line. The quoted text will all go into
//! the same element.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = r#"cp "Quotation Mark Test" "Quotation Mark Test Backup""#;
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "cp", "Quotation Mark Test", "Quotation Mark Test Backup"
//! ])
//! ```
//!
//! Quoting will *not* create a new element on its own.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = r#"I Probably Should Have"Added A Space!""#;
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "I", "Probably", "Should", "HaveAdded A Space!"
//! ])
//! ```
//!
//! There are two kinds of quotation. A double-quoted string will interpret
//! backslash escapes, including `\"`.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = r#"movie recommend "\"Swing it\" magistern""#;
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "movie", "recommend", "\"Swing it\" magistern"
//! ])
//! ```
//!
//! A single-quoted string **will not** interpret backslash escapes, not even
//! `\'`!
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = r#"addendum 'and then he said "But I haven'\''t seen it, I \
//! just searched for '\''movies with quotes in their titles'\'' on IMDB and \
//! saw that it was popular"'"#;
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "addendum", "and then he said \"But I haven't seen it, I just \
//! searched for 'movies with quotes in their titles' on IMDB and saw that it \
//! was popular\""
//! ])
//! ```
//!
//! ## Continuation
//!
//! `parse` returns `Err(ParseResult::...)` on failure. There are three ways
//! parsing can fail:
//!
//! 1. Dangling backslash: `like this\`
//! 2. Unterminated string: `like "this`
//! 3. Unrecognized escape sequence: `like this\m`
//!
//! In the first two cases, parsing could succeed if there were only more input
//! to read. So you can handle these errors by prompting for more input, adding
//! it onto the end of the string, and trying again. The `needs_continuation`
//! method of `ParseResult` is here to help:
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! // note: raw strings
//! let input_lines = [r#"This is not a very \"#,
//! r#"long line, so why did \"#,
//! r#"we choose to 'force "#,
//! r#"continuation'?"#];
//! let mut input_iter = input_lines.into_iter();
//! let mut buf = input_iter.next().unwrap().to_string();
//! let result = loop {
//! match shellish_parse::parse(&buf, SHELLISH_OPTIONS) {
//! Err(x) if x.needs_continuation() => {
//! buf.push('\n'); // don't forget this part!
//! buf.push_str(input_iter.next().unwrap())
//! },
//! x => break x,
//! }
//! };
//! assert_eq!(result.unwrap(), &[
//! "This", "is", "not", "a", "very", "long", "line,", "so", "why", "did",
//! "we", "choose", "to", "force \ncontinuation?"
//! ]);
//! ```
//!
//! ## Comments
//!
//! By default, comments are delimited by a `#` character.
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! # const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! let line = "Comment test. #comments #sayinghashtagoutloud";
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "Comment", "test."
//! ])
//! ```
//!
//! You can change this to any other character using
//! [`ParseOptions`](struct.ParseOptions.html):
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new()
//! .comment_char(Some('%'));
//! let line = "bind lmbutton Interact % make left mouse button interact";
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "bind", "lmbutton", "Interact"
//! ])
//! ```
//!
//! You can also disable comment parsing entirely:
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new()
//! .comment_char(None);
//! let line = "Comment test. #comments #sayinghashtagoutloud";
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "Comment", "test.", "#comments", "#sayinghashtagoutloud"
//! ])
//! ```
//!
//! By default, comments are not allowed in the middle of an element. This
//! behavior matches the Bourne shell. You can make it so that any comment
//! character, found outside a string, will be accepted as the beginning of a
//! comment:
//!
//! ```rust
//! # use shellish_parse::ParseOptions;
//! let line = "Comment that breaks an el#ement.";
//! const SHELLISH_OPTIONS: ParseOptions = ParseOptions::new();
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS).unwrap(), &[
//! "Comment", "that", "breaks", "an", "el#ement."
//! ]);
//! const SHELLISH_OPTIONS_2: ParseOptions = ParseOptions::new()
//! .allow_comments_within_elements();
//! assert_eq!(shellish_parse::parse(line, SHELLISH_OPTIONS_2).unwrap(), &[
//! "Comment", "that", "breaks", "an", "el"
//! ]);
//! ```
//!
//! # Legalese
//!
//! `shellish_parse` is copyright 2022-2023, Solra Bizna, and licensed under
//! either of:
//!
//! - Apache License, Version 2.0
//! ([LICENSE-APACHE](LICENSE-APACHE) or
//! <http://www.apache.org/licenses/LICENSE-2.0>)
//! - MIT license
//! ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
//!
//! at your option.
//!
//! Unless you explicitly state otherwise, any contribution intentionally
//! submitted for inclusion in the `shellish_parse` crate by you, as defined
//! in the Apache-2.0 license, shall be dual licensed as above, without any
//! additional terms or conditions.
use ;
/// Options for configuring command-line parsing.
///
/// For backwards compatibility with 2.1, you can convert a `bool` into this
/// type. `true` will be the default, and `false` will be `no_strict_escapes`.
/// A result of a failed command line parse.
///
/// Most of these errors can be resolved with additional user input. The
/// `needs_continuation` method is there to help. See
/// [the module-level documentation](index.html) for more information.
/// Parse a shellish string into elements. This function will parse a single
/// command. See [the module-level documentation](index.html) for more
/// information.
///
/// - `input`: The string to parse.
/// - `options`: A [`ParseOptions`](struct.ParseOptions.html) instance,
/// describing the options in effect for this parse. For compatibility,
/// may also be `true` as shorthand for `ParseOptions::new()`, and `false`
/// as shorthand for `ParseOptions::new().no_strict_escapes()`.
///
/// When parsing is successful, returns a vector containing each individual
/// element of the parsed command line.
/// Parse a shellish string into elements. This function can parse multiple
/// commands on a single line, separated by any of the given list of
/// separators. See [the module-level documentation](index.html) for more
/// information.
///
/// - `input`: The string to parse.
/// - `options`: A [`ParseOptions`](struct.ParseOptions.html) instance,
/// describing the options in effect for this parse. For compatibility,
/// may also be `true` as shorthand for `ParseOptions::new()`, and `false`
/// as shorthand for `ParseOptions::new().no_strict_escapes()`.
///
/// When parsing is successful, returns a vector containing tuples of
/// individual commands, along with the index of the separator that ended that
/// command. The last command may not have a separator, in which case it was
/// ended by the end of the string, rather than a separator.