argx 0.2.2

Expressive command-line parsing and configuration for Rust.
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
//! Dotenv parsing and substitution.

use std::{
    collections::HashMap,
    fs::File,
    io::{self, BufRead, BufReader, Read},
    iter::Peekable,
    path::{Path, PathBuf},
};

use crate::config::{environment::Environment, error::Location};

/// Errors produced while reading or parsing dotenv configuration.
#[derive(Debug, thiserror::Error)]
pub(crate) enum DotenvError {
    /// The environment file could not be opened or read.
    #[error("failed to read dotenv file `{}`: {source}", path.display())]
    Read {
        /// Dotenv file path.
        path: PathBuf,
        /// Underlying filesystem error.
        source: io::Error,
    },
    /// A logical dotenv line was malformed.
    #[error(
            "failed to parse dotenv file `{}` at line {}, column {}",
            path.display(),
            .location.line,
            .location.column,
        )]
    ParseSyntax {
        /// Dotenv file path.
        path: PathBuf,
        /// Source location of the dotenv failure.
        location: Location,
    },
    /// A dotenv substitution referenced an unavailable variable.
    #[error(
            "dotenv file `{}` references unset environment variable `{variable}` at line {}, column {}",
            path.display(),
            .location.line,
            .location.column,
        )]
    ParseMissingVariable {
        /// Dotenv file path.
        path: PathBuf,
        /// Source location of the dotenv failure.
        location: Location,
        /// Missing process and dotenv variable.
        variable: String,
    },
    /// A dotenv substitution referenced a non-UTF-8 process variable.
    #[error(
            "dotenv file `{}` references non-UTF-8 environment variable `{variable}` at line {}, column {}",
            path.display(),
            .location.line,
            .location.column,
        )]
    ParseNonUtf8Variable {
        /// Dotenv file path.
        path: PathBuf,
        /// Source location of the dotenv failure.
        location: Location,
        /// Non-UTF-8 process variable.
        variable: String,
    },
}

/// Stable dotenv parse failure categories.
#[derive(Debug)]
enum ParseKind {
    /// Dotenv syntax was malformed.
    Syntax,
    /// A substitution referenced a variable that is not defined.
    MissingVariable(String),
    /// A substitution referenced a process variable that is not valid UTF-8.
    NonUtf8Variable(String),
}

impl DotenvError {
    /// Returns the path associated with this dotenv error, when available.
    pub(crate) fn path(&self) -> Option<&Path> {
        match self {
            Self::Read { path, .. }
            | Self::ParseSyntax { path, .. }
            | Self::ParseMissingVariable { path, .. }
            | Self::ParseNonUtf8Variable { path, .. } => Some(path),
        }
    }

    /// Returns the source location for a dotenv syntax error.
    pub(crate) const fn location(&self) -> Option<Location> {
        match self {
            Self::ParseSyntax { location, .. }
            | Self::ParseMissingVariable { location, .. }
            | Self::ParseNonUtf8Variable { location, .. } => Some(*location),
            Self::Read { .. } => None,
        }
    }

    /// Returns the environment variable associated with a substitution failure.
    pub(crate) fn variable(&self) -> Option<&str> {
        match self {
            Self::ParseMissingVariable { variable, .. }
            | Self::ParseNonUtf8Variable { variable, .. } => Some(variable),
            Self::Read { .. } | Self::ParseSyntax { .. } => None,
        }
    }
}

/// Loads and parses one explicit dotenv-format file.
///
/// # Errors
/// Returns an error when the file cannot be read or its contents are invalid.
pub(crate) fn load_dotenv(path: &Path, process: &Environment) -> Result<Environment, DotenvError> {
    let file = File::open(path)
        .map_err(|source| DotenvError::Read { path: path.to_path_buf(), source })?;
    let values = parse(file, process).map_err(|source| match source {
        ParseError::Io(source) => DotenvError::Read { path: path.to_path_buf(), source },
        ParseError::Line { location, kind: ParseKind::Syntax } => {
            DotenvError::ParseSyntax { path: path.to_path_buf(), location }
        }
        ParseError::Line { location, kind: ParseKind::MissingVariable(variable) } => {
            DotenvError::ParseMissingVariable { path: path.to_path_buf(), location, variable }
        }
        ParseError::Line { location, kind: ParseKind::NonUtf8Variable(variable) } => {
            DotenvError::ParseNonUtf8Variable { path: path.to_path_buf(), location, variable }
        }
    })?;
    Ok(Environment::from_utf8(values))
}

