mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-09-30 16:59:20 +08:00
Compare commits
26 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
1ff67a61b4 | ||
|
349dfdab35 | ||
|
1ab29ddb39 | ||
|
09b7788412 | ||
|
ef2135f3aa | ||
|
d10c3b2709 | ||
|
ca37794b7c | ||
|
8b8b48ef55 | ||
|
aea0310a07 | ||
|
7fff088ce9 | ||
|
65ab8c8ecb | ||
|
3a041954d1 | ||
|
828378cdff | ||
|
509cda4dcf | ||
|
6076f0b1da | ||
|
1d26c280d6 | ||
|
c785d43e34 | ||
|
4c3e731445 | ||
|
3940462da3 | ||
|
bb7ef5834b | ||
|
2f7bd556e8 | ||
|
081751c1b5 | ||
|
cc86aab3f1 | ||
|
9f1f00cdd1 | ||
|
93debd3556 | ||
|
47b971c582 |
141
LICENSE
141
LICENSE
@@ -1,5 +1,5 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
@@ -7,15 +7,17 @@
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
@@ -24,34 +26,44 @@ them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
@@ -60,7 +72,7 @@ modification follow.
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
@@ -537,45 +549,35 @@ to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
@@ -633,29 +635,40 @@ the "copyright" line and a pointer to where the full notice is found.
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
|
24
README.md
24
README.md
@@ -3,7 +3,7 @@
|
||||
http://www.shellcheck.net
|
||||
|
||||
Copyright 2012-2015, Vidar 'koala_man' Holen
|
||||
Licensed under the GNU Affero General Public License, v3
|
||||
Licensed under the GNU General Public License, v3
|
||||
|
||||
The goals of ShellCheck are:
|
||||
|
||||
@@ -57,6 +57,10 @@ On Mac OS X with MacPorts (http://www.macports.org/):
|
||||
|
||||
port install hs-cabal-install
|
||||
|
||||
On native Windows (https://www.haskell.org/platform/):
|
||||
|
||||
Download and install the latest version of the Haskell Platform.
|
||||
|
||||
Let cabal update itself, in case your distro version is outdated:
|
||||
|
||||
$ cabal update
|
||||
@@ -66,17 +70,29 @@ With cabal installed, cd to the ShellCheck source directory and:
|
||||
|
||||
$ cabal install
|
||||
|
||||
This will install ShellCheck to your ~/.cabal/bin directory.
|
||||
This will install ShellCheck to your `~/.cabal/bin` directory.
|
||||
|
||||
Add the directory to your PATH (for bash, add this to your ~/.bashrc file):
|
||||
Add the directory to your `PATH` (for bash, add this to your `~/.bashrc`):
|
||||
|
||||
export PATH=$HOME/.cabal/bin:$PATH
|
||||
export PATH="$HOME/.cabal/bin:$PATH"
|
||||
|
||||
Verify that your PATH is set up correctly:
|
||||
|
||||
$ which shellcheck
|
||||
~/.cabal/bin/shellcheck
|
||||
|
||||
On native Windows, the `PATH` should already be set up, but the system
|
||||
may use a legacy codepage. In `cmd.exe`, `powershell.exe` and Powershell ISE,
|
||||
make sure to use a TrueType font, not a Raster font, and set the active
|
||||
codepage to UTF-8 (65001) with `chcp`:
|
||||
|
||||
> chcp 65001
|
||||
Active code page: 65001
|
||||
|
||||
In Powershell ISE, you may need to additionally update the output encoding:
|
||||
|
||||
> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
## Running tests
|
||||
|
||||
To run the unit test suite:
|
||||
|
@@ -1,7 +1,7 @@
|
||||
Name: ShellCheck
|
||||
Version: 0.3.6
|
||||
Version: 0.3.8
|
||||
Synopsis: Shell script analysis tool
|
||||
License: AGPL-3
|
||||
License: GPL-3
|
||||
License-file: LICENSE
|
||||
Category: Static Analysis
|
||||
Author: Vidar Holen
|
||||
@@ -43,7 +43,7 @@ library
|
||||
json,
|
||||
mtl,
|
||||
parsec,
|
||||
regex-compat,
|
||||
regex-tdfa,
|
||||
QuickCheck >= 2.7.4
|
||||
exposed-modules:
|
||||
ShellCheck.Analytics
|
||||
@@ -51,6 +51,7 @@ library
|
||||
ShellCheck.Data
|
||||
ShellCheck.Options
|
||||
ShellCheck.Parser
|
||||
ShellCheck.Regex
|
||||
ShellCheck.Simple
|
||||
other-modules:
|
||||
Paths_ShellCheck
|
||||
@@ -64,7 +65,7 @@ executable shellcheck
|
||||
json,
|
||||
mtl,
|
||||
parsec,
|
||||
regex-compat,
|
||||
regex-tdfa,
|
||||
transformers,
|
||||
QuickCheck >= 2.7.4
|
||||
main-is: shellcheck.hs
|
||||
@@ -79,7 +80,7 @@ test-suite test-shellcheck
|
||||
json,
|
||||
mtl,
|
||||
parsec,
|
||||
regex-compat,
|
||||
regex-tdfa,
|
||||
transformers,
|
||||
QuickCheck >= 2.7.4
|
||||
main-is: test/shellcheck.hs
|
||||
|
@@ -3,23 +3,23 @@
|
||||
http://www.vidarholen.net/contents/shellcheck
|
||||
|
||||
ShellCheck is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ShellCheck is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
-}
|
||||
module ShellCheck.AST where
|
||||
|
||||
import Control.Monad
|
||||
import Control.Monad.Identity
|
||||
import qualified Text.Regex as Re
|
||||
import qualified ShellCheck.Regex as Re
|
||||
|
||||
data Id = Id Int deriving (Show, Eq, Ord)
|
||||
|
||||
@@ -53,7 +53,7 @@ data Token =
|
||||
| T_Backticked Id [Token]
|
||||
| T_Bang Id
|
||||
| T_Banged Id Token
|
||||
| T_BraceExpansion Id String
|
||||
| T_BraceExpansion Id [Token]
|
||||
| T_BraceGroup Id [Token]
|
||||
| T_CLOBBER Id
|
||||
| T_Case Id
|
||||
@@ -128,11 +128,13 @@ data Token =
|
||||
data Annotation = DisableComment Integer deriving (Show, Eq)
|
||||
data ConditionType = DoubleBracket | SingleBracket deriving (Show, Eq)
|
||||
|
||||
-- I apologize for nothing!
|
||||
lolHax s = Re.subRegex (Re.mkRegex "(Id [0-9]+)") (show s) "(Id 0)"
|
||||
instance Eq Token where
|
||||
(==) a b = lolHax a == lolHax b
|
||||
-- This is an abomination.
|
||||
tokenEquals :: Token -> Token -> Bool
|
||||
tokenEquals a b = kludge a == kludge b
|
||||
where kludge s = Re.subRegex (Re.mkRegex "\\(Id [0-9]+\\)") (show s) "(Id 0)"
|
||||
|
||||
instance Eq Token where
|
||||
(==) = tokenEquals
|
||||
|
||||
analyze :: Monad m => (Token -> m ()) -> (Token -> m ()) -> (Token -> Token) -> Token -> m Token
|
||||
analyze f g i =
|
||||
@@ -169,6 +171,7 @@ analyze f g i =
|
||||
delve (T_DoubleQuoted id list) = dl list $ T_DoubleQuoted id
|
||||
delve (T_DollarDoubleQuoted id list) = dl list $ T_DollarDoubleQuoted id
|
||||
delve (T_DollarExpansion id list) = dl list $ T_DollarExpansion id
|
||||
delve (T_BraceExpansion id list) = dl list $ T_BraceExpansion id
|
||||
delve (T_Backticked id list) = dl list $ T_Backticked id
|
||||
delve (T_DollarArithmetic id c) = d1 c $ T_DollarArithmetic id
|
||||
delve (T_DollarBracket id c) = d1 c $ T_DollarBracket id
|
||||
|
@@ -3,19 +3,19 @@
|
||||
http://www.vidarholen.net/contents/shellcheck
|
||||
|
||||
ShellCheck is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ShellCheck is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
-}
|
||||
{-# LANGUAGE TemplateHaskell #-}
|
||||
{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}
|
||||
module ShellCheck.Analytics (AnalysisOptions(..), defaultAnalysisOptions, filterByAnnotation, runAnalytics, shellForExecutable, runTests) where
|
||||
|
||||
import Control.Arrow (first)
|
||||
@@ -33,7 +33,7 @@ import ShellCheck.AST
|
||||
import ShellCheck.Options
|
||||
import ShellCheck.Data
|
||||
import ShellCheck.Parser hiding (runTests)
|
||||
import Text.Regex
|
||||
import ShellCheck.Regex
|
||||
import qualified Data.Map as Map
|
||||
import Test.QuickCheck.All (forAllProperties)
|
||||
import Test.QuickCheck.Test (quickCheckWithResult, stdArgs, maxSuccess)
|
||||
@@ -203,6 +203,7 @@ nodeChecks = [
|
||||
,checkFindExecWithSingleArgument
|
||||
,checkReturn
|
||||
,checkMaskedReturns
|
||||
,checkInjectableFindSh
|
||||
]
|
||||
|
||||
|
||||
@@ -240,12 +241,6 @@ isVariableName _ = False
|
||||
|
||||
potentially = fromMaybe (return ())
|
||||
|
||||
matchAll re = unfoldr f
|
||||
where
|
||||
f str = do
|
||||
(_, match, rest, _) <- matchRegexAll re str
|
||||
return (match, rest)
|
||||
|
||||
willSplit x =
|
||||
case x of
|
||||
T_DollarBraced {} -> True
|
||||
@@ -280,20 +275,9 @@ getSuspiciousRegexWildcard str =
|
||||
suspicious = mkRegex "([A-Za-z1-9])\\*"
|
||||
contra = mkRegex "[^a-zA-Z1-9]\\*|[][^$+\\\\]"
|
||||
|
||||
matches string regex = isJust $ matchRegex regex string
|
||||
|
||||
headOrDefault _ (a:_) = a
|
||||
headOrDefault def _ = def
|
||||
|
||||
getAllMatches :: Regex -> String -> [[String]]
|
||||
getAllMatches regex str = fromJust $ f str
|
||||
where
|
||||
f str = do
|
||||
(_, _, rest, groups) <- matchRegexAll regex str
|
||||
more <- f rest
|
||||
return $ groups : more
|
||||
`mappend` return []
|
||||
|
||||
isConstant token =
|
||||
case token of
|
||||
T_NormalWord _ l -> all isConstant l
|
||||
@@ -335,15 +319,18 @@ deadSimple (TA_Sequence _ [TA_Expansion _ v]) = concatMap deadSimple v
|
||||
deadSimple _ = []
|
||||
|
||||
-- Turn a SimpleCommand foo -avz --bar=baz into args ["a", "v", "z", "bar"]
|
||||
getFlags (T_SimpleCommand _ _ (_:args)) =
|
||||
let textArgs = takeWhile (/= "--") $ map (concat . deadSimple) args in
|
||||
getFlagsUntil stopCondition (T_SimpleCommand _ _ (_:args)) =
|
||||
let textArgs = takeWhile (not . stopCondition . snd) $ map (\x -> (x, concat $ deadSimple x)) args in
|
||||
concatMap flag textArgs
|
||||
where
|
||||
flag ('-':'-':arg) = [ takeWhile (/= '=') arg ]
|
||||
flag ('-':args) = map (:[]) args
|
||||
flag (x, ('-':'-':arg)) = [ (x, takeWhile (/= '=') arg) ]
|
||||
flag (x, ('-':args)) = map (\v -> (x, [v])) args
|
||||
flag _ = []
|
||||
|
||||
getFlags _ = error "Internal shellcheck error, please report! (getFlags on non-command)"
|
||||
getFlagsUntil _ _ = error "Internal shellcheck error, please report! (getFlags on non-command)"
|
||||
|
||||
getAllFlags = getFlagsUntil (== "--")
|
||||
getLeadingFlags = getFlagsUntil (not . ("-" `isPrefixOf`))
|
||||
|
||||
(!!!) list i =
|
||||
case drop i list of
|
||||
@@ -390,6 +377,7 @@ dist a b
|
||||
lab = length a - length b
|
||||
min3 x y z = if x < y then x else min y z
|
||||
|
||||
hasFloatingPoint params = shellType params == Ksh
|
||||
|
||||
prop_checkEchoWc3 = verify checkEchoWc "n=$(echo $foo | wc -c)"
|
||||
checkEchoWc _ (T_Pipeline id _ [a, b]) =
|
||||
@@ -413,14 +401,19 @@ checkEchoSed _ (T_Pipeline id _ [a, b]) =
|
||||
["sed", "-e", v] -> checkIn v
|
||||
_ -> return ()
|
||||
where
|
||||
sedRe = mkRegex "^s(.)(.*)\\1(.*)\\1g?$"
|
||||
-- This should have used backreferences, but TDFA doesn't support them
|
||||
sedRe = mkRegex "^s(.)([^\n]*)g?$"
|
||||
isSimpleSed s = fromMaybe False $ do
|
||||
[first,rest] <- matchRegex sedRe s
|
||||
let delimiters = filter (== (first !! 0)) rest
|
||||
guard $ length delimiters == 2
|
||||
return True
|
||||
|
||||
acmd = deadSimple a
|
||||
bcmd = deadSimple b
|
||||
checkIn s =
|
||||
case matchRegex sedRe s of
|
||||
Just _ -> style id 2001
|
||||
"See if you can use ${variable//search/replace} instead."
|
||||
_ -> return ()
|
||||
when (isSimpleSed s) $
|
||||
style id 2001 "See if you can use ${variable//search/replace} instead."
|
||||
checkEchoSed _ _ = return ()
|
||||
|
||||
prop_checkPipedAssignment1 = verify checkPipedAssignment "A=ls | grep foo"
|
||||
@@ -642,6 +635,13 @@ prop_checkBashisms16= verify checkBashisms "echo $RANDOM"
|
||||
prop_checkBashisms17= verify checkBashisms "echo $((RANDOM%6+1))"
|
||||
prop_checkBashisms18= verify checkBashisms "foo &> /dev/null"
|
||||
prop_checkBashisms19= verify checkBashisms "foo > file*.txt"
|
||||
prop_checkBashisms20= verify checkBashisms "read -ra foo"
|
||||
prop_checkBashisms21= verify checkBashisms "[ -a foo ]"
|
||||
prop_checkBashisms22= verifyNot checkBashisms "[ foo -a bar ]"
|
||||
prop_checkBashisms23= verify checkBashisms "trap mything err int"
|
||||
prop_checkBashisms24= verifyNot checkBashisms "trap mything int term"
|
||||
prop_checkBashisms25= verify checkBashisms "cat < /dev/tcp/host/123"
|
||||
prop_checkBashisms26= verify checkBashisms "trap mything ERR SIGTERM"
|
||||
checkBashisms _ = bashism
|
||||
where
|
||||
errMsg id s = err id 2040 $ "In sh, " ++ s ++ " not supported, even when sh is actually bash."
|
||||
@@ -660,24 +660,42 @@ checkBashisms _ = bashism
|
||||
bashism (TC_Binary id SingleBracket op _ _)
|
||||
| op `elem` [ "-nt", "-ef", "\\<", "\\>", "==" ] =
|
||||
warnMsg id $ op ++ " is"
|
||||
bashism (TC_Unary id _ "-a" _) =
|
||||
warnMsg id "unary -a in place of -e is"
|
||||
bashism (TA_Unary id op _)
|
||||
| op `elem` [ "|++", "|--", "++|", "--|"] =
|
||||
warnMsg id $ filter (/= '|') op ++ " is"
|
||||
bashism t@(T_SimpleCommand id _ _)
|
||||
| t `isCommand` "source" =
|
||||
warnMsg id "'source' in place of '.' is"
|
||||
bashism (TA_Binary id "**" _ _) = warnMsg id "exponentials are"
|
||||
bashism (T_FdRedirect id "&" (T_IoFile _ (T_Greater _) _)) = warnMsg id "&> is"
|
||||
bashism t@(TA_Expansion id _) | getLiteralString t == Just "RANDOM" =
|
||||
warnMsg id "RANDOM is"
|
||||
bashism t@(T_DollarBraced id _) | getBracedReference (bracedString t) == "RANDOM" =
|
||||
warnMsg id "$RANDOM is"
|
||||
bashism (T_DollarBraced id token) =
|
||||
bashism (T_IoFile id _ word) | isNetworked =
|
||||
warnMsg id "/dev/{tcp,udp} is"
|
||||
where
|
||||
file = onlyLiteralString word
|
||||
isNetworked = any (`isPrefixOf` file) ["/dev/tcp", "/dev/udp"]
|
||||
|
||||
bashism t@(TA_Expansion id _) | isBashism =
|
||||
warnMsg id $ fromJust str ++ " is"
|
||||
where
|
||||
str = getLiteralString t
|
||||
isBashism = isJust str && fromJust str `elem` bashVars
|
||||
bashism t@(T_DollarBraced id token) = do
|
||||
mapM_ check expansion
|
||||
when (var `elem` bashVars) $ warnMsg id $ var ++ " is"
|
||||
where
|
||||
str = concat $ deadSimple token
|
||||
var = getBracedReference (bracedString token)
|
||||
check (regex, feature) =
|
||||
when (isJust $ matchRegex regex str) $ warnMsg id feature
|
||||
|
||||
bashism t@(T_Pipe id "|&") =
|
||||
warnMsg id "|& in place of 2>&1 | is"
|
||||
bashism (T_Array id _) =
|
||||
warnMsg id "arrays are"
|
||||
bashism (T_IoFile id _ t) | isGlob t =
|
||||
warnMsg id "redirecting to/from globs is"
|
||||
bashism (T_CoProc id _ _) =
|
||||
warnMsg id "coproc is"
|
||||
|
||||
bashism t@(T_SimpleCommand _ _ (cmd:arg:_))
|
||||
| t `isCommand` "echo" && "-" `isPrefixOf` argString =
|
||||
unless ("--" `isPrefixOf` argString) $ -- echo "-------"
|
||||
@@ -688,14 +706,38 @@ checkBashisms _ = bashism
|
||||
warnMsg (getId arg) "exec flags are"
|
||||
bashism t@(T_SimpleCommand id _ _)
|
||||
| t `isCommand` "let" = warnMsg id "'let' is"
|
||||
bashism t@(T_Pipe id "|&") =
|
||||
warnMsg id "|& in place of 2>&1 | is"
|
||||
bashism (T_Array id _) =
|
||||
warnMsg id "arrays are"
|
||||
bashism (T_IoFile id _ t) | isGlob t =
|
||||
warnMsg id "redirecting to/from globs is"
|
||||
bashism (T_CoProc id _ _) =
|
||||
warnMsg id "coproc is"
|
||||
|
||||
bashism t@(T_SimpleCommand id _ (cmd:rest)) =
|
||||
let name = fromMaybe "" $ getCommandName t
|
||||
flags = getLeadingFlags t
|
||||
in do
|
||||
when (name `elem` bashCommands) $ warnMsg id $ "'" ++ name ++ "' is"
|
||||
potentially $ do
|
||||
allowed <- Map.lookup name allowedFlags
|
||||
(word, flag) <- listToMaybe $ filter (\x -> snd x `notElem` allowed) flags
|
||||
return . warnMsg (getId word) $ name ++ " -" ++ flag ++ " is"
|
||||
|
||||
when (name == "source") $ warnMsg id "'source' in place of '.' is"
|
||||
when (name == "trap") $
|
||||
let
|
||||
check token = potentially $ do
|
||||
word <- liftM (map toLower) $ getLiteralString token
|
||||
guard $ word `elem` ["err", "debug", "return"]
|
||||
return $ warnMsg (getId token) $ "trapping " ++ word ++ " is"
|
||||
in
|
||||
mapM_ check (reverse rest)
|
||||
where
|
||||
bashCommands = [
|
||||
"let", "caller", "builtin", "complete", "compgen", "declare", "dirs", "disown",
|
||||
"enable", "mapfile", "readarray", "pushd", "popd", "shopt", "suspend", "type",
|
||||
"typeset"
|
||||
]
|
||||
allowedFlags = Map.fromList [
|
||||
("read", ["r"]),
|
||||
("ulimit", ["f"]),
|
||||
("echo", []),
|
||||
("exec", [])
|
||||
]
|
||||
|
||||
bashism _ = return ()
|
||||
|
||||
@@ -705,8 +747,11 @@ checkBashisms _ = bashism
|
||||
(re $ "^![" ++ varChars ++ "]+\\[[*@]]$", "array key expansion is"),
|
||||
(re $ "^![" ++ varChars ++ "]+[*@]$", "name matching prefixes are"),
|
||||
(re $ "^[" ++ varChars ++ "]+:[^-=?+]", "string indexing is"),
|
||||
(re $ "^[" ++ varChars ++ "]+(\\[.*\\])?/", "string replacement is"),
|
||||
(re "^RANDOM$", "$RANDOM is")
|
||||
(re $ "^[" ++ varChars ++ "]+(\\[.*\\])?/", "string replacement is")
|
||||
]
|
||||
bashVars = [
|
||||
"RANDOM", "LINENO", "OSTYPE", "MACHTYPE", "HOSTTYPE", "HOSTNAME",
|
||||
"DIRSTACK", "EUID", "UID", "SECONDS", "SHLVL", "PIPESTATUS", "SHELLOPTS"
|
||||
]
|
||||
|
||||
prop_checkForInQuoted = verify checkForInQuoted "for f in \"$(ls)\"; do echo foo; done"
|
||||
@@ -871,13 +916,14 @@ prop_checkShorthandIf = verify checkShorthandIf "[[ ! -z file ]] && scp file ho
|
||||
prop_checkShorthandIf2 = verifyNot checkShorthandIf "[[ ! -z file ]] && { scp file host || echo 'Eek'; }"
|
||||
prop_checkShorthandIf3 = verifyNot checkShorthandIf "foo && bar || echo baz"
|
||||
prop_checkShorthandIf4 = verifyNot checkShorthandIf "foo && a=b || a=c"
|
||||
prop_checkShorthandIf5 = verifyNot checkShorthandIf "foo && rm || printf b"
|
||||
checkShorthandIf _ (T_AndIf id _ (T_OrIf _ _ (T_Pipeline _ _ t)))
|
||||
| not $ isOk t =
|
||||
info id 2015 "Note that A && B || C is not if-then-else. C may run when A is true."
|
||||
where
|
||||
isOk [t] = isAssignment t || fromMaybe False (do
|
||||
name <- getCommandBasename t
|
||||
return $ name `elem` ["echo", "exit", "return"])
|
||||
return $ name `elem` ["echo", "exit", "return", "printf"])
|
||||
isOk _ = False
|
||||
checkShorthandIf _ _ = return ()
|
||||
|
||||
@@ -906,7 +952,7 @@ prop_checkUnquotedDollarAt8 = verifyNot checkUnquotedDollarAt "echo \"${args[@]:
|
||||
checkUnquotedDollarAt p word@(T_NormalWord _ parts) | not $ isStrictlyQuoteFree (parentMap p) word =
|
||||
forM_ (take 1 $ filter isArrayExpansion parts) $ \x ->
|
||||
err (getId x) 2068
|
||||
"Double quote array expansions, otherwise they're like $* and break on spaces."
|
||||
"Double quote array expansions to avoid re-splitting elements."
|
||||
checkUnquotedDollarAt _ _ = return ()
|
||||
|
||||
prop_checkConcatenatedDollarAt1 = verify checkConcatenatedDollarAt "echo \"foo$@\""
|
||||
@@ -946,6 +992,7 @@ prop_checkArrayWithoutIndex1 = verifyTree checkArrayWithoutIndex "foo=(a b); ech
|
||||
prop_checkArrayWithoutIndex2 = verifyNotTree checkArrayWithoutIndex "foo='bar baz'; foo=($foo); echo ${foo[0]}"
|
||||
prop_checkArrayWithoutIndex3 = verifyTree checkArrayWithoutIndex "coproc foo while true; do echo cow; done; echo $foo"
|
||||
prop_checkArrayWithoutIndex4 = verifyTree checkArrayWithoutIndex "coproc tail -f log; echo $COPROC"
|
||||
prop_checkArrayWithoutIndex5 = verifyTree checkArrayWithoutIndex "a[0]=foo; echo $a"
|
||||
checkArrayWithoutIndex params _ =
|
||||
concat $ doVariableFlowAnalysis readF writeF Map.empty (variableFlow params)
|
||||
where
|
||||
@@ -961,20 +1008,43 @@ checkArrayWithoutIndex params _ =
|
||||
writeF _ t name (DataArray _) = do
|
||||
modify (Map.insert name t)
|
||||
return []
|
||||
writeF _ _ name _ = do
|
||||
modify (Map.delete name)
|
||||
writeF _ expr name _ = do
|
||||
if isIndexed expr
|
||||
then modify (Map.insert name expr)
|
||||
else modify (Map.delete name)
|
||||
return []
|
||||
|
||||
isIndexed expr =
|
||||
case expr of
|
||||
T_Assignment _ _ _ (Just _) _ -> True
|
||||
_ -> False
|
||||
|
||||
prop_checkStderrRedirect = verify checkStderrRedirect "test 2>&1 > cow"
|
||||
prop_checkStderrRedirect2 = verifyNot checkStderrRedirect "test > cow 2>&1"
|
||||
checkStderrRedirect _ (T_Redirecting _ [
|
||||
prop_checkStderrRedirect3 = verifyNot checkStderrRedirect "test 2>&1 > file | grep stderr"
|
||||
prop_checkStderrRedirect4 = verifyNot checkStderrRedirect "errors=$(test 2>&1 > file)"
|
||||
prop_checkStderrRedirect5 = verifyNot checkStderrRedirect "read < <(test 2>&1 > file)"
|
||||
prop_checkStderrRedirect6 = verify checkStderrRedirect "foo | bar 2>&1 > /dev/null"
|
||||
checkStderrRedirect params redir@(T_Redirecting _ [
|
||||
T_FdRedirect id "2" (T_IoFile _ (T_GREATAND _) (T_NormalWord _ [T_Literal _ "1"])),
|
||||
T_FdRedirect _ _ (T_IoFile _ op _)
|
||||
] _) = case op of
|
||||
T_Greater _ -> error
|
||||
T_DGREAT _ -> error
|
||||
_ -> return ()
|
||||
where error = err id 2069 "The order of the 2>&1 and the redirect matters. The 2>&1 has to be last."
|
||||
where
|
||||
usesOutput t =
|
||||
case t of
|
||||
(T_Pipeline _ _ list) -> length list > 1 && not (isParentOf (parentMap params) (last list) redir)
|
||||
(T_ProcSub {}) -> True
|
||||
(T_DollarExpansion {}) -> True
|
||||
(T_Backticked {}) -> True
|
||||
_ -> False
|
||||
isCaptured = any usesOutput $ getPath (parentMap params) redir
|
||||
|
||||
error = unless isCaptured $
|
||||
err id 2069 "The order of the 2>&1 and the redirect matters. The 2>&1 has to be last."
|
||||
|
||||
checkStderrRedirect _ _ = return ()
|
||||
|
||||
lt x = trace ("FAILURE " ++ show x) x
|
||||
@@ -1228,8 +1298,18 @@ checkConstantNoary _ _ = return ()
|
||||
|
||||
prop_checkBraceExpansionVars1 = verify checkBraceExpansionVars "echo {1..$n}"
|
||||
prop_checkBraceExpansionVars2 = verifyNot checkBraceExpansionVars "echo {1,3,$n}"
|
||||
checkBraceExpansionVars _ (T_BraceExpansion id s) | "..$" `isInfixOf` s =
|
||||
warn id 2051 "Bash doesn't support variables in brace range expansions."
|
||||
checkBraceExpansionVars _ (T_BraceExpansion id list) = mapM_ check list
|
||||
where
|
||||
check element =
|
||||
when ("..$" `isInfixOf` toString element) $
|
||||
warn id 2051 "Bash doesn't support variables in brace range expansions."
|
||||
literalExt t =
|
||||
case t of
|
||||
T_DollarBraced {} -> return "$"
|
||||
T_DollarExpansion {} -> return "$"
|
||||
T_DollarArithmetic {} -> return "$"
|
||||
otherwise -> return "-"
|
||||
toString t = fromJust $ getLiteralStringExt literalExt t
|
||||
checkBraceExpansionVars _ _ = return ()
|
||||
|
||||
prop_checkForDecimals = verify checkForDecimals "((3.14*c))"
|
||||
@@ -1242,8 +1322,10 @@ checkForDecimals _ _ = return ()
|
||||
|
||||
prop_checkDivBeforeMult = verify checkDivBeforeMult "echo $((c/n*100))"
|
||||
prop_checkDivBeforeMult2 = verifyNot checkDivBeforeMult "echo $((c*100/n))"
|
||||
checkDivBeforeMult _ (TA_Binary _ "*" (TA_Binary id "/" _ _) _) =
|
||||
info id 2017 "Increase precision by replacing a/b*c with a*c/b."
|
||||
prop_checkDivBeforeMult3 = verifyNot checkDivBeforeMult "echo $((c/10*10))"
|
||||
checkDivBeforeMult params (TA_Binary _ "*" (TA_Binary id "/" _ x) y)
|
||||
| not (hasFloatingPoint params) && x /= y =
|
||||
info id 2017 "Increase precision by replacing a/b*c with a*c/b."
|
||||
checkDivBeforeMult _ _ = return ()
|
||||
|
||||
prop_checkArithmeticDeref = verify checkArithmeticDeref "echo $((3+$foo))"
|
||||
@@ -1294,8 +1376,10 @@ prop_checkComparisonAgainstGlob = verify checkComparisonAgainstGlob "[[ $cow ==
|
||||
prop_checkComparisonAgainstGlob2 = verifyNot checkComparisonAgainstGlob "[[ $cow == \"$bar\" ]]"
|
||||
prop_checkComparisonAgainstGlob3 = verify checkComparisonAgainstGlob "[ $cow = *foo* ]"
|
||||
prop_checkComparisonAgainstGlob4 = verifyNot checkComparisonAgainstGlob "[ $cow = foo ]"
|
||||
checkComparisonAgainstGlob _ (TC_Binary _ DoubleBracket op _ (T_NormalWord id [T_DollarBraced _ _])) | op == "=" || op == "==" =
|
||||
warn id 2053 "Quote the rhs of = in [[ ]] to prevent glob interpretation."
|
||||
prop_checkComparisonAgainstGlob5 = verify checkComparisonAgainstGlob "[[ $cow != $bar ]]"
|
||||
checkComparisonAgainstGlob _ (TC_Binary _ DoubleBracket op _ (T_NormalWord id [T_DollarBraced _ _]))
|
||||
| op `elem` ["=", "==", "!="] =
|
||||
warn id 2053 $ "Quote the rhs of " ++ op ++ " in [[ ]] to prevent glob matching."
|
||||
checkComparisonAgainstGlob _ (TC_Binary _ SingleBracket op _ word)
|
||||
| (op == "=" || op == "==") && isGlob word =
|
||||
err (getId word) 2081 "[ .. ] can't match globs. Use [[ .. ]] or grep."
|
||||
@@ -1397,7 +1481,6 @@ isQuoteFreeNode strict tree t =
|
||||
T_DollarDoubleQuoted _ _ -> return True
|
||||
T_CaseExpression {} -> return True
|
||||
T_HereDoc {} -> return True
|
||||
T_HereString {} -> return True
|
||||
T_DollarBraced {} -> return True
|
||||
-- When non-strict, pragmatically assume it's desirable to split here
|
||||
T_ForIn {} -> return (not strict)
|
||||
@@ -1441,6 +1524,9 @@ getPath tree t = t :
|
||||
Nothing -> []
|
||||
Just parent -> getPath tree parent
|
||||
|
||||
isParentOf tree parent child =
|
||||
elem (getId parent) . map getId $ getPath tree child
|
||||
|
||||
parents params = getPath (parentMap params)
|
||||
|
||||
--- Command specific checks
|
||||
@@ -1489,6 +1575,16 @@ getUnquotedLiteral (T_NormalWord _ list) =
|
||||
str _ = Nothing
|
||||
getUnquotedLiteral _ = Nothing
|
||||
|
||||
-- Return a list of NormalWords resulting from brace expansion
|
||||
braceExpand (T_NormalWord id list) = take 1000 $ do
|
||||
items <- mapM part list
|
||||
return $ T_NormalWord id items
|
||||
where
|
||||
part (T_BraceExpansion id items) = do
|
||||
item <- items
|
||||
braceExpand item
|
||||
part x = return x
|
||||
|
||||
isCommand token str = isCommandMatch token (\cmd -> cmd == str || ('/' : str) `isSuffixOf` cmd)
|
||||
isUnqualifiedCommand token str = isCommandMatch token (== str)
|
||||
|
||||
@@ -1784,7 +1880,7 @@ prop_checkIndirectExpansion4 = verify checkIndirectExpansion "${var${n}_$((i%2))
|
||||
prop_checkIndirectExpansion5 = verifyNot checkIndirectExpansion "${bar}"
|
||||
checkIndirectExpansion _ (T_DollarBraced i (T_NormalWord _ contents)) =
|
||||
when (isIndirection contents) $
|
||||
err i 2082 "To expand via indirection, use name=\"foo$n\"; echo \"${!name}\"."
|
||||
err i 2082 "To expand via indirection, use arrays, ${!name} or (for sh only) eval."
|
||||
where
|
||||
isIndirection vars =
|
||||
let list = mapMaybe isIndirectionPart vars in
|
||||
@@ -1845,7 +1941,7 @@ prop_checkTildeInQuotes5 = verifyNot checkTildeInQuotes "echo '/~foo/cow'"
|
||||
prop_checkTildeInQuotes6 = verifyNot checkTildeInQuotes "awk '$0 ~ /foo/'"
|
||||
checkTildeInQuotes _ = check
|
||||
where
|
||||
verify id ('~':'/':_) = warn id 2088 "Note that ~ does not expand in quotes."
|
||||
verify id ('~':'/':_) = warn id 2088 "Tilde does not expand in quotes. Use $HOME."
|
||||
verify _ _ = return ()
|
||||
check (T_NormalWord _ (T_SingleQuoted id str:_)) =
|
||||
verify id str
|
||||
@@ -2017,15 +2113,15 @@ data StackData =
|
||||
-- (Base expression, specific position, var name, assigned values)
|
||||
| Assignment (Token, Token, String, DataType)
|
||||
| Reference (Token, Token, String)
|
||||
deriving (Show, Eq)
|
||||
deriving (Show)
|
||||
|
||||
data DataType = DataString DataSource | DataArray DataSource
|
||||
deriving (Show, Eq)
|
||||
deriving (Show)
|
||||
|
||||
data DataSource = SourceFrom [Token] | SourceExternal | SourceDeclaration
|
||||
deriving (Show, Eq)
|
||||
deriving (Show)
|
||||
|
||||
data VariableState = Dead Token String | Alive deriving (Show, Eq)
|
||||
data VariableState = Dead Token String | Alive deriving (Show)
|
||||
|
||||
dataTypeFrom defaultType v = (case v of T_Array {} -> DataArray; _ -> defaultType) $ SourceFrom [v]
|
||||
|
||||
@@ -2111,7 +2207,7 @@ getReferencedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Litera
|
||||
getReference t@(T_Assignment _ _ name _ value) = [(t, t, name)]
|
||||
getReference t@(T_NormalWord _ [T_Literal _ name]) | not ("-" `isPrefixOf` name) = [(t, t, name)]
|
||||
getReference _ = []
|
||||
flags = getFlags base
|
||||
flags = map snd $ getAllFlags base
|
||||
|
||||
getReferencedVariableCommand _ = []
|
||||
|
||||
@@ -2131,7 +2227,7 @@ getModifiedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Literal
|
||||
"export" ->
|
||||
if "f" `elem` flags then [] else concatMap getModifierParamString rest
|
||||
|
||||
"declare" -> declaredVars
|
||||
"declare" -> if any (`elem` flags) ["F", "f", "p"] then [] else declaredVars
|
||||
"typeset" -> declaredVars
|
||||
|
||||
"local" -> concatMap getModifierParamString rest
|
||||
@@ -2142,9 +2238,12 @@ getModifiedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Literal
|
||||
|
||||
"printf" -> maybeToList $ getPrintfVariable rest
|
||||
|
||||
"mapfile" -> maybeToList $ getMapfileArray base rest
|
||||
"readarray" -> maybeToList $ getMapfileArray base rest
|
||||
|
||||
_ -> []
|
||||
where
|
||||
flags = getFlags base
|
||||
flags = map snd $ getAllFlags base
|
||||
stripEquals s = let rest = dropWhile (/= '=') s in
|
||||
if rest == "" then "" else tail rest
|
||||
stripEqualsFrom (T_NormalWord id1 (T_Literal id2 s:rs)) =
|
||||
@@ -2193,6 +2292,15 @@ getModifiedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Literal
|
||||
f (_:rest) = f rest
|
||||
f [] = fail "not found"
|
||||
|
||||
-- mapfile has some curious syntax allowing flags plus 0..n variable names
|
||||
-- where only the first non-option one is used if any. Here we cheat and
|
||||
-- just get the last one, if it's a variable name.
|
||||
getMapfileArray base arguments = do
|
||||
lastArg <- listToMaybe (reverse arguments)
|
||||
name <- getLiteralString lastArg
|
||||
guard $ isVariableName name
|
||||
return (base, lastArg, name, DataArray $ SourceExternal)
|
||||
|
||||
getModifiedVariableCommand _ = []
|
||||
|
||||
prop_getBracedReference1 = getBracedReference "foo" == "foo"
|
||||
@@ -2220,10 +2328,11 @@ getBracedReference s = fromMaybe s $
|
||||
getSpecial _ = fail "empty"
|
||||
|
||||
getIndexReferences s = fromMaybe [] $ do
|
||||
(_, index, _, _) <- matchRegexAll re s
|
||||
return $ matchAll variableNameRegex index
|
||||
match <- matchRegex re s
|
||||
index <- match !!! 0
|
||||
return $ matchAllStrings variableNameRegex index
|
||||
where
|
||||
re = mkRegex "\\[.*\\]"
|
||||
re = mkRegex "(\\[.*\\])"
|
||||
|
||||
getReferencedVariables t =
|
||||
case t of
|
||||
@@ -2263,7 +2372,7 @@ getReferencedVariables t =
|
||||
prop_getVariablesFromLiteral1 =
|
||||
getVariablesFromLiteral "$foo${bar//a/b}$BAZ" == ["foo", "bar", "BAZ"]
|
||||
getVariablesFromLiteral string =
|
||||
map (!! 0) $ getAllMatches variableRegex string
|
||||
map (!! 0) $ matchAllSubgroups variableRegex string
|
||||
where
|
||||
variableRegex = mkRegex "\\$\\{?([A-Za-z0-9_]+)"
|
||||
|
||||
@@ -2355,8 +2464,9 @@ prop_checkSpacefulness20= verifyNotTree checkSpacefulness "n+='foo bar'"
|
||||
prop_checkSpacefulness21= verifyNotTree checkSpacefulness "select foo in $bar; do true; done"
|
||||
prop_checkSpacefulness22= verifyNotTree checkSpacefulness "echo $\"$1\""
|
||||
prop_checkSpacefulness23= verifyNotTree checkSpacefulness "a=(1); echo ${a[@]}"
|
||||
prop_checkSpacefulness24= verifyNotTree checkSpacefulness "a='a b'; cat <<< $a"
|
||||
prop_checkSpacefulness24= verifyTree checkSpacefulness "a='a b'; cat <<< $a"
|
||||
prop_checkSpacefulness25= verifyTree checkSpacefulness "a='s/[0-9]//g'; sed $a"
|
||||
prop_checkSpacefulness26= verifyTree checkSpacefulness "a='foo bar'; echo {1,2,$a}"
|
||||
|
||||
checkSpacefulness params t =
|
||||
doVariableFlowAnalysis readF writeF (Map.fromList defaults) (variableFlow params)
|
||||
@@ -2545,6 +2655,9 @@ prop_checkUnused20= verifyNotTree checkUnusedAssignments "a=1; PS1='$a'"
|
||||
prop_checkUnused21= verifyNotTree checkUnusedAssignments "a=1; trap 'echo $a' INT"
|
||||
prop_checkUnused22= verifyNotTree checkUnusedAssignments "a=1; [ -v a ]"
|
||||
prop_checkUnused23= verifyNotTree checkUnusedAssignments "a=1; [ -R a ]"
|
||||
prop_checkUnused24= verifyNotTree checkUnusedAssignments "mapfile -C a b; echo ${b[@]}"
|
||||
prop_checkUnused25= verifyNotTree checkUnusedAssignments "readarray foo; echo ${foo[@]}"
|
||||
prop_checkUnused26= verifyNotTree checkUnusedAssignments "declare -F foo"
|
||||
checkUnusedAssignments params t = execWriter (mapM_ warnFor unused)
|
||||
where
|
||||
flow = variableFlow params
|
||||
@@ -2856,11 +2969,15 @@ prop_checkCatastrophicRm5 = verifyNot checkCatastrophicRm "rm -r /home/${USER:-t
|
||||
prop_checkCatastrophicRm6 = verify checkCatastrophicRm "rm --recursive /etc/*$config*"
|
||||
prop_checkCatastrophicRm8 = verify checkCatastrophicRm "rm -rf /home"
|
||||
prop_checkCatastrophicRm9 = verifyNot checkCatastrophicRm "rm -rf -- /home"
|
||||
prop_checkCatastrophicRm10= verifyNot checkCatastrophicRm "rm -r \"${DIR}\"/{.gitignore,.gitattributes,ci}"
|
||||
prop_checkCatastrophicRm11= verify checkCatastrophicRm "rm -r /{bin,sbin}/$exec"
|
||||
prop_checkCatastrophicRm12= verify checkCatastrophicRm "rm -r /{{usr,},{bin,sbin}}/$exec"
|
||||
prop_checkCatastrophicRm13= verifyNot checkCatastrophicRm "rm -r /{{a,b},{c,d}}/$exec"
|
||||
prop_checkCatastrophicRmA = verify checkCatastrophicRm "rm -rf /usr /lib/nvidia-current/xorg/xorg"
|
||||
prop_checkCatastrophicRmB = verify checkCatastrophicRm "rm -rf \"$STEAMROOT/\"*"
|
||||
checkCatastrophicRm params t@(T_SimpleCommand id _ tokens) | t `isCommand` "rm" =
|
||||
when (any isRecursiveFlag simpleArgs) $
|
||||
mapM_ checkWord tokens
|
||||
mapM_ (mapM_ checkWord . braceExpand) tokens
|
||||
where
|
||||
simpleArgs = deadSimple t
|
||||
|
||||
@@ -2949,6 +3066,7 @@ prop_checkUnpassedInFunctions7 = verifyTree checkUnpassedInFunctions "foo() { ec
|
||||
prop_checkUnpassedInFunctions8 = verifyNotTree checkUnpassedInFunctions "foo() { echo $((1)); }; foo;"
|
||||
prop_checkUnpassedInFunctions9 = verifyNotTree checkUnpassedInFunctions "foo() { echo $(($b)); }; foo;"
|
||||
prop_checkUnpassedInFunctions10= verifyNotTree checkUnpassedInFunctions "foo() { echo $!; }; foo;"
|
||||
prop_checkUnpassedInFunctions11= verifyNotTree checkUnpassedInFunctions "foo() { bar() { echo $1; }; bar baz; }; foo;"
|
||||
checkUnpassedInFunctions params root =
|
||||
execWriter $ mapM_ warnForGroup referenceGroups
|
||||
where
|
||||
@@ -2960,7 +3078,7 @@ checkUnpassedInFunctions params root =
|
||||
findFunction t@(T_Function id _ _ name body) =
|
||||
let flow = getVariableFlow (shellType params) (parentMap params) body
|
||||
in
|
||||
if any isPositionalReference flow && not (any isPositionalAssignment flow)
|
||||
if any (isPositionalReference t) flow && not (any isPositionalAssignment flow)
|
||||
then return t
|
||||
else Nothing
|
||||
findFunction _ = Nothing
|
||||
@@ -2969,11 +3087,15 @@ checkUnpassedInFunctions params root =
|
||||
case x of
|
||||
Assignment (_, _, str, _) -> isPositional str
|
||||
_ -> False
|
||||
isPositionalReference x =
|
||||
isPositionalReference function x =
|
||||
case x of
|
||||
Reference (_, _, str) -> isPositional str
|
||||
Reference (_, t, str) -> isPositional str && t `isDirectChildOf` function
|
||||
_ -> False
|
||||
|
||||
isDirectChildOf child parent = fromMaybe False $ do
|
||||
function <- find (\x -> case x of T_Function {} -> True; _ -> False) $ getPath (parentMap params) child
|
||||
return $ getId parent == getId function
|
||||
|
||||
referenceList :: [(String, Bool, Token)]
|
||||
referenceList = execWriter $
|
||||
doAnalysis (fromMaybe (return ()) . checkCommand) root
|
||||
@@ -3107,9 +3229,7 @@ checkMultipleAppends params t =
|
||||
mapM_ checkList $ getCommandSequences t
|
||||
where
|
||||
checkList list =
|
||||
mapM_ checkGroup groups
|
||||
where
|
||||
groups = groupWith (liftM fst) $ map getTarget list
|
||||
mapM_ checkGroup (groupWith (liftM fst) $ map getTarget list)
|
||||
checkGroup (f:_:_:_) | isJust f =
|
||||
style (snd $ fromJust f) 2129
|
||||
"Consider using { cmd1; cmd2; } >> file instead of individual redirects."
|
||||
@@ -3256,7 +3376,7 @@ prop_checkMaskedReturns5 = verifyNot checkMaskedReturns "f() { local -r a=$(fals
|
||||
checkMaskedReturns _ t@(T_SimpleCommand id _ (cmd:rest)) = potentially $ do
|
||||
name <- getCommandName t
|
||||
guard $ name `elem` ["declare", "export"]
|
||||
|| name == "local" && "r" `notElem` getFlags t
|
||||
|| name == "local" && "r" `notElem` (map snd $ getAllFlags t)
|
||||
return $ mapM_ checkArgs rest
|
||||
where
|
||||
checkArgs (T_Assignment id _ _ _ word) | any hasReturn $ getWordParts word =
|
||||
@@ -3269,6 +3389,30 @@ checkMaskedReturns _ t@(T_SimpleCommand id _ (cmd:rest)) = potentially $ do
|
||||
_ -> False
|
||||
checkMaskedReturns _ _ = return ()
|
||||
|
||||
prop_checkInjectableFindSh1 = verify checkInjectableFindSh "find . -exec sh -c 'echo {}' \\;"
|
||||
prop_checkInjectableFindSh2 = verify checkInjectableFindSh "find . -execdir bash -c 'rm \"{}\"' ';'"
|
||||
prop_checkInjectableFindSh3 = verifyNot checkInjectableFindSh "find . -exec sh -c 'rm \"$@\"' _ {} \\;"
|
||||
checkInjectableFindSh _ = checkCommand "find" (const check)
|
||||
where
|
||||
check args = do
|
||||
let idStrings = map (\x -> (getId x, onlyLiteralString x)) args
|
||||
match pattern idStrings
|
||||
|
||||
match _ [] = return ()
|
||||
match [] (next:_) = action next
|
||||
match (p:tests) ((id, arg):args) = do
|
||||
when (p arg) $ match tests args
|
||||
match (p:tests) args
|
||||
|
||||
pattern = [
|
||||
(`elem` ["-exec", "-execdir"]),
|
||||
(`elem` ["sh", "bash", "ksh"]),
|
||||
(== "-c")
|
||||
]
|
||||
action (id, arg) =
|
||||
when ("{}" `isInfixOf` arg) $
|
||||
warn id 2156 "Injecting filenames is fragile and insecure. Use parameters."
|
||||
|
||||
|
||||
return []
|
||||
runTests = $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])
|
||||
|
@@ -3,19 +3,19 @@
|
||||
http://www.vidarholen.net/contents/shellcheck
|
||||
|
||||
ShellCheck is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ShellCheck is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
yOU should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
-}
|
||||
{-# LANGUAGE NoMonomorphismRestriction, TemplateHaskell #-}
|
||||
{-# LANGUAGE NoMonomorphismRestriction, TemplateHaskell, FlexibleContexts #-}
|
||||
module ShellCheck.Parser (Note(..), Severity(..), parseShell, ParseResult(..), ParseNote(..), sortNotes, noteToParseNote, runTests, readScript) where
|
||||
|
||||
import ShellCheck.AST
|
||||
@@ -237,6 +237,12 @@ attempting rest branch =
|
||||
orFail parser errorAction =
|
||||
try parser <|> (errorAction >>= fail)
|
||||
|
||||
-- Construct a node with a parser, e.g. T_Literal `withParser` (readGenericLiteral ",")
|
||||
withParser node parser = do
|
||||
id <- getNextId
|
||||
contents <- parser
|
||||
return $ node id contents
|
||||
|
||||
wasIncluded p = option False (p >> return True)
|
||||
|
||||
acceptButWarn parser level code note =
|
||||
@@ -765,14 +771,14 @@ readDollarBracedLiteral = do
|
||||
|
||||
prop_readProcSub1 = isOk readProcSub "<(echo test | wc -l)"
|
||||
prop_readProcSub2 = isOk readProcSub "<( if true; then true; fi )"
|
||||
prop_readProcSub3 = isOk readProcSub "<( # nothing here \n)"
|
||||
readProcSub = called "process substitution" $ do
|
||||
id <- getNextId
|
||||
dir <- try $ do
|
||||
x <- oneOf "<>"
|
||||
char '('
|
||||
return [x]
|
||||
allspacing
|
||||
list <- readCompoundList
|
||||
list <- readCompoundListOrEmpty
|
||||
allspacing
|
||||
char ')'
|
||||
return $ T_ProcSub id dir list
|
||||
@@ -837,19 +843,23 @@ readBackTicked = called "backtick expansion" $ do
|
||||
suggestForgotClosingQuote startPos endPos "backtick expansion"
|
||||
|
||||
-- Result positions may be off due to escapes
|
||||
result <- subParse subStart readTermOrNone (unEscape subString)
|
||||
result <- subParse subStart subParser (unEscape subString)
|
||||
return $ T_Backticked id result
|
||||
where
|
||||
unEscape [] = []
|
||||
unEscape ('\\':x:rest) | x `elem` "$`\\" = x : unEscape rest
|
||||
unEscape ('\\':'\n':rest) = unEscape rest
|
||||
unEscape (c:rest) = c : unEscape rest
|
||||
subParser = do
|
||||
cmds <- readCompoundListOrEmpty
|
||||
verifyEof
|
||||
return cmds
|
||||
backtick =
|
||||
disregard (char '`') <|> do
|
||||
pos <- getPosition
|
||||
char '´'
|
||||
parseProblemAt pos ErrorC 1077
|
||||
"For command expansion, the tick should slant left (` vs ´)."
|
||||
"For command expansion, the tick should slant left (` vs ´). Use $(..) instead."
|
||||
|
||||
subParse pos parser input = do
|
||||
lastPosition <- getPosition
|
||||
@@ -1045,16 +1055,29 @@ readGenericEscaped = do
|
||||
|
||||
prop_readBraced = isOk readBraced "{1..4}"
|
||||
prop_readBraced2 = isOk readBraced "{foo,bar,\"baz lol\"}"
|
||||
readBraced = try $ do
|
||||
let strip (T_Literal _ s) = return ("\"" ++ s ++ "\"")
|
||||
id <- getNextId
|
||||
char '{'
|
||||
str <- many1 ((readDoubleQuotedLiteral >>= strip) <|> readGenericLiteral1 (oneOf "}\"" <|> whitespace))
|
||||
char '}'
|
||||
let result = concat str
|
||||
unless (',' `elem` result || ".." `isInfixOf` result) $
|
||||
fail "Not a brace expression"
|
||||
return $ T_BraceExpansion id result
|
||||
prop_readBraced3 = isOk readBraced "{1,\\},2}"
|
||||
prop_readBraced4 = isOk readBraced "{1,{2,3}}"
|
||||
prop_readBraced5 = isOk readBraced "{JP{,E}G,jp{,e}g}"
|
||||
prop_readBraced6 = isOk readBraced "{foo,bar,$((${var}))}"
|
||||
readBraced = try braceExpansion
|
||||
where
|
||||
braceExpansion =
|
||||
T_BraceExpansion `withParser` do
|
||||
char '{'
|
||||
elements <- bracedElement `sepBy1` char ','
|
||||
char '}'
|
||||
return elements
|
||||
bracedElement =
|
||||
T_NormalWord `withParser` do
|
||||
many $ choice [
|
||||
braceExpansion,
|
||||
readDollarExpression,
|
||||
readSingleQuoted,
|
||||
readDoubleQuoted,
|
||||
braceLiteral
|
||||
]
|
||||
braceLiteral =
|
||||
T_Literal `withParser` readGenericLiteral1 (oneOf "{}\"$'," <|> whitespace)
|
||||
|
||||
readNormalDollar = readDollarExpression <|> readDollarDoubleQuote <|> readDollarSingleQuote <|> readDollarLonely
|
||||
readDoubleQuotedDollar = readDollarExpression <|> readDollarLonely
|
||||
@@ -1078,7 +1101,6 @@ readDollarDoubleQuote = do
|
||||
doubleQuote <?> "end of translated double quoted string"
|
||||
return $ T_DollarDoubleQuoted id x
|
||||
|
||||
|
||||
prop_readDollarArithmetic = isOk readDollarArithmetic "$(( 3 * 4 +5))"
|
||||
prop_readDollarArithmetic2 = isOk readDollarArithmetic "$(((3*4)+(1*2+(3-1))))"
|
||||
readDollarArithmetic = called "$((..)) expression" $ do
|
||||
@@ -1114,11 +1136,13 @@ readDollarBraced = called "parameter expansion" $ do
|
||||
char '}'
|
||||
return $ T_DollarBraced id word
|
||||
|
||||
prop_readDollarExpansion = isOk readDollarExpansion "$(echo foo; ls\n)"
|
||||
prop_readDollarExpansion1= isOk readDollarExpansion "$(echo foo; ls\n)"
|
||||
prop_readDollarExpansion2= isOk readDollarExpansion "$( )"
|
||||
prop_readDollarExpansion3= isOk readDollarExpansion "$( command \n#comment \n)"
|
||||
readDollarExpansion = called "command expansion" $ do
|
||||
id <- getNextId
|
||||
try (string "$(")
|
||||
cmds <- readCompoundList
|
||||
cmds <- readCompoundListOrEmpty
|
||||
char ')' <?> "end of $(..) expression"
|
||||
return $ T_DollarExpansion id cmds
|
||||
|
||||
@@ -1827,6 +1851,9 @@ readCompoundCommand = do
|
||||
|
||||
|
||||
readCompoundList = readTerm
|
||||
readCompoundListOrEmpty = do
|
||||
allspacing
|
||||
readTerm <|> return []
|
||||
|
||||
readCmdPrefix = many1 (readIoRedirect <|> readAssignmentWord)
|
||||
readCmdSuffix = many1 (readIoRedirect <|> readCmdWord)
|
||||
@@ -2030,10 +2057,25 @@ readShebang = do
|
||||
parseProblemAt pos ErrorC 1084
|
||||
"Use #!, not !#, for the shebang."
|
||||
|
||||
verifyEof = eof <|> choice [
|
||||
ifParsable g_Lparen $
|
||||
parseProblem ErrorC 1088 "Parsing stopped here. Invalid use of parentheses?",
|
||||
|
||||
ifParsable readKeyword $
|
||||
parseProblem ErrorC 1089 "Parsing stopped here. Is this keyword correctly matched up?",
|
||||
|
||||
parseProblem ErrorC 1070 "Parsing stopped here. Mismatched keywords or invalid parentheses?"
|
||||
]
|
||||
where
|
||||
ifParsable p action = do
|
||||
try (lookAhead p)
|
||||
action
|
||||
|
||||
prop_readScript1 = isOk readScript "#!/bin/bash\necho hello world\n"
|
||||
prop_readScript2 = isWarning readScript "#!/bin/bash\r\necho hello world\n"
|
||||
prop_readScript3 = isWarning readScript "#!/bin/bash\necho hello\xA0world"
|
||||
prop_readScript4 = isWarning readScript "#!/usr/bin/perl\nfoo=("
|
||||
prop_readScript5 = isOk readScript "#!/bin/bash\n#This is an empty script\n\n"
|
||||
readScript = do
|
||||
id <- getNextId
|
||||
pos <- getPosition
|
||||
@@ -2044,19 +2086,13 @@ readScript = do
|
||||
sb <- option "" readShebang
|
||||
verifyShell pos (getShell sb)
|
||||
if isValidShell (getShell sb) /= Just False
|
||||
then
|
||||
do {
|
||||
allspacing;
|
||||
commands <- readTerm;
|
||||
eof <|> parseProblem ErrorC 1070 "Parsing stopped here because of parsing errors.";
|
||||
return $ T_Script id sb commands;
|
||||
} <|> do {
|
||||
parseProblem WarningC 1014 "Couldn't read any commands.";
|
||||
then do
|
||||
commands <- readCompoundListOrEmpty
|
||||
verifyEof
|
||||
return $ T_Script id sb commands
|
||||
else do
|
||||
many anyChar
|
||||
return $ T_Script id sb []
|
||||
}
|
||||
else do
|
||||
many anyChar
|
||||
return $ T_Script id sb [];
|
||||
|
||||
where
|
||||
basename s = reverse . takeWhile (/= '/') . reverse $ s
|
||||
@@ -2095,6 +2131,7 @@ readScript = do
|
||||
badShells = [
|
||||
"awk",
|
||||
"csh",
|
||||
"expect",
|
||||
"perl",
|
||||
"python",
|
||||
"ruby",
|
||||
|
71
ShellCheck/Regex.hs
Normal file
71
ShellCheck/Regex.hs
Normal file
@@ -0,0 +1,71 @@
|
||||
{-
|
||||
This file is part of ShellCheck.
|
||||
http://www.vidarholen.net/contents/shellcheck
|
||||
|
||||
ShellCheck is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ShellCheck is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
-}
|
||||
{-# LANGUAGE FlexibleContexts #-}
|
||||
|
||||
-- Basically Text.Regex based on regex-tdfa instead of the buggy regex-posix.
|
||||
module ShellCheck.Regex where
|
||||
|
||||
import Data.List
|
||||
import Data.Maybe
|
||||
import Control.Monad
|
||||
import Text.Regex.TDFA
|
||||
|
||||
-- Precompile the regex
|
||||
mkRegex :: String -> Regex
|
||||
mkRegex str =
|
||||
let make :: RegexMaker Regex CompOption ExecOption String => String -> Regex
|
||||
make = makeRegex
|
||||
in
|
||||
make str
|
||||
|
||||
-- Does the regex match?
|
||||
matches :: String -> Regex -> Bool
|
||||
matches = flip match
|
||||
|
||||
-- Get all subgroups of the first match
|
||||
matchRegex :: Regex -> String -> Maybe [String]
|
||||
matchRegex re str = do
|
||||
(_, _, _, groups) <- matchM re str :: Maybe (String,String,String,[String])
|
||||
return groups
|
||||
|
||||
-- Get all full matches
|
||||
matchAllStrings :: Regex -> String -> [String]
|
||||
matchAllStrings re = unfoldr f
|
||||
where
|
||||
f :: String -> Maybe (String, String)
|
||||
f str = do
|
||||
(_, match, rest, _) <- matchM re str :: Maybe (String, String, String, [String])
|
||||
return (match, rest)
|
||||
|
||||
-- Get all subgroups from all matches
|
||||
matchAllSubgroups :: Regex -> String -> [[String]]
|
||||
matchAllSubgroups re = unfoldr f
|
||||
where
|
||||
f :: String -> Maybe ([String], String)
|
||||
f str = do
|
||||
(_, _, rest, groups) <- matchM re str :: Maybe (String, String, String, [String])
|
||||
return (groups, rest)
|
||||
|
||||
-- Replace regex in input with string
|
||||
subRegex :: Regex -> String -> String -> String
|
||||
subRegex re input replacement = f input
|
||||
where
|
||||
f str = fromMaybe str $ do
|
||||
(before, match, after) <- matchM re str :: Maybe (String, String, String)
|
||||
when (null match) $ error ("Internal error: substituted empty in " ++ str)
|
||||
return $ before ++ replacement ++ f after
|
@@ -3,16 +3,16 @@
|
||||
http://www.vidarholen.net/contents/shellcheck
|
||||
|
||||
ShellCheck is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ShellCheck is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
-}
|
||||
{-# LANGUAGE TemplateHaskell #-}
|
||||
|
@@ -3,16 +3,16 @@
|
||||
http://www.vidarholen.net/contents/shellcheck
|
||||
|
||||
ShellCheck is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ShellCheck is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
-}
|
||||
import Control.Exception
|
||||
@@ -21,6 +21,7 @@ import Control.Monad.Trans
|
||||
import Control.Monad.Trans.Error
|
||||
import Control.Monad.Trans.List
|
||||
import Data.Char
|
||||
import Data.List
|
||||
import Data.Maybe
|
||||
import Data.Monoid
|
||||
import GHC.Exts
|
||||
@@ -34,6 +35,7 @@ import System.Console.GetOpt
|
||||
import System.Directory
|
||||
import System.Environment
|
||||
import System.Exit
|
||||
import System.Info
|
||||
import System.IO
|
||||
import Text.JSON
|
||||
import qualified Data.Map as Map
|
||||
@@ -154,7 +156,8 @@ forTty options files = do
|
||||
|
||||
getColorFunc = do
|
||||
term <- hIsTerminalDevice stdout
|
||||
return $ if term then colorComment else const id
|
||||
let windows = "mingw" `isPrefixOf` os
|
||||
return $ if term && not windows then colorComment else const id
|
||||
|
||||
forJson :: AnalysisOptions -> [FilePath] -> IO Status
|
||||
forJson options files = catchExceptions $ do
|
||||
@@ -350,5 +353,5 @@ verifyFiles files =
|
||||
printVersion = do
|
||||
putStrLn "ShellCheck - shell script analysis tool"
|
||||
putStrLn $ "version: " ++ shellcheckVersion
|
||||
putStrLn "license: GNU Affero General Public License, version 3"
|
||||
putStrLn "license: GNU General Public License, version 3"
|
||||
putStrLn "website: http://www.shellcheck.net"
|
||||
|
Reference in New Issue
Block a user