Coverage for src/su6_plugin_prettier/helpers.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-17 18:52 +0200

1""" 

2Re-usable helpers for this project. 

3""" 

4 

5import contextlib 

6from functools import lru_cache 

7from pathlib import Path 

8from typing import Optional, Sequence, Tuple 

9 

10try: 

11 chdir = contextlib.chdir 

12except AttributeError: # pragma: no cover 

13 from contextlib_chdir import chdir # type: ignore 

14 

15 

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. 

20 

21 That directory will be a common parent of all files and directories 

22 passed in `srcs`. 

23 

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. 

26 

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. 

30 

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())] 

37 

38 path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs] 

39 

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] 

43 

44 common_base = max( 

45 set.intersection(*(set(parents) for parents in src_parents)), 

46 key=lambda path: path.parts, 

47 ) 

48 

49 for directory in (common_base, *common_base.parents): 

50 if (directory / "node_modules").exists(): 

51 return directory, "node_modules" 

52 

53 if (directory / ".git").exists(): 

54 return directory, ".git directory" 

55 

56 if (directory / ".hg").is_dir(): # pragma: no cover 

57 return directory, ".hg directory" 

58 

59 if (directory / "pyproject.toml").is_file(): # pragma: no cover 

60 return directory, "pyproject.toml" 

61 

62 return directory, "file system root" 

63 

64 

65__all__ = ["chdir", "find_project_root"]