Debian Codegraph @

test/lib/ansible_test/_internal/git.py

raw
1 """Wrapper around git command-line tools."""
2
3 from __future__ import annotations
4
5 import re
6 import typing as t
7
8 from .util import (
9 SubprocessError,
10 raw_command,
11 )
12
13
14 class Git:
15 """Wrapper around git command-line tools."""
16
17 def __init__(self, root: t.Optional[str] = None) -> None:
18 self.git = 'git'
19 self.root = root
20
21 def get_diff(self, args: list[str], git_options: t.Optional[list[str]] = None) -> list[str]:
22 """Run `git diff` and return the result as a list."""
23 cmd = ['diff'] + args
24 if git_options is None:
25 git_options = ['-c', 'core.quotePath=']
26 return self.run_git_split(git_options + cmd, '\n', str_errors='replace')
27
28 def get_diff_names(self, args: list[str]) -> list[str]:
29 """Return a list of file names from the `git diff` command."""
30 cmd = ['diff', '--name-only', '--no-renames', '-z'] + args
31 return self.run_git_split(cmd, '\0')
32
33 def get_submodule_paths(self) -> list[str]:
34 """Return a list of submodule paths recursively."""
35 cmd = ['submodule', 'status', '--recursive']
36 output = self.run_git_split(cmd, '\n')
37 submodule_paths = [re.search(r'^.[0-9a-f]+ (?P<path>[^ ]+)', line).group('path') for line in output]
38
39 # status is returned for all submodules in the current git repository relative to the current directory
40 # when the current directory is not the root of the git repository this can yield relative paths which are not below the current directory
41 # this can occur when multiple collections are in a git repo and some collections are submodules when others are not
42 # specifying "." as the path to enumerate would limit results to the current directory, but can cause the git command to fail with the error:
43 # error: pathspec '.' did not match any file(s) known to git
44 # this can occur when the current directory contains no files tracked by git
45 # instead we'll filter out the relative paths, since we're only interested in those at or below the current directory
46 submodule_paths = [path for path in submodule_paths if not path.startswith('../')]
47
48 return submodule_paths
49
50 def get_file_names(self, args: list[str]) -> list[str]:
51 """Return a list of file names from the `git ls-files` command."""
52 cmd = ['ls-files', '-z'] + args
53 return self.run_git_split(cmd, '\0')
54
55 def get_branches(self) -> list[str]:
56 """Return the list of branches."""
57 cmd = ['for-each-ref', 'refs/heads/', '--format', '%(refname:strip=2)']
58 return self.run_git_split(cmd)
59
60 def get_branch(self) -> str:
61 """Return the current branch name."""
62 cmd = ['symbolic-ref', '--short', 'HEAD']
63 return self.run_git(cmd).strip()
64
65 def get_rev_list(self, commits: t.Optional[list[str]] = None, max_count: t.Optional[int] = None) -> list[str]:
66 """Return the list of results from the `git rev-list` command."""
67 cmd = ['rev-list']
68
69 if commits:
70 cmd += commits
71 else:
72 cmd += ['HEAD']
73
74 if max_count:
75 cmd += ['--max-count', '%s' % max_count]
76
77 return self.run_git_split(cmd)
78
79 def get_branch_fork_point(self, branch: str) -> str:
80 """Return a reference to the point at which the given branch was forked."""
81 cmd = ['merge-base', branch, 'HEAD']
82 return self.run_git(cmd).strip()
83
84 def is_valid_ref(self, ref: str) -> bool:
85 """Return True if the given reference is valid, otherwise return False."""
86 cmd = ['show', ref]
87 try:
88 self.run_git(cmd, str_errors='replace')
89 return True
90 except SubprocessError:
91 return False
92
93 def run_git_split(self, cmd: list[str], separator: t.Optional[str] = None, str_errors: str = 'strict') -> list[str]:
94 """Run the given `git` command and return the results as a list."""
95 output = self.run_git(cmd, str_errors=str_errors).strip(separator)
96
97 if not output:
98 return []
99
100 return output.split(separator)
101
102 def run_git(self, cmd: list[str], str_errors: str = 'strict') -> str:
103 """Run the given `git` command and return the results as a string."""
104 return raw_command([self.git] + cmd, cwd=self.root, capture=True, str_errors=str_errors)[0]