Skip to content

Commit fcc8f22

Browse files
Handle multiline options
Clean up options expecting lists before using them, as they may contain newlines. Examples: * Enclosing command-line arguments in quotes may introduce newlines in option values: $ codespell -S "A, B, > C, D, E" * INI files may contain multiline values: [codespell] skip = A, B, C, D, E, In all the above cases, the option parsing mechanism keeps the newlines (and spaces). We need to clean up, by splitting on commas and stripping each resulting item from newlines (and spaces).
1 parent a5c8237 commit fcc8f22

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

codespell_lib/_codespell.py

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -160,19 +160,15 @@ class QuietLevels:
160160

161161

162162
class GlobMatch:
163-
def __init__(self, pattern: Optional[str]) -> None:
164-
self.pattern_list: Optional[List[str]]
165-
if pattern:
166-
# Pattern might be a list of comma-delimited strings
167-
self.pattern_list = ",".join(pattern).split(",")
168-
else:
169-
self.pattern_list = None
163+
def __init__(self, pattern: Optional[List[str]]) -> None:
164+
self.pattern_list: Optional[List[str]] = pattern
170165

171166
def match(self, filename: str) -> bool:
172-
if self.pattern_list is None:
173-
return False
174-
175-
return any(fnmatch.fnmatch(filename, p) for p in self.pattern_list)
167+
return (
168+
any(fnmatch.fnmatch(filename, p) for p in self.pattern_list)
169+
if self.pattern_list
170+
else False
171+
)
176172

177173

178174
class Misspelling:
@@ -1109,6 +1105,22 @@ def parse_file(
11091105
return bad_count
11101106

11111107

1108+
def flatten_clean_comma_separated_arguments(
1109+
arguments: Optional[List[str]],
1110+
) -> Optional[List[str]]:
1111+
"""
1112+
>>> flatten_clean_comma_separated_arguments(["a, b ,\n c, d,", "e"])
1113+
['a', 'b', 'c', 'd', 'e']
1114+
>>> flatten_clean_comma_separated_arguments([])
1115+
>>> flatten_clean_comma_separated_arguments(None)
1116+
"""
1117+
return (
1118+
[item.strip() for argument in arguments for item in argument.split(",") if item]
1119+
if arguments
1120+
else None
1121+
)
1122+
1123+
11121124
def _script_main() -> int:
11131125
"""Wrap to main() for setuptools."""
11141126
return main(*sys.argv[1:])
@@ -1256,7 +1268,7 @@ def main(*args: str) -> int:
12561268

12571269
file_opener = FileOpener(options.hard_encoding_detection, options.quiet_level)
12581270

1259-
glob_match = GlobMatch(options.skip)
1271+
glob_match = GlobMatch(flatten_clean_comma_separated_arguments(options.skip))
12601272
try:
12611273
glob_match.match("/random/path") # does not need a real path
12621274
except re.error:

0 commit comments

Comments
 (0)