bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
// SC2125: Brace expansions and globs are literal in assignments. Assign as array or use * as arguments.
//
// In variable assignments, glob patterns like *.txt are treated as literal strings,
// not expanded. This is often not what the user intended.
//
// Examples:
// Bad:
//   files=*.txt           # Literal string "*.txt", not file list
//   docs={a,b,c}.md       # Literal string "{a,b,c}.md", not expansion
//   paths=/tmp/*.log      # Literal string, not expanded
//
// Good:
//   files=(*.txt)         # Array with expanded files
//   shopt -s nullglob; files=(*.txt)  # Handle no matches gracefully
//   for file in *.txt; do ...; done   # Use glob in loop, not assignment

use crate::linter::{Diagnostic, LintResult, Severity, Span};
use regex::Regex;

static GLOB_IN_ASSIGNMENT: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
    // Match: var=*.ext or var=/path/*.ext or var={a,b,c}
    Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*=([^=]*\*[^=\s]*|.*\{[^}]+\}[^=\s]*)").unwrap()
});

/// Check if a line is a comment
fn is_comment_line(line: &str) -> bool {
    line.trim_start().starts_with('#')
}

/// Check if line is an array assignment
fn is_array_assignment(line: &str) -> bool {
    line.contains("=(")
}

/// Check if line is a quoted assignment
fn is_quoted_assignment(line: &str) -> bool {
    line.contains("=\"") || line.contains("='")
}

/// Check if value contains command substitution
fn contains_command_substitution(value: &str) -> bool {
    value.contains("$(") || value.contains('`')
}

/// Check if the brace group starting at chars[start+1..] contains brace expansion patterns
/// (comma or '..' at depth 1). Returns true if it's a brace expansion.
fn is_brace_expansion_group(chars: &[char], start: usize) -> bool {
    let mut depth = 1;
    let mut j = start + 1;
    while j < chars.len() && depth > 0 {
        match chars[j] {
            '{' => depth += 1,
            '}' => depth -= 1,
            ',' if depth == 1 => return true,
            '.' if depth == 1 && j + 1 < chars.len() && chars[j + 1] == '.' => return true,
            _ => {}
        }
        j += 1;
    }
    false
}

/// Issue #93: Check if braces in value are only parameter expansion (not brace expansion)
/// Parameter expansion: ${VAR}, ${VAR:-default}, ${VAR:+alt}, ${#VAR}, ${VAR%pattern}, etc.
/// Brace expansion: {a,b,c}, {1..10} (NOT preceded by $)
/// Returns true only if the value contains braces AND all braces are parameter expansion
fn has_brace_expansion(value: &str) -> bool {
    if !value.contains('{') {
        return false;
    }

    let chars: Vec<char> = value.chars().collect();
    for i in 0..chars.len() {
        if chars[i] == '{' && (i == 0 || chars[i - 1] != '$') && is_brace_expansion_group(&chars, i)
        {
            return true;
        }
    }
    false
}

/// Create diagnostic for glob in assignment
fn create_glob_assignment_diagnostic(
    line_num: usize,
    start_col: usize,
    end_col: usize,
) -> Diagnostic {
    Diagnostic::new(
        "SC2125",
        Severity::Warning,
        "Brace expansions and globs are literal in assignments. Assign as array, e.g., arr=(*.txt)",
        Span::new(line_num, start_col, line_num, end_col),
    )
}

