bashrs 7.0.1

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
use crate::cli::args::{LintFormat, LintLevel, LintProfileArg};
use crate::cli::logic::convert_lint_profile;
use crate::cli::logic::{is_dockerfile, is_makefile, is_shell_script_file};
use crate::models::{Error, Result};
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{info, warn};

pub(crate) struct LintCommandOptions<'a> {
    pub inputs: &'a [PathBuf],
    pub format: LintFormat,
    pub fix: bool,
    pub fix_assumptions: bool,
    pub output: Option<&'a Path>,
    pub no_ignore: bool,
    pub ignore_file_path: Option<&'a Path>,
    pub quiet: bool,
    pub level: LintLevel,
    pub ignore_rules: Option<&'a str>,
    pub exclude_rules: Option<&'a [String]>,
    pub citl_export_path: Option<&'a Path>,
    pub profile: LintProfileArg,
    pub ci: bool,
    pub fail_on: LintLevel,
}

pub(crate) fn lint_command(opts: LintCommandOptions<'_>) -> Result<()> {
    // Expand inputs: directories are walked for shell/make/docker files
    let files = expand_inputs(opts.inputs)?;

    if files.is_empty() {
        return Err(Error::Validation(
            "No lintable files found in the given inputs".to_string(),
        ));
    }

    // For single file, use the original path for backward compatibility
    if files.len() == 1 {
        return lint_single_file(&files[0], &opts);
    }

    // Multi-file mode: lint each file and aggregate results
    lint_multiple_files(&files, &opts)
}

/// Expand input paths: files pass through, directories are walked for lintable files.
fn expand_inputs(inputs: &[PathBuf]) -> Result<Vec<PathBuf>> {
    let mut files = Vec::new();

    for input in inputs {
        if input.is_dir() {
            walk_for_lintable_files(input, &mut files)?;
        } else {
            files.push(input.clone());
        }
    }

    Ok(files)
}

/// Recursively find lintable files (shell, Makefile, Dockerfile) in a directory.
fn walk_for_lintable_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    let entries = fs::read_dir(dir).map_err(Error::Io)?;

    for entry in entries {
        let entry = entry.map_err(Error::Io)?;
        let path = entry.path();

        if path.is_dir() {
            // Skip hidden directories
            if path
                .file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.starts_with('.'))
            {
                continue;
            }
            walk_for_lintable_files(&path, out)?;
        } else {
            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

            // Check by filename first (Makefile, Dockerfile)
            if is_makefile(filename) || is_dockerfile(filename) {
                out.push(path);
                continue;
            }

            // Check by extension or shebang for shell scripts
            if let Ok(content) = fs::read_to_string(&path) {
                if is_shell_script_file(&path, &content) {
                    out.push(path);
                }
            }
        }
    }

    Ok(())
}

