Skip to content

Commit 131db58

Browse files
CopilotFreed-Wu
andcommitted
Add EditorConfig support for shellcheck directives
Co-authored-by: Freed-Wu <32936898+Freed-Wu@users.noreply.github.com>
1 parent 9af7ee2 commit 131db58

5 files changed

Lines changed: 231 additions & 2 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: 58 additions & 2 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

@@ -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,47 @@ 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+
let next = takeDirectory dir
587+
rest <- if next /= dir
588+
then collectDirConfigs next
589+
else return []
590+
current <- readConfig (dir </> ".editorconfig")
591+
return $ maybeToList current ++ rest
592+
593+
readGlobalEditorConfig = do
594+
path <- (getXdgDirectory XdgConfig "editorconfig.ini")
595+
`catch` ((const $ return "") :: IOException -> IO FilePath)
596+
if null path
597+
then return []
598+
else maybeToList <$> readConfig path
599+
544600
findConfig paths =
545601
case paths of
546602
(file:rest) -> do

src/ShellCheck/EditorConfig.hs

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
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, 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+
parseEditorConfig :: String -> FilePath -> String
42+
parseEditorConfig contents name =
43+
unlines . concatMap sectionDirectives $ sections
44+
where
45+
ls = lines contents
46+
sections = splitSections ls
47+
48+
splitSections [] = []
49+
splitSections (l:rest) =
50+
case parseHeader l of
51+
Just pat ->
52+
let (body, rest') = break (isJust . parseHeader) rest
53+
in (pat, body) : splitSections rest'
54+
Nothing -> splitSections rest
55+
56+
parseHeader l =
57+
let t = trim (stripComment l)
58+
in case t of
59+
('[':cs@(_:_)) | last cs == ']' -> Just (init cs)
60+
_ -> Nothing
61+
62+
sectionDirectives (pat, body) =
63+
if matchesGlob pat name
64+
then mapMaybe toDirective body
65+
else []
66+
67+
toDirective l =
68+
let t = trim (stripComment l)
69+
in case break (== '=') t of
70+
(key, '=':value) ->
71+
let key' = trim key
72+
value' = trim value
73+
in if "shellcheck." `isPrefixOf` key'
74+
then Just (drop (length "shellcheck.") key' ++ "=" ++ value')
75+
else Nothing
76+
_ -> Nothing
77+
78+
stripComment = takeWhile (\c -> c /= '#' && c /= ';')
79+
80+
trim :: String -> String
81+
trim = dropWhileEnd isSpace . dropWhile isSpace
82+
83+
-- Does the (basename of the) file match the given EditorConfig glob?
84+
matchesGlob :: String -> FilePath -> Bool
85+
matchesGlob pattern name =
86+
name `matches` mkRegex (globToRegexString pattern)
87+
88+
-- Translate an EditorConfig glob pattern into an anchored regex string.
89+
globToRegexString :: String -> String
90+
globToRegexString pattern = "^" ++ go pattern ++ "$"
91+
where
92+
go [] = ""
93+
go ('*':'*':rest) = ".*" ++ go rest
94+
go ('*':rest) = "[^/]*" ++ go rest
95+
go ('?':rest) = "[^/]" ++ go rest
96+
go ('[':rest) =
97+
let (cls, rest') = break (== ']') rest
98+
in case rest' of
99+
(']':rest'') -> "[" ++ translateClass cls ++ "]" ++ go rest''
100+
_ -> "\\[" ++ go rest
101+
go ('{':rest) =
102+
let (body, rest') = break (== '}') rest
103+
in case rest' of
104+
('}':rest'') ->
105+
"(" ++ intercalate "|" (map go (splitCommas body)) ++ ")" ++ go rest''
106+
_ -> "\\{" ++ go rest
107+
go (c:rest)
108+
| c `elem` regexSpecials = ['\\', c] ++ go rest
109+
| otherwise = c : go rest
110+
111+
regexSpecials = ".\\+()^$|"
112+
113+
translateClass ('!':cs) = '^' : escapeClass cs
114+
translateClass cs = escapeClass cs
115+
escapeClass = concatMap (\c -> if c == '\\' then "\\\\" else [c])
116+
117+
splitCommas s =
118+
case break (== ',') s of
119+
(before, ',':after) -> before : splitCommas after
120+
(before, "") -> [before]
121+
(before, after) -> [before ++ after]
122+
123+
prop_globStar = matchesGlob "*.ebuild" "foo.ebuild"
124+
prop_globBraceExt = matchesGlob "*.{ebuild,eclass}" "foo.eclass"
125+
prop_globBraceExt2 = matchesGlob "*.{ebuild,eclass}" "foo.ebuild"
126+
prop_globBraceName = matchesGlob "{PKGBUILD,APKBUILD}" "PKGBUILD"
127+
prop_globBraceName2 = matchesGlob "{PKGBUILD,APKBUILD}" "APKBUILD"
128+
prop_globNoMatch = not $ matchesGlob "*.ebuild" "foo.txt"
129+
prop_globQuestion = matchesGlob "foo?.sh" "food.sh"
130+
prop_globClass = matchesGlob "foo[0-9].sh" "foo1.sh"
131+
prop_globClassNeg = not $ matchesGlob "foo[!0-9].sh" "foo1.sh"
132+
133+
prop_parseEditorConfig1 =
134+
parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\nshellcheck.disable=SC2034\n" "foo.ebuild"
135+
== "shell=bash\ndisable=SC2034\n"
136+
prop_parseEditorConfig2 =
137+
parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\n" "foo.txt" == ""
138+
prop_parseEditorConfig3 =
139+
parseEditorConfig "[{PKGBUILD,APKBUILD}]\nshellcheck.disable=SC2034\n" "PKGBUILD" == "disable=SC2034\n"
140+
prop_parseEditorConfig4 =
141+
parseEditorConfig "root = true\n[*.sh]\nindent_style = space\nshellcheck.shell=bash\n" "foo.sh"
142+
== "shell=bash\n"
143+
144+
return []
145+
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)