Skip to content

Commit

Permalink
Throwing a more descriptive warning when reading a bad .gitignore
Browse files Browse the repository at this point in the history
A particularly unhelpful error was thrown before, I feel this will
be a lot more helpful to users trying to understand what went wrong.
  • Loading branch information
john-science committed Aug 19, 2021
1 parent ef7c45f commit c805a6a
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- Add support for formatting Jupyter Notebook files (#2357)
- Move from `appdirs` dependency to `platformdirs` (#2375)
- Fix opaque error when parsing invalid .gitignore (#2433)

### Integrations

Expand Down
6 changes: 5 additions & 1 deletion src/black/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,11 @@ def get_gitignore(root: Path) -> PathSpec:
if gitignore.is_file():
with gitignore.open(encoding="utf-8") as gf:
lines = gf.readlines()
return PathSpec.from_lines("gitwildmatch", lines)

try:
return PathSpec.from_lines("gitwildmatch", lines)
except (IndexError, ValueError, TypeError) as e:
raise SyntaxError("Problem parsing .gitignore file: {0}".format(e))


def normalize_path_maybe_ignore(
Expand Down
12 changes: 12 additions & 0 deletions tests/data/broken_gitignore_test/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# No non-source python resources.
*.pyc
*.pyo
*.pyd
*.pyx

# This should break things
!

# No build artifacts
build
wheelhouse
5 changes: 5 additions & 0 deletions tests/test_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -1727,6 +1727,11 @@ def test_nested_gitignore(self) -> None:
)
self.assertEqual(sorted(expected), sorted(sources))

def test_broken_gitignore(self) -> None:
path = Path(THIS_DIR / "data" / "broken_gitignore_test")
with self.assertRaises(SyntaxError):
_ = black.files.get_gitignore(path)

def test_empty_include(self) -> None:
path = THIS_DIR / "data" / "include_exclude_tests"
report = black.Report()
Expand Down

0 comments on commit c805a6a

Please sign in to comment.