t/check-non-portable-shell: detect "FOO=bar shell_func"

One-shot environment variable assignments, such as 'FOO' in "FOO=bar cmd", exist only during the invocation of 'cmd'. However, if 'cmd' happens to be a shell function, then 'FOO' is assigned in the executing shell itself, and that assignment remains until the process exits (unless explicitly unset). Since this side-effect of "FOO=bar shell_func" is unlikely to be intentional, detect and report such usage. To distinguish shell functions from other commands, perform a pre-scan of shell scripts named as input, gleaning a list of function names by recognizing lines of the form (loosely matching whitespace): shell_func () { and later report suspect lines of the form (loosely matching quoted values): FOO=bar [BAR=foo ...] shell_func Also take care to stitch together incomplete lines (those ending with "\") since suspect invocations may be split over multiple lines: FOO=bar BAR=foo \ shell_func Signed-off-by: Eric Sunshine <sunshine@sunshineco.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Eric Sunshine committed Jul 13, 2018 at 01:52 UTC a0a630192dca77794b2ea94aeb2e6dff0cc1810b
1 file changed +19
t/check-non-portable-shell.pl
+19
@@ -7,17 +7,34 @@ use strict;
7 use warnings;
8
9 my $exit_code=0;
10 +my %func;
11
12 sub err {
13 my $msg = shift;
14 s/^\s+//;
15 s/\s+$//;
16 + s/\s+/ /g;
17 print "$ARGV:$.: error: $msg: $_\n";
18 $exit_code = 1;
19 }
20
21 +# glean names of shell functions
22 +for my $i (@ARGV) {
23 + open(my $f, '<', $i) or die "$0: $i: $!\n";
24 + while (<$f>) {
25 + $func{$1} = 1 if /^\s*(\w+)\s*\(\)\s*{\s*$/;
26 + }
27 + close $f;
28 +}
29 +
30 while (<>) {
31 chomp;
32 + # stitch together incomplete lines (those ending with "\")
33 + while (s/\\$//) {
34 + $_ .= readline;
35 + chomp;
36 + }
37 +
38 /\bsed\s+-i/ and err 'sed -i is not portable';
39 /\becho\s+-[neE]/ and err 'echo with option is not portable (use printf)';
40 /^\s*declare\s+/ and err 'arrays/declare not portable';
@@ -25,6 +42,8 @@ while (<>) {
42 /\btest\s+[^=]*==/ and err '"test a == b" is not portable (use =)';
43 /\bwc -l.*"\s*=/ and err '`"$(wc -l)"` is not portable (use test_line_count)';
44 /\bexport\s+[A-Za-z0-9_]*=/ and err '"export FOO=bar" is not portable (use FOO=bar && export FOO)';
45 + /^\s*([A-Z0-9_]+=(\w+|(["']).*?\3)\s+)+(\w+)/ and exists($func{$4}) and
46 + err '"FOO=bar shell_func" assignment extends beyond "shell_func"';
47 # this resets our $. for each file
48 close ARGV if eof;
49 }