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
409
410
411
412
413
414
415
416
//! MAKE010: Missing error handling (|| exit 1)
//!
//! **Rule**: Detect commands without error handling in recipes
//!
//! **Why this matters**:
//! By default, Make only stops on error if the recipe command returns non-zero.
//! However, some commands may fail silently or have side effects that should
//! stop the build. Adding `|| exit 1` ensures the build stops on failure.
//!
//! **Auto-fix**: Add `|| exit 1` to commands that should fail the build
//!
//! ## Examples
//!
//! ❌ **BAD** (no error handling):
//! ```makefile
//! install:
//!     cp app /usr/bin/app
//!     chmod +x /usr/bin/app
//! ```
//!
//! ✅ **GOOD** (with error handling):
//! ```makefile
//! install:
//!     cp app /usr/bin/app || exit 1
//!     chmod +x /usr/bin/app || exit 1
//! ```

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

/// Commands that should have error handling
const CRITICAL_COMMANDS: &[&str] = &[
    "cp", "mv", "rm", "install", "chmod", "chown", "ln", "mkdir", "curl", "wget", "git",
];

/// Check for missing error handling in recipe commands
pub fn check(source: &str) -> LintResult {
    let mut result = LintResult::new();

    for (line_num, line) in source.lines().enumerate() {
        // Only check recipe lines (start with tab)
        if !line.starts_with('\t') {
            continue;
        }

        let recipe = line.trim();

        // Skip if already has error handling
        if has_error_handling(recipe) {
            continue;
        }

        // Check if line contains a critical command
        if let Some(cmd) = find_critical_command(recipe) {
            let cmd_pos = line.find(cmd).unwrap_or(0);
            let span = Span::new(
                line_num + 1,
                cmd_pos + 1,
                line_num + 1,
                cmd_pos + cmd.len() + 1,
            );

            // Create fix by adding || exit 1
            let fix_replacement = format!("{} || exit 1", line.trim_start());

            let diag = Diagnostic::new(
                "MAKE010",
                Severity::Warning,
                format!(
                    "Command '{}' missing error handling - consider adding '|| exit 1'",
                    cmd
                ),
                span,
            )
            .with_fix(Fix::new(&fix_replacement));

            result.add(diag);
        }
    }

    result
}

/// Check if a recipe line already has error handling
fn has_error_handling(recipe: &str) -> bool {
    recipe.contains("|| exit") || recipe.contains("set -e") || recipe.contains("&&")
}

/// Find if the recipe contains a critical command
///
/// Returns None if the command keyword is inside:
/// - Quoted strings (echo "install", printf 'rm -rf')
/// - Variable assignments (MSG="install here")
/// - Heredocs
/// - Comments
fn find_critical_command(recipe: &str) -> Option<&'static str> {
    // Skip if this is an echo/printf/cat command with quoted strings
    let trimmed = recipe.trim_start_matches('@').trim_start();

    // Check if line starts with echo, printf, or cat (output commands)
    if trimmed.starts_with("echo ") || trimmed.starts_with("printf ") || trimmed.starts_with("cat ")
    {
        return None;
    }

    // Check if this is a variable assignment (VAR="..." or VAR='...')
    if is_variable_assignment(trimmed) {
        return None;
    }

    // Check if we're in a heredoc context
    if trimmed.contains("<<") {
        return None;
    }

    // Now check for actual critical commands
    CRITICAL_COMMANDS
        .iter()
        .find(|&cmd| {
            recipe.split_whitespace().any(|word| {
                word == *cmd
                    || word.starts_with(&format!("{}@", cmd))
                    || word.starts_with(&format!("{}-", cmd))
            })
        })
        .map(|v| v as _)
}

