Coverage for src/su6_plugin_svelte_check/helpers.py: 100%
22 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-17 18:17 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-17 18:17 +0200
1"""
2Re-usable helpers for this project.
3"""
5import contextlib
6from functools import lru_cache
7from pathlib import Path
8from typing import Optional, Sequence, Tuple
10try:
11 chdir = contextlib.chdir
12except AttributeError: # pragma: no cover
13 from contextlib_chdir import chdir # type: ignore
16@lru_cache()
17def find_project_root(srcs: Sequence[str], stdin_filename: Optional[str] = None) -> Tuple[Path, str]:
18 """
19 Return a directory containing .git, .hg, or pyproject.toml.
21 That directory will be a common parent of all files and directories
22 passed in `srcs`.
24 If no directory in the tree contains a marker that would specify it's the
25 project root, the root of the file system is returned.
27 Returns a two-tuple with the first element as the project root path and
28 the second element as a string describing the method by which the
29 project root was discovered.
31 Modified from black.files.
32 """
33 if stdin_filename is not None:
34 srcs = tuple(stdin_filename if s == "-" else s for s in srcs)
35 if not srcs:
36 srcs = [str(Path.cwd().resolve())]
38 path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs]
40 # A list of lists of parents for each 'src'. 'src' is included as a
41 # "parent" of itself if it is a directory
42 src_parents = [list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs]
44 common_base = max(
45 set.intersection(*(set(parents) for parents in src_parents)),
46 key=lambda path: path.parts,
47 )
49 for directory in (common_base, *common_base.parents):
50 if (directory / "node_modules").exists():
51 return directory, "node_modules"
53 if (directory / ".git").exists():
54 return directory, ".git directory"
56 if (directory / ".hg").is_dir(): # pragma: no cover
57 return directory, ".hg directory"
59 if (directory / "pyproject.toml").is_file(): # pragma: no cover
60 return directory, "pyproject.toml"
62 return directory, "file system root"
65__all__ = ["chdir", "find_project_root"]