shuck-linter 0.0.26

Lint rule engine and checker for shell 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
407
408
409
410
use crate::{Checker, Rule, ShellDialect, Violation};
use shuck_ast::{Command, Span};
use shuck_semantic::ScopeKind;

pub struct UncheckedDirectoryChange {
    pub command: &'static str,
}

impl Violation for UncheckedDirectoryChange {
    fn rule() -> Rule {
        Rule::UncheckedDirectoryChange
    }

    fn message(&self) -> String {
        format!(
            "`{}` should check whether the directory change succeeded",
            self.command
        )
    }
}

pub fn unchecked_directory_change(checker: &mut Checker) {
    if !supports_directory_change_rules(checker.shell()) {
        return;
    }

    for (command, span) in unchecked_directory_change_spans(checker) {
        checker.report(UncheckedDirectoryChange { command }, span);
    }
}

pub(crate) fn unchecked_directory_change_spans(checker: &mut Checker) -> Vec<(&'static str, Span)> {
    let semantic = checker.semantic();
    let source = checker.source();
    let errexit_enabled_somewhere = checker.facts().errexit_enabled_anywhere();
    checker
        .facts()
        .commands()
        .iter()
        .filter_map(|fact| {
            let scope = semantic.scope_at(fact.stmt().span.start.offset);
            if fact.is_nested_word_command()
                && !matches!(semantic.scope_kind(scope), ScopeKind::CommandSubstitution)
            {
                return None;
            }

            let directory_change = fact.options().directory_change()?;
            let unchecked = semantic
                .flow_context_at(&fact.stmt().span)
                .map(|context| !context.exit_status_checked)
                .unwrap_or(true);

            (unchecked
                && !errexit_enabled_somewhere
                && !directory_change.is_plain_directory_stack_marker())
            .then_some((directory_change.command_name(), report_span(fact, source)))
        })
        .collect::<Vec<_>>()
}

pub(crate) fn report_span(fact: crate::facts::CommandFactRef<'_, '_>, source: &str) -> Span {
    match fact.command() {
        Command::Simple(command) => {
            let mut start = command.name.span.start;
            if command.name.span.slice(source).starts_with('\\') {
                start = start.advanced_by("\\");
            }
            let end = command
                .args
                .last()
                .map(|word| word.span.end)
                .into_iter()
                .chain(fact.redirects().iter().map(|redirect| redirect.span.end))
                .max_by_key(|position| position.offset)
                .unwrap_or(command.name.span.end);
            Span::from_positions(start, end)
        }
        _ => fact.span(),
    }
}

pub(crate) fn supports_directory_change_rules(shell: ShellDialect) -> bool {
    matches!(
        shell,
        ShellDialect::Unknown
            | ShellDialect::Sh
            | ShellDialect::Bash
            | ShellDialect::Dash
            | ShellDialect::Ksh
    )
}

#[cfg(test)]
mod tests {
    use crate::test::test_snippet;
    use crate::{LinterSettings, Rule, ShellDialect};