/// Parses dotenv assignments without modifying the process environment.
fn parse<R: Read>(reader: R, process: &Environment) -> Result<HashMap<String, String>, ParseError> {
    let mut lines = QuotedLines { buf: BufReader::new(reader), line: 0 };

    // Strip an optional UTF-8 BOM.
    let buffer = lines.buf.fill_buf().map_err(ParseError::Io)?;
    if buffer.starts_with(&[0xEF, 0xBB, 0xBF]) {
        lines.buf.consume(3);
    }

    let mut substitution_data = HashMap::new();
    let mut values = HashMap::new();
    for line in lines {
        let line = line?;
        let parsed = LineParser::new(&line.text, &mut substitution_data, process)
            .parse_line()
            .map_err(|error| locate_line_error(error, &line.text, line.start_line))?;
        if let Some((key, value)) = parsed {
            values.insert(key, value);
        }
    }
    Ok(values)
}

/// Internal dotenv parser error before a source path is attached.
#[derive(Debug, thiserror::Error)]
enum ParseError {
    /// Input could not be read.
    #[error(transparent)]
    Io(#[from] io::Error),
    /// Dotenv parsing failed at one absolute source location.
    #[error("invalid dotenv assignment")]
    Line {
        /// One-based source location.
        location: Location,
        /// Stable failure category.
        kind: ParseKind,
    },
}

/// Byte offset and stable failure kind within one logical dotenv line.
#[derive(Debug)]
struct LineError {
    /// Byte offset within the logical line.
    index: usize,
    /// Stable failure category.
    kind: ParseKind,
}

impl LineError {
    /// Creates a syntax failure at one byte offset.
    const fn syntax(index: usize) -> Self {
        Self { index, kind: ParseKind::Syntax }
    }

    /// Creates a missing-substitution failure.
    const fn missing(index: usize, variable: String) -> Self {
        Self { index, kind: ParseKind::MissingVariable(variable) }
    }

