Skip to content

Commit b96b058

Browse files
CopilotFreed-Wu
andcommitted
Add EditorConfig support for shellcheck directives
Fix EditorConfig section priority, glob depth matching, and root=true search stop Co-authored-by: Freed-Wu <32936898+Freed-Wu@users.noreply.github.com>
1 parent 9af7ee2 commit b96b058

5 files changed

Lines changed: 283 additions & 3 deletions

File tree

ShellCheck.cabal

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ library
8484
ShellCheck.Checks.Custom
8585
ShellCheck.Checks.ShellSupport
8686
ShellCheck.Data
87+
ShellCheck.EditorConfig
8788
ShellCheck.Fixer
8889
ShellCheck.Formatter.Format
8990
ShellCheck.Formatter.CheckStyle

shellcheck.1.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,31 @@ Use `shellcheckrc` without the dot instead.
334334
Note for Docker users: ShellCheck will only be able to look for files that
335335
are mounted in the container, so `~/.shellcheckrc` will not be read.
336336

337+
# EDITORCONFIG
338+
339+
Unless `--norc` is used, ShellCheck will also look for a file `.editorconfig`
340+
in the script's directory and each parent directory. Any section whose glob
341+
pattern matches the checked file will have its `shellcheck.*` keys read as
342+
directives, with the `shellcheck.` prefix stripped. This uses the same
343+
`key=value` syntax as `.shellcheckrc`.
344+
345+
For example:
346+
347+
[*.{ebuild,eclass}]
348+
shellcheck.shell=bash
349+
shellcheck.disable=SC2034
350+
351+
[{PKGBUILD,APKBUILD}]
352+
shellcheck.shell=bash
353+
shellcheck.disable=SC2034
354+
355+
If no matching directives are found in any `.editorconfig` in the parent
356+
directories, ShellCheck will look in the global default
357+
`$XDG_CONFIG_HOME/editorconfig.ini` (usually `~/.config/editorconfig.ini`).
358+
359+
Directives from `.shellcheckrc`/`shellcheckrc` and from `.editorconfig` are
360+
both applied, with `.shellcheckrc` taking precedence in case of conflicts.
361+
337362

338363
# ENVIRONMENT VARIABLES
339364

shellcheck.hs

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import qualified ShellCheck.Analyzer
2121
import ShellCheck.Checker
2222
import ShellCheck.Data
23+
import ShellCheck.EditorConfig
2324
import ShellCheck.Interface
2425
import ShellCheck.Regex
2526

