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
23 from black.output import err
24 from black.report import Report
27 import colorama # noqa: F401
31 def find_project_root(srcs: Sequence[str]) -> Path:
32 """Return a directory containing .git, .hg, or pyproject.toml.
34 That directory will be a common parent of all files and directories
37 If no directory in the tree contains a marker that would specify it's the
38 project root, the root of the file system is returned.
41 return Path("/").resolve()
43 path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs]
45 # A list of lists of parents for each 'src'. 'src' is included as a
46 # "parent" of itself if it is a directory
48 list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs
52 set.intersection(*(set(parents) for parents in src_parents)),
53 key=lambda path: path.parts,
56 for directory in (common_base, *common_base.parents):
57 if (directory / ".git").exists():
60 if (directory / ".hg").is_dir():
63 if (directory / "pyproject.toml").is_file():
69 def find_pyproject_toml(path_search_start: Tuple[str, ...]) -> Optional[str]:
70 """Find the absolute filepath to a pyproject.toml if it exists"""
71 path_project_root = find_project_root(path_search_start)
72 path_pyproject_toml = path_project_root / "pyproject.toml"
73 if path_pyproject_toml.is_file():
74 return str(path_pyproject_toml)
77 path_user_pyproject_toml = find_user_pyproject_toml()
79 str(path_user_pyproject_toml)
80 if path_user_pyproject_toml.is_file()
83 except PermissionError as e:
84 # We do not have access to the user-level config directory, so ignore it.
85 err(f"Ignoring user configuration directory due to {e!r}")
89 def parse_pyproject_toml(path_config: str) -> Dict[str, Any]:
90 """Parse a pyproject toml file, pulling out relevant parts for Black
92 If parsing fails, will raise a toml.TomlDecodeError
94 pyproject_toml = toml.load(path_config)
95 config = pyproject_toml.get("tool", {}).get("black", {})
96 return {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
100 def find_user_pyproject_toml() -> Path:
101 r"""Return the path to the top-level user configuration for black.
103 This looks for ~\.black on Windows and ~/.config/black on Linux and other
106 if sys.platform == "win32":
108 user_config_path = Path.home() / ".black"
110 config_root = os.environ.get("XDG_CONFIG_HOME", "~/.config")
111 user_config_path = Path(config_root).expanduser() / "black"
112 return user_config_path.resolve()
116 def get_gitignore(root: Path) -> PathSpec:
117 """Return a PathSpec matching gitignore content if present."""
118 gitignore = root / ".gitignore"
119 lines: List[str] = []
120 if gitignore.is_file():
121 with gitignore.open(encoding="utf-8") as gf:
122 lines = gf.readlines()
123 return PathSpec.from_lines("gitwildmatch", lines)
126 def normalize_path_maybe_ignore(
127 path: Path, root: Path, report: Report
129 """Normalize `path`. May return `None` if `path` was ignored.
131 `report` is where "path ignored" output goes.
134 abspath = path if path.is_absolute() else Path.cwd() / path
135 normalized_path = abspath.resolve().relative_to(root).as_posix()
137 report.path_ignored(path, f"cannot be read because {e}")
141 if path.is_symlink():
142 report.path_ignored(path, f"is a symbolic link that points outside {root}")
147 return normalized_path
150 def path_is_excluded(
151 normalized_path: str,
152 pattern: Optional[Pattern[str]],
154 match = pattern.search(normalized_path) if pattern else None
155 return bool(match and match.group(0))
158 def gen_python_files(
159 paths: Iterable[Path],
161 include: Pattern[str],
162 exclude: Pattern[str],
163 extend_exclude: Optional[Pattern[str]],
164 force_exclude: Optional[Pattern[str]],
166 gitignore: Optional[PathSpec],
168 """Generate all files under `path` whose paths are not excluded by the
169 `exclude_regex`, `extend_exclude`, or `force_exclude` regexes,
170 but are included by the `include` regex.
172 Symbolic links pointing outside of the `root` directory are ignored.
174 `report` is where output about exclusions goes.
176 assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
178 normalized_path = normalize_path_maybe_ignore(child, root, report)
179 if normalized_path is None:
182 # First ignore files matching .gitignore, if passed
183 if gitignore is not None and gitignore.match_file(normalized_path):
184 report.path_ignored(child, "matches the .gitignore file content")
187 # Then ignore with `--exclude` `--extend-exclude` and `--force-exclude` options.
188 normalized_path = "/" + normalized_path
190 normalized_path += "/"
192 if path_is_excluded(normalized_path, exclude):
193 report.path_ignored(child, "matches the --exclude regular expression")
196 if path_is_excluded(normalized_path, extend_exclude):
198 child, "matches the --extend-exclude regular expression"
202 if path_is_excluded(normalized_path, force_exclude):
203 report.path_ignored(child, "matches the --force-exclude regular expression")
207 # If gitignore is None, gitignore usage is disabled, while a Falsey
208 # gitignore is when the directory doesn't have a .gitignore file.
209 yield from gen_python_files(
217 gitignore + get_gitignore(child) if gitignore is not None else None,
220 elif child.is_file():
221 include_match = include.search(normalized_path) if include else True
226 def wrap_stream_for_windows(
228 ) -> Union[io.TextIOWrapper, "colorama.AnsiToWin32"]:
230 Wrap stream with colorama's wrap_stream so colors are shown on Windows.
232 If `colorama` is unavailable, the original stream is returned unmodified.
233 Otherwise, the `wrap_stream()` function determines whether the stream needs
234 to be wrapped for a Windows environment and will accordingly either return
235 an `AnsiToWin32` wrapper or the original stream.
238 from colorama.initialise import wrap_stream
242 # Set `strip=False` to avoid needing to modify test_express_diff_with_color.
243 return wrap_stream(f, convert=None, strip=False, autoreset=False, wrap=True)