xpanda 0.2.0

Unix shell-like parameter expansion/variable substitution
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
//! This crate provides the ability to expand/substitute variables in strings
//! similar to [`envsubst`] and [`Bash parameter expansion`].
//!
//! There is a single public struct (not counting errors and builders),
//! [`Xpanda`], which in turn contains a single method: `expand`. The expand
//! method takes a string by reference and returns a copy of it with all
//! variables expanded/substituted according to some patterns.
//!
//! [`envsubst`]: https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html
//! [`Bash parameter expansion`]: https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html
//! [`Xpanda`]: struct.Xpanda.html

#![deny(clippy::all)]
#![warn(clippy::pedantic, clippy::nursery)]
#![allow(unused)]

mod ast;
mod eval;
mod forward_peekable;
mod glob;
mod lexer;
mod parser;
mod position;
mod str_read;
mod token;

use crate::eval::Evaluator;
use crate::lexer::Lexer;
use crate::parser::Parser;
use crate::position::Position;
use std::collections::HashMap;
use std::env;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Error {
    pub message: String,
    pub line: usize,
    pub col: usize,
}

impl Error {
    #[must_use]
    pub const fn new(message: String, position: &Position) -> Self {
        Self {
            message,
            line: position.line,
            col: position.col,
        }
    }
}

impl From<parser::Error> for Error {
    fn from(error: parser::Error) -> Self {
        Self::new(error.message, &error.position)
    }
}

impl From<eval::Error> for Error {
    fn from(error: eval::Error) -> Self {
        Self::new(error.message, &Position::default())
    }
}

#[derive(Default)]
pub struct Builder {
    no_unset: bool,
    positional_vars: Vec<String>,
    named_vars: HashMap<String, String>,
}

impl Builder {
    /// With this flag set, missing variables without any default value will
    /// cause an error instead of omitting en empty string. Off by default.
    #[must_use]
    pub const fn no_unset(mut self, no_unset: bool) -> Self {
        self.no_unset = no_unset;
        self
    }

    /// Adds all environment variables as named variables.
    #[must_use]
    pub fn with_env_vars(mut self) -> Self {
        self.named_vars.extend(env::vars());
        self
    }

    /// Adds the given map values as named variables.
    #[must_use]
    pub fn with_named_vars(mut self, vars: HashMap<String, String>) -> Self {
        self.named_vars.extend(vars);
        self
    }

    /// Adds the given strings as positional variables.
    #[must_use]
    pub fn with_positional_vars(mut self, vars: Vec<String>) -> Self {
        self.positional_vars.extend(vars);
        self
    }

    /// Builds a new [`Xpanda`] instance.
    #[must_use]
    pub fn build(self) -> Xpanda {
        Xpanda::new(self)
    }
}

/// [`Xpanda`] substitutes the values of variables in strings similar to
/// [`envsubst`] and [`Bash parameter expansion`].
///
/// [`envsubst`]: https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html
/// [`Bash parameter expansion`]: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
#[derive(Default)]
pub struct Xpanda {
    evaluator: Evaluator,
}

impl Xpanda {
    fn new(builder: Builder) -> Self {
        Self {
            evaluator: Evaluator::new(
                builder.no_unset,
                builder.positional_vars,
                builder.named_vars,
            ),
        }
    }

    #[must_use]
    pub fn builder() -> Builder {
        Builder::default()
    }