    /// Creates a non-UTF-8 substitution failure.
    const fn non_utf8(index: usize, variable: String) -> Self {
        Self { index, kind: ParseKind::NonUtf8Variable(variable) }
    }
}

/// Attaches an absolute source location to one logical-line parse error.
fn locate_line_error(error: LineError, input: &str, start_line: usize) -> ParseError {
    let relative = Location::from_offset(input, error.index);
    ParseError::Line {
        location: Location { line: start_line + relative.line - 1, column: relative.column },
        kind: error.kind,
    }
}

/// Iterator over logical dotenv lines with quoted multiline values joined.
struct QuotedLines<B> {
    /// Buffered source of physical input lines.
    buf: B,
    /// Number of physical lines already consumed.
    line: usize,
}

/// One logical dotenv line and its one-based starting physical line.
struct LogicalLine {
    /// Joined logical-line contents.
    text: String,
    /// One-based physical line at which the logical line begins.
    start_line: usize,
}

/// Parser state used while scanning for the end of a logical dotenv line.
#[derive(Clone, Copy, Debug)]
enum ParseState {
    /// Parser is outside quotes and escapes.
    Complete,
    /// Previous character was an escape outside quotes.
    Escape,
    /// Parser is inside a single-quoted string.
    StrongOpen,
    /// Parser is inside a double-quoted string.
    WeakOpen,
    /// Previous character was an escape inside double quotes.
    WeakOpenEscape,
    /// Parser has entered a trailing comment.
    Comment,
    /// Parser is scanning whitespace after a completed value.
    WhiteSpace,
}

/// Evaluates how one physical input fragment changes logical-line parser state.
fn eval_end_state(previous: ParseState, input: &str) -> (usize, ParseState) {
    let mut state = previous;
    let mut position = 0;

    for (offset, character) in input.char_indices() {
        position = offset;
        state = match state {
            ParseState::WhiteSpace => match character {
                '#' => return (position, ParseState::Comment),
                character
                    if character.is_whitespace() && character != '\n' && character != '\r' =>
                {
                    ParseState::WhiteSpace
                }
                '\\' => ParseState::Escape,
                '"' => ParseState::WeakOpen,
                '\'' => ParseState::StrongOpen,
                _ => ParseState::Complete,
            },
            ParseState::Escape => ParseState::Complete,
            ParseState::Complete => match character {
                character
                    if character.is_whitespace() && character != '\n' && character != '\r' =>
                {
                    ParseState::WhiteSpace
                }
                '\\' => ParseState::Escape,
                '"' => ParseState::WeakOpen,
                '\'' => ParseState::StrongOpen,
                _ => ParseState::Complete,
            },
            ParseState::WeakOpen => match character {
                '\\' => ParseState::WeakOpenEscape,
                '"' => ParseState::Complete,
                _ => ParseState::WeakOpen,
            },
            ParseState::WeakOpenEscape => ParseState::WeakOpen,
            ParseState::StrongOpen => match character {
                '\'' => ParseState::Complete,
                _ => ParseState::StrongOpen,
            },
            ParseState::Comment => panic!("comment state should have returned immediately"),
        };
    }
    (position, state)
}

impl<B: BufRead> Iterator for QuotedLines<B> {
    type Item = Result<LogicalLine, ParseError>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut buffer = String::new();
        let mut state = ParseState::Complete;
        let start_line = self.line + 1;
        loop {
            let buffer_start = buffer.len();
            match self.buf.read_line(&mut buffer) {
                Ok(0) => {
                    return match state {
                        ParseState::Complete => None,
                        _ => {
                            let relative = Location::from_offset(&buffer, buffer.len());
                            Some(Err(ParseError::Line {
                                location: Location {
                                    line: start_line + relative.line - 1,
                                    column: relative.column,
                                },
                                kind: ParseKind::Syntax,
                            }))
                        }
                    };
                }
                Ok(_) => {
                    self.line += 1;
                    if buffer[buffer_start..].trim_start().starts_with('#')
                        && buffer[..buffer_start].is_empty()
                    {
                        return Some(Ok(LogicalLine { text: String::new(), start_line }));
                    }
                    let (position, next_state) = eval_end_state(state, &buffer[buffer_start..]);
                    state = next_state;

                    match state {
                        ParseState::Complete => {
                            buffer.truncate(buffer.trim_end_matches(['\r', '\n']).len());
                            return Some(Ok(LogicalLine { text: buffer, start_line }));
                        }
                        ParseState::Comment => {
                            buffer.truncate(buffer_start + position);
                            return Some(Ok(LogicalLine { text: buffer, start_line }));
                        }
                        ParseState::Escape
                        | ParseState::StrongOpen
                        | ParseState::WeakOpen
                        | ParseState::WeakOpenEscape
                        | ParseState::WhiteSpace => {}
                    }
                }
                Err(source) => return Some(Err(ParseError::Io(source))),
            }
        }
    }
}

/// Parser for one logical dotenv assignment line.
struct LineParser<'a> {
    /// Previously parsed values available to later substitutions.
    substitution_data: &'a mut HashMap<String, Option<String>>,
    /// Process environment, which takes precedence during substitution.
    process: &'a Environment,
    /// Remaining unparsed line slice.
    line: &'a str,
    /// Byte offset into the logical line for diagnostics.
    position: usize,
}

impl<'a> LineParser<'a> {
    /// Creates a parser for one logical line.
    fn new(
        line: &'a str,
        substitution_data: &'a mut HashMap<String, Option<String>>,
        process: &'a Environment,
    ) -> Self {
        Self { substitution_data, process, line: line.trim_end(), position: 0 }
    }

    /// Builds a parse error at the current byte offset.
    const fn error(&self) -> LineError {
        LineError::syntax(self.position)
    }

