Coverage for src/su6_plugin_svelte_check/find_project_root.py: 100%

18 statements  

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

1""" 

2Modified from black.files. 

3""" 

4from functools import lru_cache 

5from pathlib import Path 

6from typing import Optional, Sequence, Tuple 

7 

8 

9@lru_cache() 

10def find_project_root(srcs: Sequence[str], stdin_filename: Optional[str] = None) -> Tuple[Path, str]: 

11 """ 

12 Return a directory containing .git, .hg, or pyproject.toml. 

13 

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

15 passed in `srcs`. 

16 

17 If no directory in the tree contains a marker that would specify it's the 

18 project root, the root of the file system is returned. 

19 

20 Returns a two-tuple with the first element as the project root path and 

21 the second element as a string describing the method by which the 

22 project root was discovered. 

23 """ 

24 if stdin_filename is not None: 

25 srcs = tuple(stdin_filename if s == "-" else s for s in srcs) 

26 if not srcs: 

27 srcs = [str(Path.cwd().resolve())] 

28 

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

30 

31 # A list of lists of parents for each 'src'. 'src' is included as a 

32 # "parent" of itself if it is a directory 

33 src_parents = [list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs] 

34 

35 common_base = max( 

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

37 key=lambda path: path.parts, 

38 ) 

39 

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

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

42 return directory, "node_modules" 

43 

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

45 return directory, ".git directory" 

46 

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

48 return directory, ".hg directory" 

49 

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

51 return directory, "pyproject.toml" 

52 

53 return directory, "file system root"