    /// Expands the given text by substituting the values of the variables
    /// inside it.
    ///
    /// Variables can appear in any of the following forms:
    ///
    /// <table>
    ///   <thead>
    ///     <tr>
    ///       <th>Pattern</th>
    ///       <th>Description</th>
    ///     </tr>
    ///   </thead>
    ///   <tbody>
    ///     <tr>
    ///       <td>$VAR</td>
    ///       <td>substituted with the corresponding value for 'VAR' if set,
    /// otherwise "".</td>     </tr>
    ///     <tr>
    ///       <td>${VAR}</td>
    ///       <td>substituted with the corresponding value for 'VAR' if set,
    /// otherwise "".</td>     </tr>
    ///     <tr>
    ///       <td>${VAR-default}</td>
    ///       <td>
    ///         substituted with the corresponding value for 'VAR' if set,
    /// otherwise "default".       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:-default}</td>
    ///       <td>
    ///         substituted with the corresponding value for 'VAR' if set and
    /// non-empty, otherwise "default".
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR+alternative}</td>
    ///       <td>
    ///         substituted with "alternative" if the corresponding value for
    /// 'VAR' is set, otherwise "".
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:+alternative}</td>
    ///       <td>
    ///         substituted with "alternative" if the corresponding value for
    /// 'VAR' is set and non-empty, otherwise "".
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR?}</td>
    ///       <td>
    ///         substituted with the corresponding value for 'VAR' if set,
    /// otherwise yields an error.
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR?error}</td>
    ///       <td>
    ///         substituted with the corresponding value for 'VAR' if set,
    /// otherwise yields an error with the given message (in this
    /// case "error").       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:?error}</td>
    ///       <td>
    ///         substituted with the corresponding value for 'VAR' if set and
    /// non-empty, otherwise yields an error with the given message
    /// (in this case "error").       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${#VAR}</td>
    ///       <td>
    ///         substituted with the length of the corresponding value for 'VAR'
    /// if set, otherwise "0".
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${#}</td>
    ///       <td>substituted with the number of positional variables.</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${!VAR}</td>
    ///       <td>
    ///         the value of 'VAR' is evaluated again as a variable name — the
    /// result is the value of the variable it names (indirect reference).
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:offset}</td>
    ///       <td>
    ///         substituted with the value of 'VAR' starting at index `offset`
    /// through the end. Negative `offset` counts from the end;
    /// parenthesize or precede with a space to disambiguate from
    /// `${VAR:-default}`.       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:offset:length}</td>
    ///       <td>
    ///         substituted with `length` characters of 'VAR' starting at index
    /// `offset`.       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR^}</td>
    ///       <td>
    ///         substituted with the value of the variable named by the value of
    /// `VAR`, with the first character uppercased.
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR^^}</td>
    ///       <td>
    ///         substituted with the value of the variable named by the value of
    /// `VAR`, with all characters uppercased.
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR,}</td>
    ///       <td>
    ///         substituted with the value of the variable named by the value of
    /// `VAR`, with the first character lowercased.
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR,,}</td>
    ///       <td>
    ///         substituted with the value of the variable named by the value of
    /// `VAR`, with all characters lowercased.
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR~}</td>
    ///       <td>
    ///         substituted with the value of the variable named by the value of
    /// `VAR`, with the casing of the first character reversed.
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR~~}</td>
    ///       <td>
    ///         substituted with the value of the variable named by the value of
    /// `VAR`, with the casing of all characters reversed.
    ///       </td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR#pattern}</td>
    ///       <td>$VAR with the shortest prefix matching `pattern` removed.</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR##pattern}</td>
    ///       <td>$VAR with the longest prefix matching `pattern` removed.</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR%pattern}</td>
    ///       <td>$VAR with the shortest suffix matching `pattern` removed.</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR%%pattern}</td>
    ///       <td>$VAR with the longest suffix matching `pattern` removed.</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR/pattern/replacement}</td>
    ///       <td>$VAR with the first match of `pattern` replaced by
    /// `replacement`.</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR//pattern/replacement}</td>
    ///       <td>$VAR with every match of `pattern` replaced by
    /// `replacement`.</td>
    ///     </tr>
    ///   </tbody>
    /// </table>
    ///
    /// `VAR` above is a named variable. Named variables can be provided using
    /// the builder:
    ///
    /// ```rust
    /// use std::collections::HashMap;
    /// use xpanda::Xpanda;
    ///
    /// let named_vars = HashMap::new();
    /// let xpanda = Xpanda::builder().with_named_vars(named_vars).build();
    /// ```
    ///
    /// Positional variables are also supported and can be provided in the same
    /// way:
    ///
    /// ```rust
    /// use xpanda::Xpanda;
    ///
    /// let xpanda = Xpanda::builder().with_positional_vars(Vec::new()).build();
    /// ```
    ///
    /// Positional variables can be referenced using their index (starting at 1)
    /// - for example, `$1` references the first positional variable, `$2` the
    ///   second, and so on. `$0` is a space-concatenated string of all
    ///   positional variables.
    ///
    /// Here are some examples and their output:
    ///
    /// <table>
    ///   <thead>
    ///     <tr>
    ///       <th>Pattern</th>
    ///       <th>VAR unset</th>
    ///       <th>VAR=""</th>
    ///       <th>VAR="example"</th>
    ///     </tr>
    ///   </thead>
    ///   <tbody>
    ///     <tr>
    ///       <td>$VAR</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR-default}</td>
    ///       <td>"default"</td>
    ///       <td></td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:-default}</td>
    ///       <td>"default"</td>
    ///       <td>"default"</td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR+alternative}</td>
    ///       <td></td>
    ///       <td>"alternative"</td>
    ///       <td>"alternative"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:+alternative}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"alternative"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR?message}</td>
    ///       <td>error: "message"</td>
    ///       <td></td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:?message}</td>
    ///       <td>error: "message"</td>
    ///       <td>error: "message"</td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${#VAR}</td>
    ///       <td>"0"</td>
    ///       <td>"0"</td>
    ///       <td>"7"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${!VAR}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>$example</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:2}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"ample"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:2:4}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"ampl"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR^}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"Example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR^^}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"EXAMPLE"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR,}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR,,}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR~}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"Example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR~~}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"EXAMPLE"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR#*e}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"xample"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR##*e}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td></td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR%e*}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"exampl"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR%%e*}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td></td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR/e/E}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"Example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR//e/E}</td>
    ///       <td></td>
    ///       <td></td>
    ///       <td>"ExamplE"</td>
    ///     </tr>
    ///   </tbody>
    /// </table>
    ///
    /// Special rules take precedence when [`Builder::no_unset`] is `true`:
    ///
    /// <table>
    ///   <thead>
    ///     <tr>
    ///       <th>Pattern</th>
    ///       <th>VAR unset</th>
    ///     </tr>
    ///   </thead>
    ///   <tbody>
    ///     <tr>
    ///       <td>$VAR</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${#VAR}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${!VAR}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR^}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR^^}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR,}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR,,}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR~}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR~~}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:2}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR:2:4}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR#pat}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR##pat}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR%pat}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR%%pat}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR/a/b}</td>
    ///       <td>error</td>
    ///     </tr>
    ///     <tr>
    ///       <td>${VAR//a/b}</td>
    ///       <td>error</td>
    ///     </tr>
    ///   </tbody>
    /// </table>
    ///
    /// Default/Alternative values can also be variables:
    ///
    /// <table>
    ///   <thead>
    ///     <tr>
    ///       <th>Pattern</th>
    ///       <th>VAR unset</th>
    ///       <th>VAR=""</th>
    ///       <th>VAR="example"</th>
    ///     </tr>
    ///   </thead>
    ///   <tbody>
    ///     <tr>
    ///       <td>`${VAR:-$DEF}`</td>
    ///       <td>`$DEF`</td>
    ///       <td></td>
    ///       <td>"example"</td>
    ///     </tr>
    ///     <tr>
    ///       <td>`${VAR+${ALT:-alternative}}`</td>
    ///       <td></td>
    ///       <td>`${ALT:-alternative}`</td>
    ///       <td>${ALT:-alternative}</td>
    ///     </tr>
    ///   </tbody>
    /// </table>
    ///
    /// The `$` character is assumed to be the start of a variable. If the
    /// variable does not match any of the forms listed above, an error is
    /// returned. Variables can be escaped by prefixing them
    /// by an additional '$', for example, `$$VAR` which yields `$VAR` and
    /// `${VAR-$$text}` which yields `$text` if `VAR` is unset.
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if the given string is badly formatted and cannot be
    /// parsed.
    ///
    /// # Examples
    ///
    /// ```
    /// use xpanda::Xpanda;
    ///
    /// let xpanda = Xpanda::default();
    /// assert_eq!(xpanda.expand("${1:-default}"), Ok(String::from("default")));
    /// ```
    pub fn expand(&self, input: &str) -> Result<String, Error> {
        let lexer = Lexer::new(input);
        let mut parser = Parser::new(lexer);
        let ast = parser.parse()?;
        let result = self.evaluator.eval(&ast)?;

        Ok(result)
    }
}