    /// Parses this line into an optional key/value assignment.
    fn parse_line(&mut self) -> Result<Option<(String, String)>, LineError> {
        self.skip_whitespace();
        if self.line.is_empty() || self.line.starts_with('#') {
            return Ok(None);
        }

        let mut key = self.parse_key()?;
        self.skip_whitespace();

        // `export` may be either an optional prefix or the key itself.
        if key == "export" {
            if self.expect_equal().is_err() {
                key = self.parse_key()?;
                self.skip_whitespace();
                self.expect_equal()?;
            }
        } else {
            self.expect_equal()?;
        }
        self.skip_whitespace();

        if self.line.is_empty() || self.line.starts_with('#') {
            self.substitution_data.insert(key.clone(), None);
            return Ok(Some((key, String::new())));
        }

        let value = parse_value(self.line, self.substitution_data, self.process)
            .map_err(|error| LineError { index: self.position + error.index, kind: error.kind })?;
        self.substitution_data.insert(key.clone(), Some(value.clone()));
        Ok(Some((key, value)))
    }

    /// Parses an environment variable key.
    fn parse_key(&mut self) -> Result<String, LineError> {
        if !self
            .line
            .starts_with(|character: char| character.is_ascii_alphabetic() || character == '_')
        {
            return Err(self.error());
        }
        let index = self
            .line
            .find(|character: char| {
                !(character.is_ascii_alphanumeric() || character == '_' || character == '.')
            })
            .unwrap_or(self.line.len());
        self.position += index;
        let key = String::from(&self.line[..index]);
        self.line = &self.line[index..];
        Ok(key)
    }

    /// Consumes the assignment separator.
    fn expect_equal(&mut self) -> Result<(), LineError> {
        if !self.line.starts_with('=') {
            return Err(self.error());
        }
        self.line = &self.line[1..];
        self.position += 1;
        Ok(())
    }

    /// Advances past leading whitespace in the remaining line.
    fn skip_whitespace(&mut self) {
        if let Some(index) = self.line.find(|character: char| !character.is_whitespace()) {
            self.position += index;
            self.line = &self.line[index..];
        } else {
            self.position += self.line.len();
            self.line = "";
        }
    }
}

/// Parses and unescapes one dotenv value, applying variable substitution.
fn parse_value(
    input: &str,
    substitution_data: &HashMap<String, Option<String>>,
    process: &Environment,
) -> Result<String, LineError> {
    let mut strong_quote = false;
    let mut weak_quote = false;
    let mut escaped = false;
    let mut expecting_end = false;
    let mut output = String::new();
    let mut characters = input.char_indices().peekable();

    while let Some((index, character)) = characters.next() {
        if expecting_end {
            match character {
                ' ' | '\t' => {}
                '#' => break,
                _ => return Err(LineError::syntax(index)),
            }
            continue;
        }

        if strong_quote {
            if character == '\'' {
                strong_quote = false;
            } else {
                output.push(character);
            }
            continue;
        }

        if escaped {
            match character {
                '\\' | '\'' | '"' | '$' | ' ' => output.push(character),
                'n' => output.push('\n'),
                _ => return Err(LineError::syntax(index)),
            }
            escaped = false;
            continue;
        }

        if weak_quote {
            match character {
                '"' => weak_quote = false,
                '\\' => escaped = true,
                '$' => apply_next_substitution(
                    index,
                    &mut characters,
                    process,
                    substitution_data,
                    &mut output,
                    input.len(),
                )?,
                _ => output.push(character),
            }
            continue;
        }

        match character {
            '\'' => strong_quote = true,
            '"' => weak_quote = true,
            '\\' => escaped = true,
            '$' => apply_next_substitution(
                index,
                &mut characters,
                process,
                substitution_data,
                &mut output,
                input.len(),
            )?,
            ' ' | '\t' => expecting_end = true,
            _ => output.push(character),
        }
    }

    if strong_quote || weak_quote || escaped {
        return Err(LineError::syntax(input.len().saturating_sub(1)));
    }

    Ok(output)
}

