From 7b998239afe21e89c1c57e7f26947fb4b640214f Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Mon, 17 Feb 2020 18:02:23 -0800 Subject: [PATCH] SC2257: Warn when changing arithmetic variables in redirections --- CHANGELOG.md | 1 + src/ShellCheck/Analytics.hs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5931276..11860ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - SC2254: Suggest quoting expansions in case statements - SC2255: Suggest using `$((..))` in `[ 2*3 -eq 6 ]` - SC2256: Warn about translated strings that are known variables +- SC2257: Warn about arithmetic mutation in redirections ### Changed - SC2230: 'command -v' suggestion is now off by default (-i deprecate-which) diff --git a/src/ShellCheck/Analytics.hs b/src/ShellCheck/Analytics.hs index e695d24..df3d3f4 100644 --- a/src/ShellCheck/Analytics.hs +++ b/src/ShellCheck/Analytics.hs @@ -189,6 +189,7 @@ nodeChecks = [ ,checkDollarQuoteParen ,checkUselessBang ,checkTranslatedStringVariable + ,checkModifiedArithmeticInRedirection ] optionalChecks = map fst optionalTreeChecks @@ -3530,5 +3531,40 @@ checkUselessBang params t = when (hasSetE params) $ mapM_ check (getNonReturning x:rest -> x : dropLast rest _ -> [] +prop_checkModifiedArithmeticInRedirection1 = verify checkModifiedArithmeticInRedirection "ls > $((i++))" +prop_checkModifiedArithmeticInRedirection2 = verify checkModifiedArithmeticInRedirection "cat < \"foo$((i++)).txt\"" +prop_checkModifiedArithmeticInRedirection3 = verifyNot checkModifiedArithmeticInRedirection "while true; do true; done > $((i++))" +prop_checkModifiedArithmeticInRedirection4 = verify checkModifiedArithmeticInRedirection "cat <<< $((i++))" +prop_checkModifiedArithmeticInRedirection5 = verify checkModifiedArithmeticInRedirection "cat << foo\n$((i++))\nfoo\n" +checkModifiedArithmeticInRedirection _ t = + case t of + T_Redirecting _ redirs (T_SimpleCommand _ _ (_:_)) -> mapM_ checkRedirs redirs + _ -> return () + where + checkRedirs t = + case t of + T_FdRedirect _ _ (T_IoFile _ _ word) -> + mapM_ checkArithmetic $ getWordParts word + T_FdRedirect _ _ (T_HereString _ word) -> + mapM_ checkArithmetic $ getWordParts word + T_FdRedirect _ _ (T_HereDoc _ _ _ _ list) -> + mapM_ checkArithmetic list + _ -> return () + checkArithmetic t = + case t of + T_DollarArithmetic _ x -> checkModifying x + _ -> return () + checkModifying t = + case t of + TA_Sequence _ list -> mapM_ checkModifying list + TA_Unary id s _ | s `elem` ["|++", "++|", "|--", "--|"] -> warnFor id + TA_Assignment id _ _ _ -> warnFor id + TA_Binary _ _ x y -> mapM_ checkModifying [x ,y] + TA_Trinary _ x y z -> mapM_ checkModifying [x, y, z] + _ -> return () + warnFor id = + warn id 2257 "Arithmetic modifications in command redirections may be discarded. Do them separately." + + return [] runTests = $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])