All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
1 from functools import lru_cache
4 from pathlib import Path
20 from pathspec import PathSpec
21 from pathspec.patterns.gitwildmatch import GitWildMatchPatternError
24 from black.output import err
25 from black.report import Report
26 from black.handle_ipynb_magics import jupyter_dependencies_are_installed
29 import colorama # noqa: F401
33 def find_project_root(srcs: Sequence[str]) -> Path:
34 """Return a directory containing .git, .hg, or pyproject.toml.
36 That directory will be a common parent of all files and directories
39 If no directory in the tree contains a marker that would specify it's the
40 project root, the root of the file system is returned.
43 srcs = [str(Path.cwd().resolve())]
45 path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs]
47 # A list of lists of parents for each 'src'. 'src' is included as a
48 # "parent" of itself if it is a directory
50 list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs
54 set.intersection(*(set(parents) for parents in src_parents)),
55 key=lambda path: path.parts,
58 for directory in (common_base, *common_base.parents):
59 if (directory / ".git").exists():
62 if (directory / ".hg").is_dir():
65 if (directory / "pyproject.toml").is_file():
71 def find_pyproject_toml(path_search_start: Tuple[str, ...]) -> Optional[str]:
72 """Find the absolute filepath to a pyproject.toml if it exists"""
73 path_project_root = find_project_root(path_search_start)
74 path_pyproject_toml = path_project_root / "pyproject.toml"
75 if path_pyproject_toml.is_file():
76 return str(path_pyproject_toml)
79 path_user_pyproject_toml = find_user_pyproject_toml()
81 str(path_user_pyproject_toml)
82 if path_user_pyproject_toml.is_file()
85 except PermissionError as e:
86 # We do not have access to the user-level config directory, so ignore it.
87 err(f"Ignoring user configuration directory due to {e!r}")
91 def parse_pyproject_toml(path_config: str) -> Dict[str, Any]:
92 """Parse a pyproject toml file, pulling out relevant parts for Black
94 If parsing fails, will raise a tomli.TOMLDecodeError
96 with open(path_config, encoding="utf8") as f:
97 pyproject_toml = tomli.load(f) # type: ignore # due to deprecated API usage
98 config = pyproject_toml.get("tool", {}).get("black", {})
99 return {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
103 def find_user_pyproject_toml() -> Path:
104 r"""Return the path to the top-level user configuration for black.
106 This looks for ~\.black on Windows and ~/.config/black on Linux and other
109 if sys.platform == "win32":
111 user_config_path = Path.home() / ".black"
113 config_root = os.environ.get("XDG_CONFIG_HOME", "~/.config")
114 user_config_path = Path(config_root).expanduser() / "black"
115 return user_config_path.resolve()
119 def get_gitignore(root: Path) -> PathSpec:
120 """Return a PathSpec matching gitignore content if present."""
121 gitignore = root / ".gitignore"
122 lines: List[str] = []
123 if gitignore.is_file():
124 with gitignore.open(encoding="utf-8") as gf:
125 lines = gf.readlines()
127 return PathSpec.from_lines("gitwildmatch", lines)
128 except GitWildMatchPatternError as e:
129 err(f"Could not parse {gitignore}: {e}")
133 def normalize_path_maybe_ignore(
134 path: Path, root: Path, report: Report
136 """Normalize `path`. May return `None` if `path` was ignored.
138 `report` is where "path ignored" output goes.
141 abspath = path if path.is_absolute() else Path.cwd() / path
142 normalized_path = abspath.resolve().relative_to(root).as_posix()
144 report.path_ignored(path, f"cannot be read because {e}")
148 if path.is_symlink():
149 report.path_ignored(path, f"is a symbolic link that points outside {root}")
154 return normalized_path
157 def path_is_excluded(
158 normalized_path: str,
159 pattern: Optional[Pattern[str]],
161 match = pattern.search(normalized_path) if pattern else None
162 return bool(match and match.group(0))
165 def gen_python_files(
166 paths: Iterable[Path],
168 include: Pattern[str],
169 exclude: Pattern[str],
170 extend_exclude: Optional[Pattern[str]],
171 force_exclude: Optional[Pattern[str]],
173 gitignore: Optional[PathSpec],
178 """Generate all files under `path` whose paths are not excluded by the
179 `exclude_regex`, `extend_exclude`, or `force_exclude` regexes,
180 but are included by the `include` regex.
182 Symbolic links pointing outside of the `root` directory are ignored.
184 `report` is where output about exclusions goes.
186 assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
188 normalized_path = normalize_path_maybe_ignore(child, root, report)
189 if normalized_path is None:
192 # First ignore files matching .gitignore, if passed
193 if gitignore is not None and gitignore.match_file(normalized_path):
194 report.path_ignored(child, "matches the .gitignore file content")
197 # Then ignore with `--exclude` `--extend-exclude` and `--force-exclude` options.
198 normalized_path = "/" + normalized_path
200 normalized_path += "/"
202 if path_is_excluded(normalized_path, exclude):
203 report.path_ignored(child, "matches the --exclude regular expression")
206 if path_is_excluded(normalized_path, extend_exclude):
208 child, "matches the --extend-exclude regular expression"
212 if path_is_excluded(normalized_path, force_exclude):
213 report.path_ignored(child, "matches the --force-exclude regular expression")
217 # If gitignore is None, gitignore usage is disabled, while a Falsey
218 # gitignore is when the directory doesn't have a .gitignore file.
219 yield from gen_python_files(
227 gitignore + get_gitignore(child) if gitignore is not None else None,
232 elif child.is_file():
233 if child.suffix == ".ipynb" and not jupyter_dependencies_are_installed(
234 verbose=verbose, quiet=quiet
237 include_match = include.search(normalized_path) if include else True
242 def wrap_stream_for_windows(
244 ) -> Union[io.TextIOWrapper, "colorama.AnsiToWin32"]:
246 Wrap stream with colorama's wrap_stream so colors are shown on Windows.
248 If `colorama` is unavailable, the original stream is returned unmodified.
249 Otherwise, the `wrap_stream()` function determines whether the stream needs
250 to be wrapped for a Windows environment and will accordingly either return
251 an `AnsiToWin32` wrapper or the original stream.
254 from colorama.initialise import wrap_stream
258 # Set `strip=False` to avoid needing to modify test_express_diff_with_color.
259 return wrap_stream(f, convert=None, strip=False, autoreset=False, wrap=True)