/// Consumes one `$NAME` or `${NAME}` substitution after the leading `$`.
fn apply_next_substitution<I>(
    dollar_index: usize,
    characters: &mut Peekable<I>,
    process: &Environment,
    substitution_data: &HashMap<String, Option<String>>,
    output: &mut String,
    input_len: usize,
) -> Result<(), LineError>
where
    I: Iterator<Item = (usize, char)>,
{
    let mut name = String::new();
    let braced = matches!(characters.peek(), Some((_, '{')));

    if braced {
        let _ = characters.next();
        let mut closed = false;
        for (_, character) in characters.by_ref() {
            if character == '}' {
                closed = true;
                break;
            }
            name.push(character);
        }
        if !closed {
            return Err(LineError::syntax(input_len.saturating_sub(1)));
        }
        if name.is_empty() {
            return Err(LineError::syntax(dollar_index));
        }
    } else {
        while let Some((_, character)) = characters.peek() {
            if character.is_ascii_alphanumeric() || *character == '_' {
                name.push(*character);
                let _ = characters.next();
            } else {
                break;
            }
        }
        if name.is_empty() {
            output.push('$');
            return Ok(());
        }
    }

    apply_substitution(process, substitution_data, dollar_index, &name, output)
}

/// Appends one resolved substitution value to the parsed output.
fn apply_substitution(
    process: &Environment,
    substitution_data: &HashMap<String, Option<String>>,
    index: usize,
    name: &str,
    output: &mut String,
) -> Result<(), LineError> {
    if let Some(value) = process.raw(name) {
        let Some(value) = value.to_str() else {
            return Err(LineError::non_utf8(index, name.to_owned()));
        };
        output.push_str(value);
        return Ok(());
    }

    if let Some(value) = substitution_data.get(name) {
        if let Some(value) = value {
            output.push_str(value);
        }
        return Ok(());
    }

    Err(LineError::missing(index, name.to_owned()))
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;

    #[test]
    fn parser_supports_quotes_export_comments_bom_and_multiline_values() {
        let input = concat!(
            "\u{feff}export FIRST=plain # comment\n",
            "SECOND=\"two words\"\n",
            "THIRD='three words'\n",
            "MULTI=\"first\nsecond\"\n",
        );
        let values = parse(Cursor::new(input.as_bytes()), &Environment::default())
            .expect("dotenv should parse");

        assert_eq!(values.get("FIRST").map(String::as_str), Some("plain"));
        assert_eq!(values.get("SECOND").map(String::as_str), Some("two words"));
        assert_eq!(values.get("THIRD").map(String::as_str), Some("three words"));
        assert_eq!(values.get("MULTI").map(String::as_str), Some("first\nsecond"));
    }

    #[test]
    fn parser_reports_physical_line_and_column() {
        let input = "GOOD=1\nBROKEN=value extra\n";
        let error = parse(Cursor::new(input.as_bytes()), &Environment::default())
            .expect_err("malformed dotenv syntax should fail");

        assert!(matches!(
            error,
            ParseError::Line {
                location: Location { line: 2, column: 14 },
                kind: ParseKind::Syntax
            }
        ));
    }

    #[test]
    fn substitution_prefers_process_then_latest_preceding_dotenv_assignment() {
        let input = concat!(
            "BASE=first\n",
            "BASE=second\n",
            "FROM_DOTENV=$BASE\n",
            "FROM_PROCESS=${SHADOW}\n",
        );
        let values = parse(
            Cursor::new(input.as_bytes()),
            &Environment::from_pairs(&[("SHADOW", "process")]),
        )
        .expect("dotenv substitutions should parse");

        assert_eq!(values.get("FROM_DOTENV").map(String::as_str), Some("second"));
        assert_eq!(values.get("FROM_PROCESS").map(String::as_str), Some("process"));
    }

    #[test]
    fn undefined_substitutions_are_errors_instead_of_empty_strings() {
        let error = parse(Cursor::new(b"VALUE=$MISSING\n"), &Environment::default())
            .expect_err("undefined dotenv substitutions must fail");

        assert!(matches!(
            error,
            ParseError::Line {
                location: Location { line: 1, column: 7 },
                kind: ParseKind::MissingVariable(variable),
            } if variable == "MISSING"
        ));
    }

    #[test]
    fn explicitly_empty_dotenv_assignments_remain_valid_substitution_values() {
        let values =
            parse(Cursor::new(b"EMPTY=\nVALUE=before${EMPTY}after\n"), &Environment::default())
                .expect("defined empty values should substitute as empty strings");

        assert_eq!(values.get("VALUE").map(String::as_str), Some("beforeafter"));
    }

    #[test]
    fn unterminated_quotes_are_rejected() {
        assert!(parse(Cursor::new(b"VALUE=\"unterminated\n"), &Environment::default()).is_err());
    }
}