fn lint_single_file(input: &Path, opts: &LintCommandOptions<'_>) -> Result<()> {
    use crate::linter::ignore_file::IgnoreResult;
    use crate::linter::rules::lint_shell;
    use crate::linter::{
        rules::{lint_dockerfile_with_profile, lint_makefile, LintProfile},
        LintResult,
    };

    info!("Linting {}", input.display());

    // Issue #85: Load .bashrsignore FIRST to get both file patterns and rule codes
    let ignore_file_data = load_ignore_file(input, opts.no_ignore, opts.ignore_file_path);

    // Check if this file should be ignored (file pattern matching)
    if let Some(ref ignore) = ignore_file_data {
        if let IgnoreResult::Ignored(pattern) = ignore.should_ignore(input) {
            info!(
                "Skipped {} (matched .bashrsignore pattern: {})",
                input.display(),
                pattern
            );
            if !opts.ci {
                println!(
                    "Skipped: {} (matched .bashrsignore pattern: '{}')",
                    input.display(),
                    pattern
                );
            }
            return Ok(());
        }
    }

    // Build set of ignored rule codes from --ignore, -e flags, AND .bashrsignore (Issue #82, #85)
    let ignored_rules = build_ignored_rules(
        opts.ignore_rules,
        opts.exclude_rules,
        ignore_file_data.as_ref(),
    );

    // Determine minimum severity based on --quiet and --level flags (Issue #75)
    let min_severity = determine_min_severity(opts.quiet, opts.level);

    // Helper to filter diagnostics by severity and ignored rules (Issue #75, #82, #85)
    let filter_diagnostics = |result: LintResult| -> LintResult {
        let filtered = result
            .diagnostics
            .into_iter()
            .filter(|d| d.severity >= min_severity)
            .filter(|d| !ignored_rules.contains(&d.code.to_uppercase()))
            .collect();
        LintResult {
            diagnostics: filtered,
        }
    };

    // Read input file
    let source = fs::read_to_string(input).map_err(Error::Io)?;

    // Detect file type and use appropriate linter (using logic module)
    let filename = input.file_name().and_then(|n| n.to_str()).unwrap_or("");
    let file_is_makefile = is_makefile(filename);
    let file_is_dockerfile = is_dockerfile(filename);

    // Convert CLI profile arg to linter profile
    let lint_profile = convert_lint_profile(opts.profile);

    // bashrs has shell, Makefile and Dockerfile rules — and no Rust rules.
    // Running the SHELL rules over Rust produced nonsense: `let x = 42;` was
    // reported as SC1068 "don't put spaces around the = in 'let' assignments".
    // Say so instead of inventing findings.
    if filename.ends_with(".rs") {
        return Err(Error::Validation(format!(
            "{filename}: bashrs lints shell scripts, Makefiles and Dockerfiles; \
             it has no Rust rules. For Rust input use `bashrs check` or \
             `bashrs build` (Rust -> shell transpilation)."
        )));
    }

    // Run linter based on file type
    let result_raw = if file_is_makefile {
        lint_makefile(&source)
    } else if file_is_dockerfile {
        lint_dockerfile_with_profile(&source, lint_profile)
    } else {
        lint_shell(&source)
    };

    // Display profile info if using non-standard profile
    if file_is_dockerfile && lint_profile != LintProfile::Standard {
        info!("Using lint profile: {}", lint_profile);
    }

    // Apply severity filter (Issue #75: --quiet and --level flags)
    let result = filter_diagnostics(result_raw.clone());

    // Issue #83: Export diagnostics in CITL format if requested
    export_citl_if_requested(input, &result_raw, opts.citl_export_path);

    // Apply fixes if requested (use raw result to find all fixable issues)
    if opts.fix && result_raw.diagnostics.iter().any(|d| d.fix.is_some()) {
        handle_lint_fixes(
            input,
            &result_raw,
            opts.fix_assumptions,
            opts.output,
            file_is_makefile,
            opts.format,
            &filter_diagnostics,
        )
    } else if opts.ci {
        // CI mode: emit GitHub Actions annotations
        emit_ci_annotations(input, &result);
        exit_for_fail_on(&result, opts.fail_on)
    } else {
        // GH-209: print, THEN apply the --fail-on threshold. Previously this
        // called a variant that picked the exit code itself, so --fail-on was
        // honoured only under --ci and `bashrs lint --fail-on error Makefile`
        // still exited 1 on a warnings-only run. Default is Warning, so the
        // out-of-the-box exit codes are unchanged.
        output_lint_results_no_exit(&result, opts.format, input)?;
        exit_for_fail_on(&result, opts.fail_on)
    }
}