    #[test]
    fn reports_plain_cd_commands() {
        let source = "cd /tmp\n";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span.slice(source), "cd /tmp");
    }

    #[test]
    fn ignores_checked_directory_changes() {
        let source = "\
if cd /tmp; then
\tpwd
fi
if ! builtin cd /var; then
\treturn 1
fi
cd /tmp || exit 1
cd /tmp && pwd
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert!(diagnostics.is_empty(), "diagnostics: {diagnostics:?}");
    }

    #[test]
    fn ignores_directory_change_inside_checked_subshell_group() {
        let source = "\
make_tar() {
  (cd \"$DIST_ROOT/unix/\"; tar -czf \"../out.tgz\" out) || die
}
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert!(diagnostics.is_empty(), "diagnostics: {diagnostics:?}");
    }

    #[test]
    fn reports_cd_in_following_list_position() {
        let source = "echo start && cd /tmp\n";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span.slice(source), "cd /tmp");
    }

    #[test]
    fn reports_pushd_popd_escaped_and_wrapped_cd() {
        let source = "\
pushd /tmp
popd
\\cd /var >/dev/null
builtin cd /opt
cd /srv # inline comment
pushd /work >/dev/null
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(
            diagnostics
                .iter()
                .map(|diagnostic| diagnostic.span.slice(source))
                .collect::<Vec<_>>(),
            vec![
                "pushd /tmp",
                "popd",
                "cd /var >/dev/null",
                "builtin cd /opt",
                "cd /srv",
                "pushd /work >/dev/null"
            ]
        );
    }

    #[test]
    fn ignores_directory_changes_when_errexit_is_enabled_anywhere() {
        let source = "\
cd /start
set -e
cd /tmp
set +e
cd /var
set -o errexit
pushd /opt
set +o errexit
popd
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert!(diagnostics.is_empty(), "diagnostics: {diagnostics:?}");
    }

    #[test]
    fn ignores_directory_stack_markers() {
        let source = "\
cd .
cd ..
cd /
cd ../..
cd ./../..
pushd .
pushd ..
pushd /
pushd ../..
popd
cd ./child
cd ../../child
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(
            diagnostics
                .iter()
                .map(|diagnostic| diagnostic.span.slice(source))
                .collect::<Vec<_>>(),
            vec!["popd", "cd ./child", "cd ../../child"]
        );
    }

    #[test]
    fn wrapped_directory_stack_markers_still_report() {
        let source = "\
builtin cd ..
command cd /
\\cd ..
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(
            diagnostics
                .iter()
                .map(|diagnostic| diagnostic.span.slice(source))
                .collect::<Vec<_>>(),
            vec!["builtin cd ..", "command cd /"]
        );
    }

    #[test]
    fn ignores_directory_changes_when_shebang_enables_errexit() {
        let source = "\
#!/bin/bash -eux
cd /tmp
pushd /var
popd
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert!(diagnostics.is_empty(), "diagnostics: {diagnostics:?}");
    }

    #[test]
    fn shebang_without_errexit_still_reports() {
        let source = "\
#!/bin/bash -u
cd /tmp
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span.slice(source), "cd /tmp");
    }

    #[test]
    fn long_shebang_options_do_not_suppress_reports() {
        let source = "\
#!/bin/bash --noprofile
cd /tmp
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span.slice(source), "cd /tmp");
    }

    #[test]
    fn ignores_errexit_shebang_after_leading_blank_lines() {
        let source = "\n#!/bin/bash -eu\ncd /tmp\n";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert!(diagnostics.is_empty(), "diagnostics: {diagnostics:?}");
    }

    #[test]
    fn reports_nested_cd_inside_command_substitutions() {
        let source = "path=\"$( \\cd /tmp>/dev/null; pwd )\"\n";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span.slice(source), "cd /tmp>/dev/null");
    }

    #[test]
    fn reports_directory_changes_inside_functions_when_specific_rule_is_disabled() {
        let source = "\
#!/bin/sh
f() {
\tcd /tmp
}
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span.slice(source), "cd /tmp");
    }

    #[test]
    fn nested_command_substitutions_inside_functions_still_use_the_general_rule() {
        let source = "\
#!/bin/sh
f() {
\tpath=\"$(cd /tmp; pwd)\"
}
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rules([
                Rule::UncheckedDirectoryChange,
                Rule::UncheckedDirectoryChangeInFunction,
            ]),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].rule, Rule::UncheckedDirectoryChange);
        assert_eq!(diagnostics[0].span.slice(source), "cd /tmp");
    }

    #[test]
    fn still_reports_function_scoped_directory_changes_when_c125_is_enabled() {
        let source = "\
#!/bin/sh
f() {
\tcd /tmp
\tcd ..
}
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rules([
                Rule::UncheckedDirectoryChange,
                Rule::UncheckedDirectoryChangeInFunction,
            ]),
        );

        assert_eq!(
            diagnostics
                .iter()
                .map(|diagnostic| (diagnostic.rule, diagnostic.span.slice(source)))
                .collect::<Vec<_>>(),
            vec![
                (Rule::UncheckedDirectoryChange, "cd /tmp"),
                (Rule::UncheckedDirectoryChangeInFunction, "cd ..")
            ]
        );
    }

    #[test]
    fn ignores_zsh_scripts() {
        let source = "\
#!/bin/zsh
cd /tmp
";
        let diagnostics = test_snippet(
            source,
            &LinterSettings::for_rule(Rule::UncheckedDirectoryChange).with_shell(ShellDialect::Zsh),
        );

        assert!(diagnostics.is_empty(), "diagnostics: {diagnostics:?}");
    }
}