Skip to content

Fix: Handle Trailing Commas and Empty Strings in File Paths #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix config parsing to allow trailing commas but prevent empty entries
- Modified `split_and_match_files_list` to handle trailing commas correctly.
- Ensured empty string entries result in an error to match CLI behavior.
- Updated unit tests to cover various edge cases.
- Improved test coverage for config parsing with different file list formats.
  • Loading branch information
x612skm committed Feb 24, 2025
commit ec969415a455e6b81c738180078eae6fe84615be
19 changes: 19 additions & 0 deletions mypy/config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ def split_and_match_files_list(paths: Sequence[str]) -> list[str]:
expanded_paths = []

for path in paths:
if not path:
continue

path = expand_path(path.strip())
globbed_files = fileglob.glob(path, recursive=True)
if globbed_files:
Expand Down Expand Up @@ -318,6 +321,22 @@ def parse_config_file(
print(f"{file_read}: No [mypy] section in config file", file=stderr)
else:
section = parser["mypy"]

if "files" in section:
raw_files = section["files"].strip()
files_split = [file.strip() for file in raw_files.split(",")]

# Remove trailing empty entry if present
if files_split and files_split[-1] == "":
files_split.pop()
Comment on lines +329 to +331

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This check removes the trailing empty string, but the subsequent check on line 334 raises an error if any empty strings are present. Consider simplifying this logic to directly raise an error if any empty strings are present after stripping whitespace, as trailing commas are now explicitly allowed.

# Raise an error if there are any empty strings
if any(not file for file in files_split):
    raise ValueError(
        "Invalid config: Empty filenames are not allowed except for trailing commas."
    )


# Raise an error if there are any remaining empty strings
if "" in files_split:
raise ValueError("Invalid config: Empty filenames are not allowed except for trailing commas.")

options.files = files_split


prefix = f"{file_read}: [mypy]: "
updates, report_dirs = parse_section(
prefix, options, set_strict_flags, section, config_types, stderr
Expand Down
213 changes: 213 additions & 0 deletions mypy/test/testconfigparser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import os
import tempfile
from unittest import TestCase, main
from mypy.options import Options
from mypy.config_parser import parse_config_file

class TestConfigParser(TestCase):
def test_parse_config_file_with_single_file(self):
"""A single file should be correctly parsed."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files = file1.py
"""
)

options = Options()

parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertEqual(options.files, ["file1.py"])

def test_parse_config_file_with_no_spaces(self):
"""Files listed without spaces should be correctly parsed."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files =file1.py,file2.py,file3.py
"""
)

options = Options()

parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertEqual(options.files, ["file1.py", "file2.py", "file3.py"])

def test_parse_config_file_with_extra_spaces(self):
"""Files with extra spaces should be correctly parsed."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files = file1.py , file2.py , file3.py
"""
)

options = Options()

parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertEqual(options.files, ["file1.py", "file2.py", "file3.py"])

def test_parse_config_file_with_empty_files_key(self):
"""An empty files key should result in an empty list."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files =
"""
)

options = Options()

parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertEqual(options.files, [])

def test_parse_config_file_with_only_comma(self):
"""A files key with only a comma should raise an error."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files = ,
"""
)

options = Options()

with self.assertRaises(ValueError) as cm:
parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertIn("Invalid config", str(cm.exception))

def test_parse_config_file_with_only_whitespace(self):
"""A files key with only whitespace should result in an empty list."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files =
"""
)

options = Options()

parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertEqual(options.files, [])

def test_parse_config_file_with_mixed_valid_and_invalid_entries(self):
"""Mix of valid and invalid filenames should raise an error."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files = file1.py, , , file2.py
"""
)

options = Options()

with self.assertRaises(ValueError) as cm:
parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertIn("Invalid config", str(cm.exception))

def test_parse_config_file_with_newlines_between_files(self):
"""Newlines between file entries should be correctly handled."""
with tempfile.TemporaryDirectory() as tmpdirname:
config_path = os.path.join(tmpdirname, "test_config.ini")

with open(config_path, "w") as f:
f.write(
"""
[mypy]
files = file1.py,
file2.py,
file3.py
"""
)

options = Options()

parse_config_file(
options,
lambda: None,
config_path,
stdout=None,
stderr=None,
)

self.assertEqual(options.files, ["file1.py", "file2.py", "file3.py"])

if __name__ == "__main__":
main()