57 Commits

Author SHA1 Message Date
Vidar Holen
1ff67a61b4 Stable version 0.3.8. Now GPLv3!
This release is dedicated to Richard Stallman.
Happy hacking, and may we all live in a free GNUtopia!
2015-06-20 10:17:48 -07:00
Vidar Holen
349dfdab35 Relicense from AGPL v3 to GPL v3. 2015-06-20 09:52:07 -07:00
Vidar Holen
1ab29ddb39 Made SC2082 indirection message more sh friendly. 2015-06-14 17:20:52 -07:00
Vidar Holen
09b7788412 Don't consider declare -Ffp assignments. 2015-06-14 16:51:18 -07:00
Vidar Holen
ef2135f3aa Don't warn about unpassed parameters if used in child functions. 2015-06-14 16:14:05 -07:00
Vidar Holen
d10c3b2709 Don't warn about 2>&1 > foo if piping or capturing. 2015-06-14 15:39:44 -07:00
Vidar Holen
ca37794b7c Allow empty scripts, $()s and <()s. Also improves related error messages. 2015-06-14 14:30:11 -07:00
Vidar Holen
8b8b48ef55 Make quoted tilde message suggest $HOME instead. 2015-06-14 10:24:40 -07:00
Vidar Holen
aea0310a07 Added install instructions for native Windows 2015-06-14 10:16:32 -07:00
Vidar Holen
7fff088ce9 Don't output ansi escape codes on Windows 2015-06-07 18:08:23 -07:00
Vidar Holen
65ab8c8ecb Account for brace expansion in SC2115 (catastrophic rm). 2015-06-07 13:02:49 -07:00
Vidar Holen
3a041954d1 Don't warn about a&&b||c if c == printf 2015-05-24 12:41:54 -07:00
Vidar Holen
828378cdff Warn about injecting filenames into sh -c strings with find. 2015-05-23 13:03:07 -07:00
Vidar Holen
509cda4dcf Count mapfile/readarray as variable assignment 2015-05-10 13:13:42 -07:00
Vidar Holen
6076f0b1da Parse variables and subexpressions in brace expansions 2015-05-10 12:49:50 -07:00
Vidar Holen
1d26c280d6 Warn when failing to quote here strings. 2015-05-09 12:12:11 -07:00
Vidar Holen
c785d43e34 Fixed unquoted $@ warning message. 2015-05-09 12:07:33 -07:00
Vidar Holen
4c3e731445 Don't warn about a/b*c for ksh or when b == c 2015-05-09 11:48:08 -07:00
Vidar Holen
3940462da3 Warn about glob matching in [[ ]] for != as well as ==. 2015-05-09 11:34:34 -07:00
Vidar Holen
bb7ef5834b Warn on unindexed references for implicit arrays. 2015-04-21 19:19:15 -07:00
Vidar Holen
2f7bd556e8 Stable version 0.3.7
This is purely a bugfix bump that compiles on GHC 7.10
and uses a regex lib that doesn't crash on OS X.
2015-04-16 08:13:49 -07:00
Vidar Holen
081751c1b5 Fixed case sensitivity in 'trap' bashism test 2015-04-05 10:33:54 -07:00
Vidar Holen
cc86aab3f1 Added multiple new checks from checkbashisms 2015-04-05 10:25:00 -07:00
Vidar Holen
9f1f00cdd1 Switch from regex-compat to regex-tdfa 2015-04-04 16:26:28 -07:00
Vidar Holen
93debd3556 Add expect to list of known non-shells 2015-04-02 19:22:47 -07:00
Vidar Holen
47b971c582 Declared FlexibleContexts for GHC 7.10 2015-03-31 21:59:03 -07:00
Vidar Holen
f25ae90746 Stable version 0.3.6
This release is dedicated to Maxis: shaping the 90s
for yours truly with SimCity, SimCopter and El-Fish.
2015-03-28 12:27:39 -07:00
Vidar Holen
3daa47c0f2 Remove zsh specific variables. 2015-03-28 11:55:25 -07:00
Vidar Holen
ed56a837c3 Killed Zsh support 2015-03-20 10:03:56 -07:00
Vidar Holen
80cf5d9852 Include [] as glob chars to warn about quoting for 2015-03-19 18:29:47 -07:00
Vidar Holen
8e554ae3d4 Fix SC2143 to not warn about pgrep and other quasi-greps. 2015-03-12 08:31:49 -07:00
Vidar Holen
0a80188363 Fix parsing of ((a?b:c)) 2015-03-08 18:11:23 -07:00
Vidar Holen
0e1a64b6ba Warn about export/declare/local masking return values. 2015-03-08 14:17:43 -07:00
Vidar Holen
0a2cf208c8 Fixed quoted ~ warning to only trigger for ~/ 2015-03-07 23:48:01 -08:00
Vidar Holen
dcc10bbdf6 Fixed accidentally ignored undef warning for ${#foo} 2015-03-07 23:01:34 -08:00
Vidar Holen
2c2e41952f Improved missing shebang message. 2015-03-07 22:37:49 -08:00
Vidar Holen
0d74140650 Multiple wrong assignment warning fixes 2015-03-07 20:15:04 -08:00
Vidar Holen
955ad60823 Fixed parser errors not being excluded by -e 2015-03-01 13:44:57 -08:00
Vidar Holen
2573332d77 Fixed edge cases for braced reference extractor. 2015-03-01 13:44:18 -08:00
Vidar Holen
00c470f323 Improve SC2143 error message 2015-03-01 12:20:37 -08:00
Vidar Holen
63188282e9 Add warning for vars that are referenced but not assigned. 2015-02-28 18:43:22 -08:00
Vidar Holen
61b4b65184 Warn about obviously bad return values, like -1 or "foo" 2015-02-14 12:03:38 -08:00
Vidar Holen
39b2bf4378 Don't warn about modifying $@ or $IFS in a subshell 2015-02-14 10:43:49 -08:00
Vidar Holen
2fe117728d Count [[ -v foo ]] (and -R) as a variable reference 2015-02-13 20:10:18 -08:00
Vidar Holen
cde3ba8769 Add filename to JSON output. 2015-02-13 19:32:20 -08:00
Vidar Holen
33c78b7c95 Track variables created through coproc. 2015-01-27 10:11:17 -08:00
Vidar Holen
a485482979 Add support for coproc 2015-01-26 22:21:04 -08:00
Vidar Holen
895d83afc5 s/deprecated/legacy/ for backtick warnings. 2015-01-25 12:27:49 -08:00
Vidar Holen
39bc011757 Rewrote catastrophic rm detection, now simpler and more robust. 2015-01-25 12:18:06 -08:00
koalaman
fe0a398239 Merge pull request #295 from orlitzky/sdist-manpage
Add a pre-sdist hook to compile the man page (Github issue #247).
2015-01-24 13:10:09 -08:00
Michael Orlitzky
1be0f1ea75 Add a pre-sdist hook to compile the man page (Github issue #247).
This replaces the default preSDist hook in Setup.hs with our own. The
only thing the new hook does is compile the man page using callCommand
from System.Process.

If Pandoc fails, the entire sdist process will fail, since
Extra-Source-Files in the cabal file now lists the man page.

This is preferable to a build hook, because Pandoc pulls in a huge
number of dependencies. It's better to build the man page once and
ship it than to require every user to build and install pandoc before
he can build ShellCheck.

This creates another TODO item: an install hook can now be used to
install the man page along with the rest of ShellCheck. But beware,
the "man path" can vary from system to system.
2015-01-24 12:15:36 -05:00
Vidar Holen
c9aa133282 Fix pattern matching error in z=$(echo) 2015-01-02 18:06:10 -08:00
Vidar Holen
7b70500d41 Suppress SC2140 if the user just prefers quoting single items at a time. 2014-12-23 19:47:55 -08:00
Vidar Holen
8bed447411 Warn when trying to find -exec "shell command" \; 2014-11-22 12:16:30 -08:00
Vidar Holen
22710bf4d8 Fixed $! counting as a positional parameter reference. 2014-11-22 11:21:54 -08:00
Vidar Holen
a354685ab1 Warn about redirecting to globs in sh 2014-11-22 10:50:38 -08:00
Vidar Holen
a8ff7a02fd Fix $10 warning triggering for $?!, and also warn about $arr[index]. 2014-11-22 10:09:19 -08:00
13 changed files with 1093 additions and 456 deletions

141
LICENSE
View File

@@ -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>.

View File

@@ -2,8 +2,8 @@
http://www.shellcheck.net
Copyright 2012-2014, Vidar 'koala_man' Holen
Licensed under the GNU Affero General Public License, v3
Copyright 2012-2015, Vidar 'koala_man' Holen
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:

View File

@@ -1,2 +1,43 @@
import Distribution.Simple
main = defaultMain
import Distribution.PackageDescription (
HookedBuildInfo,
emptyHookedBuildInfo )
import Distribution.Simple (
Args,
UserHooks ( preSDist ),
defaultMainWithHooks,
simpleUserHooks )
import Distribution.Simple.Setup ( SDistFlags )
-- | This requires the process package from,
--
-- https://hackage.haskell.org/package/process
--
import System.Process ( callCommand )
-- | This will use almost the default implementation, except we switch
-- out the default pre-sdist hook with our own, 'myPreSDist'.
--
main = defaultMainWithHooks myHooks
where
myHooks = simpleUserHooks { preSDist = myPreSDist }
-- | This hook will be executed before e.g. @cabal sdist@. It runs
-- pandoc to create the man page from shellcheck.1.md. If the pandoc
-- command is not found, this will fail with an error message:
--
-- /bin/sh: pandoc: command not found
--
-- Since the man page is listed in the Extra-Source-Files section of
-- our cabal file, a failure here should result in a failure to
-- create the distribution tarball (that's a good thing).
--
myPreSDist :: Args -> SDistFlags -> IO HookedBuildInfo
myPreSDist _ _ = do
putStrLn "Building the man page..."
putStrLn pandoc_cmd
callCommand pandoc_cmd
return emptyHookedBuildInfo
where
pandoc_cmd = "pandoc -s -t man shellcheck.1.md -o shellcheck.1"

View File

@@ -1,7 +1,7 @@
Name: ShellCheck
Version: 0.3.5
Version: 0.3.8
Synopsis: Shell script analysis tool
License: AGPL-3
License: GPL-3
License-file: LICENSE
Category: Static Analysis
Author: Vidar Holen
@@ -26,6 +26,8 @@ Extra-Source-Files:
-- documentation
README.md
shellcheck.1.md
-- built with a cabal sdist hook
shellcheck.1
-- tests
test/shellcheck.hs
@@ -41,7 +43,7 @@ library
json,
mtl,
parsec,
regex-compat,
regex-tdfa,
QuickCheck >= 2.7.4
exposed-modules:
ShellCheck.Analytics
@@ -49,6 +51,7 @@ library
ShellCheck.Data
ShellCheck.Options
ShellCheck.Parser
ShellCheck.Regex
ShellCheck.Simple
other-modules:
Paths_ShellCheck
@@ -62,7 +65,7 @@ executable shellcheck
json,
mtl,
parsec,
regex-compat,
regex-tdfa,
transformers,
QuickCheck >= 2.7.4
main-is: shellcheck.hs
@@ -77,7 +80,7 @@ test-suite test-shellcheck
json,
mtl,
parsec,
regex-compat,
regex-tdfa,
transformers,
QuickCheck >= 2.7.4
main-is: test/shellcheck.hs

View File

@@ -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)
@@ -28,7 +28,6 @@ data Dashed = Dashed | Undashed deriving (Show, Eq)
data AssignmentMode = Assign | Append deriving (Show, Eq)
data FunctionKeyword = FunctionKeyword Bool deriving (Show, Eq)
data FunctionParentheses = FunctionParentheses Bool deriving (Show, Eq)
data ForInType = NormalForIn | ShortForIn deriving (Show, Eq)
data CaseType = CaseBreak | CaseFallThrough | CaseContinue deriving (Show, Eq)
data Token =
@@ -49,13 +48,12 @@ data Token =
| T_Arithmetic Id Token
| T_Array Id [Token]
| T_IndexedElement Id Token Token
| T_ Id [Token]
| T_Assignment Id AssignmentMode String (Maybe Token) Token
| T_Backgrounded Id 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
@@ -83,7 +81,7 @@ data Token =
| T_Fi Id
| T_For Id
| T_ForArithmetic Id Token Token Token [Token]
| T_ForIn Id ForInType [String] [Token] [Token]
| T_ForIn Id String [Token] [Token]
| T_Function Id FunctionKeyword FunctionParentheses String Token
| T_GREATAND Id
| T_Glob Id String
@@ -123,16 +121,20 @@ data Token =
| T_WhileExpression Id [Token] [Token]
| T_Annotation Id [Annotation] Token
| T_Pipe Id String
| T_CoProc Id (Maybe String) Token
| T_CoProcBody Id Token
deriving (Show)
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
@@ -205,7 +208,7 @@ analyze f g i =
delve (T_BraceGroup id l) = dl l $ T_BraceGroup id
delve (T_WhileExpression id c l) = dll c l $ T_WhileExpression id
delve (T_UntilExpression id c l) = dll c l $ T_UntilExpression id
delve (T_ForIn id t v w l) = dll w l $ T_ForIn id t v
delve (T_ForIn id v w l) = dll w l $ T_ForIn id v
delve (T_SelectIn id v w l) = dll w l $ T_SelectIn id v
delve (T_CaseExpression id word cases) = do
newWord <- round word
@@ -248,6 +251,8 @@ analyze f g i =
delve (TA_Expansion id t) = dl t $ TA_Expansion id
delve (TA_Index id t) = d1 t $ TA_Index id
delve (T_Annotation id anns t) = d1 t $ T_Annotation id anns
delve (T_CoProc id var body) = d1 body $ T_CoProc id var
delve (T_CoProcBody id t) = d1 t $ T_CoProcBody id
delve t = return t
getId t = case t of
@@ -312,7 +317,7 @@ getId t = case t of
T_BraceGroup id _ -> id
T_WhileExpression id _ _ -> id
T_UntilExpression id _ _ -> id
T_ForIn id _ _ _ _ -> id
T_ForIn id _ _ _ -> id
T_SelectIn id _ _ _ -> id
T_CaseExpression id _ _ -> id
T_Function id _ _ _ _ -> id
@@ -341,6 +346,8 @@ getId t = case t of
T_DollarBracket id _ -> id
T_Annotation id _ _ -> id
T_Pipe id _ -> id
T_CoProc id _ _ -> id
T_CoProcBody id _ -> id
blank :: Monad m => Token -> m ()
blank = const $ return ()

File diff suppressed because it is too large Load Diff

View File

@@ -27,22 +27,10 @@ internalVariables = [
"LC_MESSAGES", "LC_NUMERIC", "LINES", "MAIL", "MAILCHECK", "MAILPATH",
"OPTERR", "PATH", "POSIXLY_CORRECT", "PROMPT_COMMAND",
"PROMPT_DIRTRIM", "PS1", "PS2", "PS3", "PS4", "SHELL", "TIMEFORMAT",
"TMOUT", "TMPDIR", "auto_resume", "histchars",
"TMOUT", "TMPDIR", "auto_resume", "histchars", "COPROC",
-- Zsh
"ARGV0", "BAUD", "cdpath", "COLUMNS", "CORRECT_IGNORE",
"DIRSTACKSIZE", "ENV", "FCEDIT", "fignore", "fpath", "histchars",
"HISTCHARS", "HISTFILE", "HISTSIZE", "HOME", "IFS", "KEYBOARD_HACK",
"KEYTIMEOUT", "LANG", "LC_ALL", "LC_COLLATE", "LC_CTYPE",
"LC_MESSAGES", "LC_NUMERIC", "LC_TIME", "LINES", "LISTMAX",
"LOGCHECK", "MAIL", "MAILCHECK", "mailpath", "manpath", "module_path",
"NULLCMD", "path", "POSTEDIT", "PROMPT", "PROMPT2", "PROMPT3",
"PROMPT4", "prompt", "PROMPT_EOL_MARK", "PS1", "PS2", "PS3", "PS4",
"psvar", "READNULLCMD", "REPORTTIME", "REPLY", "reply", "RPROMPT",
"RPS1", "RPROMPT2", "RPS2", "SAVEHIST", "SPROMPT", "STTY", "TERM",
"TERMINFO", "TIMEFMT", "TMOUT", "TMPPREFIX", "watch", "WATCHFMT",
"WORDCHARS", "ZBEEP", "ZDOTDIR", "ZLE_LINE_ABORTED",
"ZLE_REMOVE_SUFFIX_CHARS", "ZLE_SPACE_SUFFIX_CHARS"
-- Other
"USER", "TZ", "TERM"
]
variablesWithoutSpaces = [

View File

@@ -1,6 +1,6 @@
module ShellCheck.Options where
data Shell = Ksh | Zsh | Sh | Bash
data Shell = Ksh | Sh | Bash
deriving (Show, Eq)
data AnalysisOptions = AnalysisOptions {

View File

@@ -3,23 +3,24 @@
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
import ShellCheck.Data
import ShellCheck.Options
import Text.Parsec
import Debug.Trace
import Control.Monad
@@ -236,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 =
@@ -468,14 +475,15 @@ prop_a6 = isOk readArithmeticContents " 1 | 2 ||3|4"
prop_a7 = isOk readArithmeticContents "3*2**10"
prop_a8 = isOk readArithmeticContents "3"
prop_a9 = isOk readArithmeticContents "a^!-b"
prop_aA = isOk readArithmeticContents "! $?"
prop_aB = isOk readArithmeticContents "10#08 * 16#f"
prop_aC = isOk readArithmeticContents "\"$((3+2))\" + '37'"
prop_aD = isOk readArithmeticContents "foo[9*y+x]++"
prop_aE = isOk readArithmeticContents "1+`echo 2`"
prop_aF = isOk readArithmeticContents "foo[`echo foo | sed s/foo/4/g` * 3] + 4"
prop_a10= isOk readArithmeticContents "$foo$bar"
prop_a11= isOk readArithmeticContents "i<(0+(1+1))"
prop_a10= isOk readArithmeticContents "! $?"
prop_a11= isOk readArithmeticContents "10#08 * 16#f"
prop_a12= isOk readArithmeticContents "\"$((3+2))\" + '37'"
prop_a13= isOk readArithmeticContents "foo[9*y+x]++"
prop_a14= isOk readArithmeticContents "1+`echo 2`"
prop_a15= isOk readArithmeticContents "foo[`echo foo | sed s/foo/4/g` * 3] + 4"
prop_a16= isOk readArithmeticContents "$foo$bar"
prop_a17= isOk readArithmeticContents "i<(0+(1+1))"
prop_a18= isOk readArithmeticContents "a?b:c"
readArithmeticContents =
readSequence
where
@@ -517,7 +525,7 @@ readArithmeticContents =
readNormalDollar,
readBraced,
readBackTicked,
readNormalLiteral "+-*/=%^,]"
readNormalLiteral "+-*/=%^,]?:"
]
spacing
return $ TA_Expansion id pieces
@@ -763,15 +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 "=(ls)"
prop_readProcSub3 = isOk readProcSub "<( # nothing here \n)"
readProcSub = called "process substitution" $ do
id <- getNextId
dir <- try $ do
x <- oneOf "<>="
x <- oneOf "<>"
char '('
return [x]
allspacing
list <- readCompoundList
list <- readCompoundListOrEmpty
allspacing
char ')'
return $ T_ProcSub id dir list
@@ -836,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
@@ -949,7 +960,7 @@ readNormalEscaped = called "escaped char" $ do
pos <- getPosition
backslash
do
next <- quotable <|> oneOf "?*@!+[]{}.,"
next <- quotable <|> oneOf "?*@!+[]{}.,~#"
return $ if next == '\n' then "" else [next]
<|>
do
@@ -1044,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
@@ -1077,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
@@ -1094,6 +1117,7 @@ readDollarBracket = called "$[..] expression" $ do
string "]"
return (T_DollarBracket id c)
prop_readArithmeticExpression = isOk readArithmeticExpression "((a?b:c))"
readArithmeticExpression = called "((..)) command" $ do
id <- getNextId
try (string "((")
@@ -1112,32 +1136,44 @@ 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
prop_readDollarVariable = isOk readDollarVariable "$@"
prop_readDollarVariable2 = isOk (readDollarVariable >> anyChar) "$?!"
prop_readDollarVariable3 = isWarning (readDollarVariable >> anyChar) "$10"
prop_readDollarVariable4 = isWarning (readDollarVariable >> string "[@]") "$arr[@]"
readDollarVariable = do
id <- getNextId
pos <- getPosition
let singleCharred p = do
n <- p
value <- wrap [n]
return (T_DollarBraced id value) `attempting` do
pos <- getPosition
num <- lookAhead $ many1 p
parseNoteAt pos ErrorC 1037 $ "$" ++ (n:num) ++ " is equivalent to ${" ++ [n] ++ "}"++ num ++"."
return (T_DollarBraced id value)
let positional = do
value <- singleCharred digit
return value `attempting` do
lookAhead digit
parseNoteAt pos ErrorC 1037 "Braces are required for positionals over 9, e.g. ${10}."
let positional = singleCharred digit
let special = singleCharred specialVariable
let regular = do
name <- readVariableName
value <- wrap name
return $ T_DollarBraced id value
return (T_DollarBraced id value) `attempting` do
lookAhead $ void (string "[@]") <|> void (string "[*]") <|> void readArrayIndex
parseNoteAt pos ErrorC 1087 "Braces are required when expanding arrays, as in ${array[idx]}."
try $ char '$' >> (positional <|> special <|> regular)
@@ -1345,7 +1381,6 @@ prop_readSimpleCommand3 = isOk readSimpleCommand "export foo=(bar baz)"
prop_readSimpleCommand4 = isOk readSimpleCommand "typeset -a foo=(lol)"
prop_readSimpleCommand5 = isOk readSimpleCommand "time if true; then echo foo; fi"
prop_readSimpleCommand6 = isOk readSimpleCommand "time -p ( ls -l; )"
prop_readSimpleCommand7 = isOk readSimpleCommand "cat =(ls)"
readSimpleCommand = called "simple command" $ do
id1 <- getNextId
id2 <- getNextId
@@ -1449,7 +1484,11 @@ readPipe = do
spacing
return $ T_Pipe id ('|':qualifier)
readCommand = readCompoundCommand <|> readSimpleCommand
readCommand = choice [
readCompoundCommand,
readCoProc,
readSimpleCommand
]
readCmdName = do
f <- readNormalWord
@@ -1617,7 +1656,6 @@ prop_readForClause7 = isOk readForClause "for ((;;)) do echo $i\ndone"
prop_readForClause8 = isOk readForClause "for ((;;)) ; do echo $i\ndone"
prop_readForClause9 = isOk readForClause "for i do true; done"
prop_readForClause10= isOk readForClause "for ((;;)) { true; }"
prop_readForClause11= isOk readForClause "for a b in *; do echo $a $b; done"
prop_readForClause12= isWarning readForClause "for $a in *; do echo \"$a\"; done"
readForClause = called "for loop" $ do
pos <- getPosition
@@ -1646,25 +1684,10 @@ readForClause = called "for loop" $ do
readRegular id pos = do
acceptButWarn (char '$') ErrorC 1086
"Don't use $ on the iterator name in for loops."
names <- readNames
readShort names <|> readLong names
where
readLong names = do
values <- readInClause <|> (optional readSequentialSep >> return [])
group <- readDoGroup pos
return $ T_ForIn id NormalForIn names values group
readShort names = do
char '('
allspacing
words <- many (readNormalWord `thenSkip` allspacing)
char ')'
allspacing
command <- readAndOr
return $ T_ForIn id ShortForIn names words [command]
readNames =
reluctantlyTill1 (readVariableName `thenSkip` spacing) $
disregard g_Do <|> disregard readInClause <|> disregard readSequentialSep
name <- readVariableName `thenSkip` spacing
values <- readInClause <|> (optional readSequentialSep >> return [])
group <- readDoGroup pos
return $ T_ForIn id name values group
prop_readSelectClause1 = isOk readSelectClause "select foo in *; do echo $foo; done"
prop_readSelectClause2 = isOk readSelectClause "select foo; do echo $foo; done"
@@ -1785,7 +1808,31 @@ readFunctionDefinition = called "function" $ do
g_Rparen
return ()
readFunctionName = many functionChars
readFunctionName = many1 functionChars
prop_readCoProc1 = isOk readCoProc "coproc foo { echo bar; }"
prop_readCoProc2 = isOk readCoProc "coproc { echo bar; }"
prop_readCoProc3 = isOk readCoProc "coproc echo bar"
readCoProc = called "coproc" $ do
id <- getNextId
try $ do
string "coproc"
whitespace
choice [ try $ readCompoundCoProc id, readSimpleCoProc id ]
where
readCompoundCoProc id = do
var <- optionMaybe $
readVariableName `thenSkip` whitespace
body <- readBody readCompoundCommand
return $ T_CoProc id var body
readSimpleCoProc id = do
body <- readBody readSimpleCommand
return $ T_CoProc id Nothing body
readBody parser = do
id <- getNextId
body <- parser
return $ T_CoProcBody id body
readPattern = (readNormalWord `thenSkip` spacing) `sepBy1` (char '|' `thenSkip` spacing)
@@ -1804,6 +1851,9 @@ readCompoundCommand = do
readCompoundList = readTerm
readCompoundListOrEmpty = do
allspacing
readTerm <|> return []
readCmdPrefix = many1 (readIoRedirect <|> readAssignmentWord)
readCmdSuffix = many1 (readIoRedirect <|> readCmdWord)
@@ -1842,6 +1892,7 @@ prop_readAssignmentWord6 = isWarning readAssignmentWord "b += (1 2 3)"
prop_readAssignmentWord7 = isOk readAssignmentWord "a[3$n'']=42"
prop_readAssignmentWord8 = isOk readAssignmentWord "a[4''$(cat foo)]=42"
prop_readAssignmentWord9 = isOk readAssignmentWord "IFS= "
prop_readAssignmentWord9a= isOk readAssignmentWord "foo="
prop_readAssignmentWord10= isWarning readAssignmentWord "foo$n=42"
prop_readAssignmentWord11= isOk readAssignmentWord "foo=([a]=b [c] [d]= [e f )"
prop_readAssignmentWord12= isOk readAssignmentWord "a[b <<= 3 + c]='thing'"
@@ -1850,25 +1901,23 @@ readAssignmentWord = try $ do
pos <- getPosition
optional (char '$' >> parseNote ErrorC 1066 "Don't use $ on the left side of assignments.")
variable <- readVariableName
notFollowedBy2 $ do -- Special case for zsh =(..) syntax
spacing1
string "=("
optional (readNormalDollar >> parseNoteAt pos ErrorC
1067 "For indirection, use (associative) arrays or 'read \"var$n\" <<< \"value\"'")
index <- optionMaybe readArrayIndex
space <- spacing
hasLeftSpace <- liftM (not . null) spacing
pos <- getPosition
op <- readAssignmentOp
space2 <- spacing
if space == "" && space2 /= ""
hasRightSpace <- liftM (not . null) spacing
isEndOfCommand <- liftM isJust $ optionMaybe (try . lookAhead $ (disregard (oneOf "\r\n;&|)") <|> eof))
if not hasLeftSpace && (hasRightSpace || isEndOfCommand)
then do
when (variable /= "IFS") $
when (variable /= "IFS" && hasRightSpace) $
parseNoteAt pos WarningC 1007
"Remove space after = if trying to assign a value (for empty string, use var='' ... )."
value <- readEmptyLiteral
return $ T_Assignment id op variable index value
else do
when (space /= "" || space2 /= "") $
when (hasLeftSpace || hasRightSpace) $
parseNoteAt pos ErrorC 1068 "Don't put spaces around the = in assignments."
value <- readArray <|> readNormalWord
spacing
@@ -2008,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
@@ -2022,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
@@ -2050,8 +2108,8 @@ readScript = do
verifyShell pos s =
case isValidShell s of
Just True -> return ()
Just False -> parseProblemAt pos ErrorC 1071 "ShellCheck only supports Bourne based shell scripts, sorry!"
Nothing -> parseProblemAt pos InfoC 1008 "This shebang was unrecognized. Note that ShellCheck only handles Bourne based shells."
Just False -> parseProblemAt pos ErrorC 1071 "ShellCheck only supports sh/bash/ksh scripts. Sorry!"
Nothing -> parseProblemAt pos InfoC 1008 "This shebang was unrecognized. Note that ShellCheck only handles sh/bash/ksh."
isValidShell s =
let good = s == "" || any (`isPrefixOf` s) goodShells
@@ -2065,17 +2123,20 @@ readScript = do
goodShells = [
"sh",
"ash",
"dash",
"bash",
"ksh",
"zsh"
"ksh"
]
badShells = [
"awk",
"csh",
"expect",
"perl",
"python",
"ruby",
"tcsh"
"tcsh",
"zsh"
]
readUtf8Bom = called "Byte Order Mark" $ string "\xFEFF"
@@ -2119,13 +2180,13 @@ getStringFromParsec errors =
Message s -> if null s then Nothing else return $ s ++ "."
unexpected s = "Unexpected " ++ (if null s then "eof" else s) ++ "."
parseShell filename contents =
parseShell options filename contents =
case rp (parseWithNotes readScript) filename contents of
(Right (script, map, notes), (parsenotes, _)) ->
ParseResult (Just (script, map)) (nub $ sortNotes $ notes ++ parsenotes)
ParseResult (Just (script, map)) (nub . sortNotes . excludeNotes $ notes ++ parsenotes)
(Left err, (p, context)) ->
ParseResult Nothing
(nub $ sortNotes $ p ++ notesForContext context ++ [makeErrorFor err])
(nub . sortNotes . excludeNotes $ p ++ notesForContext context ++ [makeErrorFor err])
where
isName (ContextName _ _) = True
isName _ = False
@@ -2134,6 +2195,7 @@ parseShell filename contents =
"Couldn't parse this " ++ str ++ "."
second (ContextName pos str) = ParseNote pos InfoC 1009 $
"The mentioned parser error was in this " ++ str ++ "."
excludeNotes = filter (\c -> codeForParseNote c `notElem` optionExcludes options)
lt x = trace (show x) x
ltt t = trace (show t)

71
ShellCheck/Regex.hs Normal file
View 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

View File

@@ -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 #-}
@@ -28,7 +28,7 @@ import Text.Parsec.Pos
shellCheck :: AnalysisOptions -> String -> [ShellCheckComment]
shellCheck options script =
let (ParseResult result notes) = parseShell "-" script in
let (ParseResult result notes) = parseShell options "-" script in
let allNotes = notes ++ concat (maybeToList $ do
(tree, posMap) <- result
let list = runAnalytics options tree
@@ -72,6 +72,9 @@ prop_commentDisablesAnalysisIssue2 =
prop_optionDisablesIssue1 =
null $ shellCheck (defaultAnalysisOptions { optionExcludes = [2086, 2148] }) "echo $1"
prop_optionDisablesIssue2 =
null $ shellCheck (defaultAnalysisOptions { optionExcludes = [2148, 1037] }) "echo \"$10\""
return []
runTests = $quickCheckAll

View File

@@ -16,6 +16,20 @@ errors and pitfalls where the shell just gives a cryptic error message or
strange behavior, but it also reports on a few more advanced issues where
corner cases can cause delayed failures.
ShellCheck gives shell specific advice. Consider the line:
(( area = 3.14*r*r ))
+ For scripts starting with `#!/bin/sh` (or when using `-s sh`), ShellCheck
will warn that `(( .. ))` is not POSIX compliant (similar to checkbashisms).
+ For scripts starting with `#!/bin/bash` (or using `-s bash`), ShellCheck
will warn that decimals are not supported.
+ For scripts starting with `#!/bin/ksh` (or using `-s ksh`), ShellCheck will
not warn at all, as `ksh` supports decimals in arithmetic contexts.
# OPTIONS
**-e**\ *CODE1*[,*CODE2*...],\ **--exclude=***CODE1*[,*CODE2*...]
@@ -32,9 +46,9 @@ corner cases can cause delayed failures.
**-s**\ *shell*,\ **--shell=***shell*
: Specify Bourne shell dialect. Valid values are *sh*, *bash*, *ksh* and
*zsh*. The default is to use the file's shebang, or *bash* if the target
shell can't be determined.
: Specify Bourne shell dialect. Valid values are *sh*, *bash* and *ksh*.
The default is to use the file's shebang, or *bash* if the target shell
can't be determined.
**-V**\ *version*,\ **--version**
@@ -83,11 +97,12 @@ corner cases can cause delayed failures.
[
{
"line": line,
"column": column,
"level": level,
"code": ####,
"message": message
"file": "filename",
"line": lineNumber,
"column": columnNumber,
"level": "severitylevel",
"code": errorCode,
"message": "warning message"
},
...
]
@@ -104,6 +119,14 @@ For example, to suppress SC2035 about using `./*.jpg`:
# shellcheck disable=SC2035
echo "Files: " *.jpg
Here a shell brace group is used to suppress on multiple lines:
# shellcheck disable=SC2016
{
echo 'Modifying $PATH'
echo 'PATH=foo:$PATH' >> ~/.bashrc
}
Valid keys are:
**disable**

View File

@@ -3,23 +3,25 @@
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
import Control.Monad
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
@@ -33,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
@@ -40,6 +43,8 @@ import qualified Data.Map as Map
data Flag = Flag String String
data Status = NoProblems | SomeProblems | BadInput | SupportFailure | SyntaxFailure | RuntimeException deriving (Ord, Eq)
data JsonComment = JsonComment FilePath ShellCheckComment
instance Error Status where
noMsg = RuntimeException
@@ -54,7 +59,7 @@ options = [
Option "f" ["format"]
(ReqArg (Flag "format") "FORMAT") "output format",
Option "s" ["shell"]
(ReqArg (Flag "shell") "SHELLNAME") "Specify dialect (bash,sh,ksh,zsh)",
(ReqArg (Flag "shell") "SHELLNAME") "Specify dialect (bash,sh,ksh)",
Option "V" ["version"]
(NoArg $ Flag "version" "true") "Print version information"
]
@@ -62,8 +67,9 @@ options = [
printErr = hPutStrLn stderr
instance JSON ShellCheckComment where
showJSON c = makeObj [
instance JSON (JsonComment) where
showJSON (JsonComment filename c) = makeObj [
("file", showJSON $ filename),
("line", showJSON $ scLine c),
("column", showJSON $ scColumn c),
("level", showJSON $ scSeverity c),
@@ -150,12 +156,15 @@ 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
-- This totally ignores the filenames. Fixme?
forJson :: AnalysisOptions -> [FilePath] -> IO Status
forJson options files = catchExceptions $ do
comments <- liftM concat $ mapM (commentsFor options) files
comments <- runListT $ do
file <- ListT $ return files
comment <- ListT $ commentsFor options file
return $ JsonComment file comment
putStrLn $ encodeStrict comments
return $ checkComments comments
@@ -344,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"