Debian Codegraph @

test/lib/ansible_test/_internal/provider/source/git.py

raw
1 """Source provider for a content root managed by git version control."""
2
3 from __future__ import annotations
4
5 import os
6
7 from ...git import (
8 Git,
9 )
10
11 from ...encoding import (
12 to_bytes,
13 )
14
15 from ...util import (
16 SubprocessError,
17 display,
18 )
19
20 from . import (
21 SourceProvider,
22 )
23
24
25 class GitSource(SourceProvider):
26 """Source provider for a content root managed by git version control."""
27
28 @staticmethod
29 def is_content_root(path: str) -> bool:
30 """Return True if the given path is a content root for this provider."""
31 return os.path.exists(os.path.join(path, '.git'))
32
33 def get_paths(self, path: str) -> list[str]:
34 """Return the list of available content paths under the given path."""
35 paths = self.__get_paths(path)
36
37 try:
38 submodule_paths = Git(path).get_submodule_paths()
39 except SubprocessError:
40 if path == self.root:
41 raise
42
43 # older versions of git require submodule commands to be executed from the top level of the working tree
44 # git version 2.18.1 (centos8) does not have this restriction
45 # git version 1.8.3.1 (centos7) does
46 # fall back to using the top level directory of the working tree only when needed
47 # this avoids penalizing newer git versions with a potentially slower analysis due to additional submodules
48 rel_path = os.path.relpath(path, self.root) + os.path.sep
49
50 submodule_paths = Git(self.root).get_submodule_paths()
51 submodule_paths = [os.path.relpath(p, rel_path) for p in submodule_paths if p.startswith(rel_path)]
52
53 for submodule_path in submodule_paths:
54 submodule_full_path = os.path.join(path, submodule_path)
55
56 if not os.path.exists(submodule_full_path):
57 display.warning(f"Missing submodule: {submodule_path}")
58 continue
59
60 paths.extend(os.path.join(submodule_path, p) for p in self.__get_paths(submodule_full_path))
61
62 # git reports submodule directories as regular files
63 paths = [p for p in paths if p not in submodule_paths]
64
65 return paths
66
67 @staticmethod
68 def __get_paths(path: str) -> list[str]:
69 """Return the list of available content paths under the given path."""
70 git = Git(path)
71 paths = git.get_file_names(['--cached', '--others', '--exclude-standard'])
72 deleted_paths = git.get_file_names(['--deleted'])
73 paths = sorted(set(paths) - set(deleted_paths))
74
75 # directory symlinks are reported by git as regular files but they need to be treated as directories
76 paths = [path + os.path.sep if os.path.isdir(to_bytes(path)) else path for path in paths]
77
78 return paths