@@ -110,7 +111,7 @@ options = [
110111
Option "" ["list-optional"]
111112
(NoArg $ Flag "list-optional" "true") "List checks disabled by default",
112113
Option "" ["norc"]
113-
(NoArg $ Flag "norc" "true") "Don't look for .shellcheckrc files",
114+
(NoArg $ Flag "norc" "true") "Don't look for .shellcheckrc and .editorconfig files",
114115
Option "" ["rcfile"]
115116
(ReqArg (Flag "rcfile") "RCFILE")
116117
"Prefer the specified configuration file over searching for one",
@@ -514,8 +515,22 @@ ioInterface options files = do
514515
fallback path _ = return path
515516

516517

517-
-- Returns the name and contents of .shellcheckrc for the given file
518-
getConfig cache filename =
518+
-- Returns the name and contents of .shellcheckrc for the given file,
519+
-- merged with any shellcheck.* directives found in applicable
520+
-- EditorConfig files.
521+
getConfig cache filename = do
522+
rcResult <- getRcConfig cache filename
523+
ecResult <- getEditorConfig filename
524+
return $ mergeConfigs filename rcResult ecResult
525+
526+
mergeConfigs filename rcResult ecResult =
527+
case (rcResult, ecResult) of
528+
(Nothing, Nothing) -> Nothing
529+
(Just (_, rc), Nothing) -> Just (filename, rc)
530+
(Nothing, Just ec) -> Just (filename, ec)
531+
(Just (_, rc), Just ec) -> Just (filename, rc ++ "\n" ++ ec)
532+
533+
getRcConfig cache filename =
519534
case rcfile options of
520535
Just file -> do
521536
-- We have a specified rcfile. Ignore normal rcfile resolution.
@@ -541,6 +556,48 @@ ioInterface options files = do
541556
writeIORef cache (dir, result)
542557
return result
543558

559+
-- Look for .editorconfig files in the target file's directory and
560+
-- all its parents (as per the EditorConfig spec), plus the global
561+
-- ${XDG_CONFIG_HOME}/editorconfig.ini default. shellcheck.* keys in
562+
-- matching sections are turned into directives.
563+
getEditorConfig filename = do
564+
path <- normalize filename
565+
dirConfigs <- collectDirConfigs (takeDirectory path)
566+
globalConfig <- readGlobalEditorConfig
567+
let directives = concatMap (directivesFor path) (dirConfigs ++ globalConfig)
568+
return $ if null directives then Nothing else Just (concat directives)
569+
where
570+
directivesFor path (file, contents) =
571+
let relative = makeRelativeTo (takeDirectory file) path
572+
result = parseEditorConfig contents relative
573+
in [result | not (null result)]
574+
575+
makeRelativeTo dir path =
576+
case stripPrefix (addTrailingSlash dir) path of
577+
Just rest -> rest
578+
Nothing -> takeFileName path
579+
580+
addTrailingSlash dir
581+
| null dir = dir
582+
| last dir == '/' = dir
583+
| otherwise = dir ++ "/"
584+
585+
collectDirConfigs dir = do
586+
current <- readConfig (dir </> ".editorconfig")
587+
let isRoot = maybe False (isEditorConfigRoot . snd) current
588+
next = takeDirectory dir
589+
rest <- if next /= dir && not isRoot
590+
then collectDirConfigs next
591+
else return []
592+
return $ maybeToList current ++ rest
593+
594+
readGlobalEditorConfig = do
595+
path <- (getXdgDirectory XdgConfig "editorconfig.ini")
596+
`catch` ((const $ return "") :: IOException -> IO FilePath)
597+
if null path
598+
then return []
599+
else maybeToList <$> readConfig path
600+
544601
findConfig paths =
545602
case paths of
546603
(file:rest) -> do

src/ShellCheck/EditorConfig.hs

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
{-
2+
Copyright 2012-2024 Vidar Holen
3+
4+
This file is part of ShellCheck.
5+
https://www.shellcheck.net
6+
7+
ShellCheck is free software: you can redistribute it and/or modify
8+
it under the terms of the GNU General Public License as published by
9+
the Free Software Foundation, either version 3 of the License, or
10+
(at your option) any later version.
11+
12+
ShellCheck is distributed in the hope that it will be useful,
13+
but WITHOUT ANY WARRANTY; without even the implied warranty of
14+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+
GNU General Public License for more details.
16+
17+
You should have received a copy of the GNU General Public License
18+
along with this program. If not, see <https://www.gnu.org/licenses/>.
19+
-}
20+
21+
{-# LANGUAGE TemplateHaskell #-}
22+
-- Minimal support for reading shellcheck directives from EditorConfig
23+
-- style files (https://editorconfig.org/). Only the `shellcheck.*` keys
24+
-- of sections whose glob matches the file being checked are extracted,
25+
-- and turned into the same "key=value" directive syntax that is used in
26+
-- .shellcheckrc files.
27+
module ShellCheck.EditorConfig (parseEditorConfig, isEditorConfigRoot, globToRegexString, runTests) where
28+
29+
import Data.Char
30+
import Data.List
31+
import Data.Maybe
32+
33+
import ShellCheck.Regex
34+
35+
import Test.QuickCheck
36+
37+
-- Given the contents of an EditorConfig style file and the name of the
38+
-- file being checked, return the shellcheck directives (as a
39+
-- "key=value\n" delimited blob, suitable for feeding into the same
40+
-- parser as .shellcheckrc) found in matching sections.
41+
--
42+
-- As per the EditorConfig spec, files are read top to bottom and
43+
-- properties from later sections override those from earlier ones
44+
-- (for the same key), so on conflicts the last matching section wins.
45+
parseEditorConfig :: String -> FilePath -> String
46+
parseEditorConfig contents name =
47+
unlines . map render . lastWins . concatMap sectionDirectives $ sections
48+
where
49+
render (key, value) = key ++ "=" ++ value
50+
51+
-- Keep only the last occurrence of each key, preserving the
52+
-- relative order of the remaining (first-seen) entries.
53+
lastWins = reverse . nubBy (\a b -> fst a == fst b) . reverse
54+
55+
ls = lines contents
56+
sections = splitSections ls
57+
58+
splitSections [] = []
59+
splitSections (l:rest) =
60+
case parseHeader l of
61+
Just pat ->
62+
let (body, rest') = break (isJust . parseHeader) rest
63+
in (pat, body) : splitSections rest'
64+
Nothing -> splitSections rest
65+
66+
parseHeader l =
67+
let t = trim (stripComment l)
68+
in case t of
69+
('[':cs@(_:_)) | last cs == ']' -> Just (init cs)
70+
_ -> Nothing
71+
72+
sectionDirectives (pat, body) =
73+
if matchesGlob pat name
74+
then mapMaybe toDirective body
75+
else []
76+
77+
toDirective l =
78+
let t = trim (stripComment l)
79+
in case break (== '=') t of
80+
(key, '=':value) ->
81+
let key' = trim key
82+
value' = trim value
83+
in if "shellcheck." `isPrefixOf` key'
84+
then Just (drop (length "shellcheck.") key', value')
85+
else Nothing
86+
_ -> Nothing
87+
88+
stripComment = takeWhile (\c -> c /= '#' && c /= ';')
89+
90+
-- Does the top-level (pre-section) part of an EditorConfig file
91+
-- declare "root = true"? Per the spec, this stops the search for
92+
-- further EditorConfig files in parent directories.
93+
isEditorConfigRoot :: String -> Bool
94+
isEditorConfigRoot contents =
95+
any isRootTrue . takeWhile (not . isSectionHeader) $ lines contents
96+
where
97+
isSectionHeader l =
98+
case trim (stripComment l) of
99+
('[':cs@(_:_)) -> last cs == ']'
100+
_ -> False
101+
102+
isRootTrue l =
103+
case break (== '=') (trim (stripComment l)) of
104+
(key, '=':value) ->
105+
map toLower (trim key) == "root" && map toLower (trim value) == "true"
106+
_ -> False
107+
108+
stripComment = takeWhile (\c -> c /= '#' && c /= ';')
109+
110+
trim :: String -> String
111+
trim = dropWhileEnd isSpace . dropWhile isSpace
112+
113+
-- Does the (relative path of the) file match the given EditorConfig glob?
114+
matchesGlob :: String -> FilePath -> Bool
115+
matchesGlob pattern name =
116+
name `matches` mkRegex (globToRegexString pattern)
117+
118+
-- Translate an EditorConfig glob pattern into an anchored regex string.
119+
-- Per the spec, patterns without a path separator are matched against
120+
-- the file at any depth (as if prefixed with "**/").
121+
globToRegexString :: String -> String
122+
globToRegexString pattern = "^" ++ prefix ++ go pattern ++ "$"
123+
where
124+
prefix = if '/' `elem` pattern then "" else "(.*/)?"
125+
126+
go [] = ""
127+
go ('*':'*':rest) = ".*" ++ go rest
128+
go ('*':rest) = "[^/]*" ++ go rest
129+
go ('?':rest) = "[^/]" ++ go rest
130+
go ('[':rest) =
131+
let (cls, rest') = break (== ']') rest
132+
in case rest' of
133+
(']':rest'') -> "[" ++ translateClass cls ++ "]" ++ go rest''
134+
_ -> "\\[" ++ go rest
135+
go ('{':rest) =
136+
let (body, rest') = break (== '}') rest
137+
in case rest' of
138+
('}':rest'') ->
139+
"(" ++ intercalate "|" (map go (splitCommas body)) ++ ")" ++ go rest''
140+
_ -> "\\{" ++ go rest
141+
go (c:rest)
142+
| c `elem` regexSpecials = ['\\', c] ++ go rest
143+
| otherwise = c : go rest
144+
145+
regexSpecials = ".\\+()^$|"
146+
147+
translateClass ('!':cs) = '^' : escapeClass cs
148+
translateClass cs = escapeClass cs
149+
escapeClass = concatMap (\c -> if c == '\\' then "\\\\" else [c])
150+
151+
splitCommas s =
152+
case break (== ',') s of
153+
(before, ',':after) -> before : splitCommas after
154+
(before, "") -> [before]
155+
(before, after) -> [before ++ after]
156+
157+
prop_globStar = matchesGlob "*.ebuild" "foo.ebuild"
158+
prop_globBraceExt = matchesGlob "*.{ebuild,eclass}" "foo.eclass"
159+
prop_globBraceExt2 = matchesGlob "*.{ebuild,eclass}" "foo.ebuild"
160+
prop_globBraceName = matchesGlob "{PKGBUILD,APKBUILD}" "PKGBUILD"
161+
prop_globBraceName2 = matchesGlob "{PKGBUILD,APKBUILD}" "APKBUILD"
162+
prop_globNoMatch = not $ matchesGlob "*.ebuild" "foo.txt"
163+
prop_globQuestion = matchesGlob "foo?.sh" "food.sh"
164+
prop_globClass = matchesGlob "foo[0-9].sh" "foo1.sh"
165+
prop_globClassNeg = not $ matchesGlob "foo[!0-9].sh" "foo1.sh"
166+
-- Patterns without a path separator should match at any depth.
167+
prop_globAnyDepth = matchesGlob "*.sh" "sub/dir/foo.sh"
168+
prop_globAnyDepthPlain = matchesGlob "foo" "sub/foo"
169+
-- Patterns with a path separator are only matched against the full
170+
-- relative path.
171+
prop_globWithSlashNoMatch = not $ matchesGlob "sub/*.sh" "other/foo.sh"
172+
prop_globWithSlashMatch = matchesGlob "sub/*.sh" "sub/foo.sh"
173+
174+
prop_parseEditorConfig1 =
175+
parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\nshellcheck.disable=SC2034\n" "foo.ebuild"
176+
== "shell=bash\ndisable=SC2034\n"
177+
prop_parseEditorConfig2 =
178+
parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\n" "foo.txt" == ""
179+
prop_parseEditorConfig3 =
180+
parseEditorConfig "[{PKGBUILD,APKBUILD}]\nshellcheck.disable=SC2034\n" "PKGBUILD" == "disable=SC2034\n"
181+
prop_parseEditorConfig4 =
182+
parseEditorConfig "root = true\n[*.sh]\nindent_style = space\nshellcheck.shell=bash\n" "foo.sh"
183+
== "shell=bash\n"
184+
-- A later, more specific section overrides an earlier, more general
185+
-- one for the same key.
186+
prop_parseEditorConfig5 =
187+
parseEditorConfig "[*]\nshellcheck.shell=sh\n\n[foo]\nshellcheck.shell=bash\n" "foo"
188+
== "shell=bash\n"
189+
-- Non-conflicting keys from earlier and later sections are all kept.
190+
prop_parseEditorConfig6 =
191+
parseEditorConfig "[*]\nshellcheck.shell=sh\n\n[foo]\nshellcheck.disable=SC2034\n" "foo"
192+
== "shell=sh\ndisable=SC2034\n"
193+
194+
return []
195+
runTests = $quickCheckAll

test/shellcheck.hs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import qualified ShellCheck.Checks.Commands
1212
import qualified ShellCheck.Checks.ControlFlow
1313
import qualified ShellCheck.Checks.Custom
1414
import qualified ShellCheck.Checks.ShellSupport
15+
import qualified ShellCheck.EditorConfig
1516
import qualified ShellCheck.Fixer
1617
import qualified ShellCheck.Formatter.Diff
1718
import qualified ShellCheck.Parser
@@ -35,6 +36,7 @@ main = do
3536
, ("Checks.ControlFlow" , ShellCheck.Checks.ControlFlow.runTests)
3637
, ("Checks.Custom" , ShellCheck.Checks.Custom.runTests)
3738
, ("Checks.ShellSupport", ShellCheck.Checks.ShellSupport.runTests)
39+
, ("EditorConfig" , ShellCheck.EditorConfig.runTests)
3840
, ("Fixer" , ShellCheck.Fixer.runTests)
3941
, ("Formatter.Diff" , ShellCheck.Formatter.Diff.runTests)
4042
, ("Parser" , ShellCheck.Parser.runTests)

0 commit comments

Comments
 (0)