fn lint_multiple_files(files: &[PathBuf], opts: &LintCommandOptions<'_>) -> Result<()> {
    use crate::linter::rules::lint_shell;
    use crate::linter::{
        rules::{lint_dockerfile_with_profile, lint_makefile},
        LintResult,
    };

    let ignored_rules = build_ignored_rules(opts.ignore_rules, opts.exclude_rules, None);
    let min_severity = determine_min_severity(opts.quiet, opts.level);
    let lint_profile = convert_lint_profile(opts.profile);

    let mut all_results: Vec<(PathBuf, LintResult)> = Vec::new();
    let mut total_errors = 0u32;
    let mut total_warnings = 0u32;

    for file in files {
        let source = match fs::read_to_string(file) {
            Ok(s) => s,
            Err(e) => {
                warn!("Could not read {}: {}", file.display(), e);
                continue;
            }
        };

        let filename = file.file_name().and_then(|n| n.to_str()).unwrap_or("");
        let file_is_makefile = is_makefile(filename);
        let file_is_dockerfile = is_dockerfile(filename);

        let result_raw = if file_is_makefile {
            lint_makefile(&source)
        } else if file_is_dockerfile {
            lint_dockerfile_with_profile(&source, lint_profile)
        } else {
            lint_shell(&source)
        };

        let result = LintResult {
            diagnostics: result_raw
                .diagnostics
                .into_iter()
                .filter(|d| d.severity >= min_severity)
                .filter(|d| !ignored_rules.contains(&d.code.to_uppercase()))
                .collect(),
        };

        if result.has_errors() {
            total_errors += 1;
        }
        if result.has_warnings() {
            total_warnings += 1;
        }

        if opts.ci {
            emit_ci_annotations(file, &result);
        }

        if !result.diagnostics.is_empty() {
            all_results.push((file.clone(), result));
        }
    }

    // Output results
    if !opts.ci {
        for (file, result) in &all_results {
            output_lint_results_no_exit(result, opts.format, file)?;
        }
        eprintln!(
            "\nLinted {} file(s): {} with errors, {} with warnings",
            files.len(),
            total_errors,
            total_warnings,
        );
    }

    // Exit based on --fail-on threshold
    let has_failing = match opts.fail_on {
        LintLevel::Error => total_errors > 0,
        LintLevel::Warning => total_errors > 0 || total_warnings > 0,
        LintLevel::Info => all_results.iter().any(|(_, r)| !r.diagnostics.is_empty()),
    };

    if has_failing {
        if total_errors > 0 {
            std::process::exit(2);
        } else {
            std::process::exit(1);
        }
    }

    Ok(())
}

/// Emit GitHub Actions workflow annotations for each diagnostic.
fn emit_ci_annotations(input: &Path, result: &crate::linter::LintResult) {
    use crate::linter::Severity;

    for diag in &result.diagnostics {
        let level = match diag.severity {
            Severity::Error => "error",
            Severity::Warning | Severity::Risk => "warning",
            Severity::Info | Severity::Note | Severity::Perf => "notice",
        };
        println!(
            "::{level} file={},line={},col={},title={}::{}",
            input.display(),
            diag.span.start_line,
            diag.span.start_col,
            diag.code,
            diag.message,
        );
    }
}

/// Check result against --fail-on threshold and exit appropriately.
fn exit_for_fail_on(result: &crate::linter::LintResult, fail_on: LintLevel) -> Result<()> {
    let should_fail = match fail_on {
        LintLevel::Error => result.has_errors(),
        LintLevel::Warning => result.has_errors() || result.has_warnings(),
        LintLevel::Info => !result.diagnostics.is_empty(),
    };

    if should_fail {
        if result.has_errors() {
            std::process::exit(2);
        } else {
            std::process::exit(1);
        }
    }

    Ok(())
}

/// Load `.bashrsignore` file and return it if found.
///
/// Returns `None` when `no_ignore` is set, no ignore file exists, or the file
/// cannot be loaded. The caller is responsible for checking `should_ignore`.
pub(crate) fn load_ignore_file(
    input: &Path,
    no_ignore: bool,
    ignore_file_path: Option<&Path>,
) -> Option<crate::linter::ignore_file::IgnoreFile> {
    use crate::linter::ignore_file::IgnoreFile;

    if no_ignore {
        return None;
    }

    // Determine ignore file path
    let ignore_path = ignore_file_path
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| {
            // Look for .bashrsignore in current directory or parent directories
            let mut current = input
                .parent()
                .and_then(|p| p.canonicalize().ok())
                .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

            loop {
                let candidate = current.join(".bashrsignore");
                if candidate.exists() {
                    return candidate;
                }
                if !current.pop() {
                    break;
                }
            }
            // Default to current directory
            PathBuf::from(".bashrsignore")
        });

    // Load ignore file if it exists
    match IgnoreFile::load(&ignore_path) {
        Ok(Some(ignore)) => Some(ignore),
        Ok(None) => None,
        Err(e) => {
            warn!("Failed to load .bashrsignore: {}", e);
            None
        }
    }
}

include!("lint_commands_build.rs");