pub fn check(source: &str) -> LintResult {
    let mut result = LintResult::new();

    for (line_num, line) in source.lines().enumerate() {
        let line_num = line_num + 1;

        let trimmed = line.trim_start();
        if is_comment_line(trimmed) || is_array_assignment(trimmed) || is_quoted_assignment(trimmed)
        {
            continue;
        }

        for cap in GLOB_IN_ASSIGNMENT.captures_iter(trimmed) {
            if let Some(value) = cap.get(1) {
                let val_text = value.as_str();

                if contains_command_substitution(val_text) {
                    continue;
                }

                // Issue #93: Check what was matched
                // The regex matches: glob (*) OR brace expansion ({...})
                let has_glob = val_text.contains('*');
                let has_brace = has_brace_expansion(val_text);

                // Skip if no glob and no brace expansion (only parameter expansion like ${VAR:-default})
                if !has_glob && !has_brace {
                    continue;
                }

                let start_col = cap.get(0).unwrap().start() + 1;
                let end_col = cap.get(0).unwrap().end() + 1;

                let diagnostic = create_glob_assignment_diagnostic(line_num, start_col, end_col);
                result.add(diagnostic);
            }
        }
    }

    result
}

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

    // ===== Manual Property Tests =====

    #[test]
    fn prop_sc2125_comments_never_diagnosed() {
        // Property: Comment lines should never produce diagnostics
        let test_cases = vec![
            "# files=*.txt",
            "  # docs={a,b,c}.md",
            "\t# logs=/tmp/*.log",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sc2125_array_assignments_never_diagnosed() {
        // Property: Array assignments should never be diagnosed
        let test_cases = vec!["files=(*.txt)", "docs=({a,b,c}.md)", "logs=(/tmp/*.log)"];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sc2125_quoted_assignments_never_diagnosed() {
        // Property: Quoted assignments should never be diagnosed
        let test_cases = vec![
            "pattern=\"*.txt\"",
            "glob='*.log'",
            "brace=\"{a,b,c}\"",
            "path='/tmp/*.log'",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sc2125_command_substitution_never_diagnosed() {
        // Property: Command substitution should never be diagnosed
        let test_cases = vec![
            "files=$(ls *.txt)",
            "docs=`find . -name *.md`",
            "logs=$(echo /tmp/*.log)",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sc2125_literal_values_never_diagnosed() {
        // Property: Literal values without globs should never be diagnosed
        let test_cases = vec!["name=value", "path=/usr/bin", "file=test.txt"];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sc2125_unquoted_globs_always_diagnosed() {
        // Property: Unquoted globs in assignments should always be diagnosed
        let test_cases = vec![
            "files=*.txt",
            "logs=/tmp/*.log",
            "all=/var/log/*.log",
            "docs=*.md",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 1, "Should diagnose: {}", code);
            assert!(result.diagnostics[0].message.contains("array"));
        }
    }

    #[test]
    fn prop_sc2125_brace_expansions_always_diagnosed() {
        // Property: Brace expansions in assignments should always be diagnosed
        let test_cases = vec![
            "docs={a,b,c}.md",
            "configs=/etc/{a,b,c}/config",
            "files={1,2,3}.txt",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 1, "Should diagnose: {}", code);
        }
    }

    #[test]
    fn prop_sc2125_diagnostic_code_always_sc2125() {
        // Property: All diagnostics must have code "SC2125"
        let code = "files=*.txt\nlogs=*.log";
        let result = check(code);

        for diagnostic in &result.diagnostics {
            assert_eq!(&diagnostic.code, "SC2125");
        }
    }

    #[test]
    fn prop_sc2125_diagnostic_severity_always_warning() {
        // Property: All diagnostics must be Warning severity
        let code = "files=*.txt";
        let result = check(code);

        for diagnostic in &result.diagnostics {
            assert_eq!(diagnostic.severity, Severity::Warning);
        }
    }

    #[test]
    fn prop_sc2125_empty_source_no_diagnostics() {
        // Property: Empty source should produce no diagnostics
        let result = check("");
        assert_eq!(result.diagnostics.len(), 0);
    }

    // ===== Original Unit Tests =====

    #[test]
    fn test_sc2125_glob_assignment() {
        let code = r#"files=*.txt"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "SC2125");
        assert_eq!(result.diagnostics[0].severity, Severity::Warning);
        assert!(result.diagnostics[0].message.contains("array"));
    }

    #[test]
    fn test_sc2125_brace_expansion() {
        let code = r#"docs={a,b,c}.md"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_sc2125_path_glob() {
        let code = r#"logs=/tmp/*.log"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_sc2125_array_assignment_ok() {
        let code = r#"files=(*.txt)"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_sc2125_quoted_assignment_ok() {
        let code = r#"pattern="*.txt""#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_sc2125_single_quoted_ok() {
        let code = r#"glob='*.log'"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_sc2125_command_substitution_ok() {
        let code = r#"files=$(ls *.txt)"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_sc2125_literal_value_ok() {
        let code = r#"name=value"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_sc2125_multiple_wildcards() {
        let code = r#"all=/var/log/*.log"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_sc2125_brace_in_path() {
        let code = r#"configs=/etc/{a,b,c}/config"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 1);
    }

    // Issue #93: Parameter expansion ${VAR:-default} should NOT be flagged
    #[test]
    fn test_issue_93_param_expansion_default_ok() {
        // From issue #93: ${VAR:-default} is parameter expansion, not brace expansion
        let code = r#"TEST_LINE=${TEST_LINE:-99999}"#;
        let result = check(code);
        assert_eq!(
            result.diagnostics.len(),
            0,
            "SC2125 must NOT flag parameter expansion ${{VAR:-default}}"
        );
    }

    #[test]
    fn test_issue_93_param_expansion_multiple_ok() {
        let code = r#"PROBAR_COUNT=${PROBAR_COUNT:-0}"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_issue_93_param_expansion_alt_value_ok() {
        let code = r#"VALUE=${OTHER:+replacement}"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_issue_93_param_expansion_error_ok() {
        let code = r#"REQUIRED=${VAR:?error message}"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_issue_93_param_expansion_assign_default_ok() {
        let code = r#"VAR=${VAR:=default}"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_issue_93_param_expansion_length_ok() {
        let code = r#"LEN=${#VAR}"#;
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_issue_93_mixed_param_and_brace_flagged() {
        // Parameter expansion at start, but brace expansion in middle - should be flagged
        let code = r#"FILE=${DIR}/{a,b}.txt"#;
        let result = check(code);
        // The {a,b} part is brace expansion and SHOULD be flagged
        assert_eq!(
            result.diagnostics.len(),
            1,
            "Mixed param expansion + brace expansion should be flagged"
        );
    }
}