/// Check if a line is a variable assignment
fn is_variable_assignment(line: &str) -> bool {
    // Pattern: VAR="..." or VAR='...'
    if let Some(eq_pos) = line.find('=') {
        let before_eq = &line[..eq_pos];
        // Variable name should be alphanumeric + underscore only
        let is_valid_var_name = before_eq
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '$');

        if is_valid_var_name {
            let after_eq = &line[eq_pos + 1..];
            // Check if value is quoted
            return after_eq.starts_with('"') || after_eq.starts_with('\'');
        }
    }
    false
}

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

    // RED PHASE: Write failing tests first

    #[test]
    fn test_MAKE010_detects_missing_error_handling() {
        let makefile = "install:\n\tcp app /usr/bin/app";
        let result = check(makefile);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert_eq!(diag.code, "MAKE010");
        assert_eq!(diag.severity, Severity::Warning);
        assert!(diag.message.contains("error handling"));
    }

    #[test]
    fn test_MAKE010_no_warning_with_exit_handling() {
        let makefile = "install:\n\tcp app /usr/bin/app || exit 1";
        let result = check(makefile);

        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_MAKE010_provides_fix() {
        let makefile = "install:\n\tcp app /usr/bin/app";
        let result = check(makefile);

        assert!(result.diagnostics[0].fix.is_some());
        let fix = result.diagnostics[0].fix.as_ref().unwrap();
        assert!(fix.replacement.contains("|| exit 1"));
    }

    #[test]
    fn test_MAKE010_detects_multiple_commands() {
        let makefile = "install:\n\tcp app /usr/bin\n\tchmod +x /usr/bin/app";
        let result = check(makefile);

        assert_eq!(result.diagnostics.len(), 2);
    }

    #[test]
    fn test_MAKE010_no_warning_for_safe_commands() {
        let makefile = "build:\n\techo Building...";
        let result = check(makefile);

        // echo doesn't need error handling
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_MAKE010_no_warning_with_set_e() {
        let makefile = "install:\n\tset -e; cp app /usr/bin/app";
        let result = check(makefile);

        // set -e provides error handling
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_MAKE010_detects_git_commands() {
        let makefile = "deploy:\n\tgit pull origin main";
        let result = check(makefile);

        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_MAKE010_no_warning_with_and_chaining() {
        let makefile = "deploy:\n\tgit pull origin main && make build";
        let result = check(makefile);

        // && chaining provides implicit error handling
        assert_eq!(result.diagnostics.len(), 0);
    }

    // Issue #18: Tests for string literal detection

    #[test]
    fn test_MAKE010_no_warning_for_echo_with_command_keyword() {
        let makefile = "help:\n\t@echo \"Run: make install\"";
        let result = check(makefile);

        // Should NOT warn about 'install' in echo string
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_MAKE010_no_warning_for_printf_with_command_keyword() {
        let makefile = "help:\n\t@printf 'Use: rm -rf /tmp\\n'";
        let result = check(makefile);

        // Should NOT warn about 'rm' in printf string
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_MAKE010_no_warning_for_variable_assignment() {
        let makefile = "config:\n\t@MSG=\"install here\"";
        let result = check(makefile);

        // Should NOT warn about 'install' in variable assignment
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_MAKE010_no_warning_for_heredoc() {
        let makefile = "docs:\n\t@cat << EOF";
        let result = check(makefile);

        // Should NOT warn in heredoc context
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_is_variable_assignment_double_quotes() {
        assert!(is_variable_assignment("MSG=\"install here\""));
        assert!(is_variable_assignment("HELP=\"use rm -rf\""));
    }

    #[test]
    fn test_is_variable_assignment_single_quotes() {
        assert!(is_variable_assignment("MSG='install here'"));
        assert!(is_variable_assignment("HELP='use rm -rf'"));
    }

    #[test]
    fn test_is_variable_assignment_unquoted() {
        assert!(!is_variable_assignment("MSG=install"));
        assert!(!is_variable_assignment("HELP=rm"));
    }

    #[test]
    fn test_is_variable_assignment_shell_var() {
        assert!(is_variable_assignment("$$VAR=\"value\""));
    }

    #[test]
    fn test_is_not_variable_assignment() {
        assert!(!is_variable_assignment("echo test"));
        assert!(!is_variable_assignment("cargo install foo"));
    }

    // Property-based tests for Issue #18

    #[cfg(test)]
    mod property_tests {
        use super::*;
        use proptest::prelude::*;

        // Generate valid command keywords
        fn command_keyword() -> impl Strategy<Value = String> {
            prop::sample::select(vec![
                "install", "cp", "mv", "rm", "chmod", "chown", "ln", "mkdir", "curl", "wget", "git",
            ])
            .prop_map(|s| s.to_string())
        }

        proptest! {
        #![proptest_config(proptest::test_runner::Config::with_cases(10))]
            /// Property: echo/printf with command keywords should never trigger MAKE010
            #[test]
            fn prop_echo_with_command_never_warns(
                cmd in command_keyword(),
                prefix in prop::sample::select(vec!["echo", "printf"]),
                text in "[a-zA-Z0-9 ]+",
            ) {
                let recipe = format!("\t@{} \"{}. Use: {} here\"", prefix, text, cmd);
                let makefile = format!("target:\n{}", recipe);
                let result = check(&makefile);

                // Should NOT trigger MAKE010 for command in echo/printf
                let make010_count = result.diagnostics.iter()
                    .filter(|d| d.code == "MAKE010")
                    .count();

                prop_assert_eq!(make010_count, 0,
                    "echo/printf with '{}' in string should not trigger MAKE010", cmd);
            }

            /// Property: Variable assignments with command keywords should never trigger MAKE010
            #[test]
            fn prop_variable_assignment_never_warns(
                cmd in command_keyword(),
                var_name in "[A-Z][A-Z0-9_]{0,10}",
                text in "[a-zA-Z0-9 ]+",
            ) {
                let recipe = format!("\t@{}=\"{} {}\"", var_name, text, cmd);
                let makefile = format!("target:\n{}", recipe);
                let result = check(&makefile);

                // Should NOT trigger MAKE010 for command in variable assignment
                let make010_count = result.diagnostics.iter()
                    .filter(|d| d.code == "MAKE010")
                    .count();

                prop_assert_eq!(make010_count, 0,
                    "Variable assignment with '{}' in value should not trigger MAKE010", cmd);
            }

            /// Property: Actual commands without error handling should always trigger MAKE010
            #[test]
            fn prop_actual_command_always_warns(
                cmd in command_keyword(),
                args in "[a-zA-Z0-9/._-]+",
            ) {
                let recipe = format!("\t{} {}", cmd, args);
                let makefile = format!("target:\n{}", recipe);
                let result = check(&makefile);

                // SHOULD trigger MAKE010 for actual command
                let make010_count = result.diagnostics.iter()
                    .filter(|d| d.code == "MAKE010")
                    .count();

                prop_assert_eq!(make010_count, 1,
                    "Actual '{}' command without error handling should trigger MAKE010", cmd);
            }

            /// Property: Commands with || exit 1 should never trigger MAKE010
            #[test]
            fn prop_command_with_error_handling_never_warns(
                cmd in command_keyword(),
                args in "[a-zA-Z0-9/._-]+",
            ) {
                let recipe = format!("\t{} {} || exit 1", cmd, args);
                let makefile = format!("target:\n{}", recipe);
                let result = check(&makefile);

                // Should NOT trigger MAKE010 when error handling present
                let make010_count = result.diagnostics.iter()
                    .filter(|d| d.code == "MAKE010")
                    .count();

                prop_assert_eq!(make010_count, 0,
                    "Command '{}' with || exit 1 should not trigger MAKE010", cmd);
            }

            /// Property: is_variable_assignment is deterministic
            #[test]
            fn prop_is_variable_assignment_deterministic(line in ".*") {
                let result1 = is_variable_assignment(&line);
                let result2 = is_variable_assignment(&line);
                prop_assert_eq!(result1, result2,
                    "is_variable_assignment should be deterministic");
            }

            /// Property: is_variable_assignment only accepts quoted values
            #[test]
            fn prop_is_variable_assignment_requires_quotes(
                var_name in "[A-Z][A-Z0-9_]{0,10}",
                value in "[a-zA-Z0-9 ]+",
            ) {
                let unquoted = format!("{}={}", var_name, value);
                let double_quoted = format!("{}=\"{}\"", var_name, value);
                let single_quoted = format!("{}='{}'", var_name, value);

                prop_assert!(!is_variable_assignment(&unquoted),
                    "Unquoted assignment should return false");
                prop_assert!(is_variable_assignment(&double_quoted),
                    "Double-quoted assignment should return true");
                prop_assert!(is_variable_assignment(&single_quoted),
                    "Single-quoted assignment should return true");
            }
        }
    }
}