Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/vcs.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5
6 import logging
7 import os
8 import re
9 import subprocess
10 from abc import ABC, abstractmethod
11 from shutil import which
12 from typing import List, Optional
13
14 from taskgraph.util.path import ancestors
15
16 PUSHLOG_TMPL = "{}/json-pushes?version=2&changeset={}&tipsonly=1&full=1"
17
18 logger = logging.getLogger(__name__)
19
20
21 class Repository(ABC):
22 # Both mercurial and git use sha1 as revision identifiers. Luckily, both define
23 # the same value as the null revision.
24 #
25 # https://github.com/git/git/blob/dc04167d378fb29d30e1647ff6ff51dd182bc9a3/t/oid-info/hash-info#L7
26 # https://www.mercurial-scm.org/repo/hg-stable/file/82efc31bd152/mercurial/node.py#l30
27 NULL_REVISION = "0000000000000000000000000000000000000000"
28
29 def __init__(self, path):
30 self.path = path
31 self.binary = which(self.tool)
32 if self.binary is None:
33 raise OSError(f"{self.tool} not found!")
34 self._valid_diff_filter = ("m", "a", "d")
35
36 self._env = os.environ.copy()
37
38 def run(self, *args: str, **kwargs) -> str:
39 return_codes = kwargs.pop("return_codes", [])
40 cmd = (self.binary,) + args
41
42 try:
43 return subprocess.check_output( # type: ignore
44 cmd, # type: ignore
45 cwd=self.path,
46 env=self._env,
47 encoding="utf-8",
48 **kwargs,
49 )
50 except subprocess.CalledProcessError as e:
51 if e.returncode in return_codes:
52 return ""
53 raise
54
55 @property
56 @abstractmethod
57 def tool(self) -> str:
58 """Version control system being used, either 'hg' or 'git'."""
59
60 @property
61 @abstractmethod
62 def head_rev(self) -> str:
63 """Hash of HEAD revision."""
64
65 @property
66 @abstractmethod
67 def base_rev(self) -> str:
68 """Hash of revision the current topic branch is based on."""
69
70 @property
71 @abstractmethod
72 def branch(self) -> Optional[str]:
73 """Current branch or bookmark the checkout has active."""
74
75 @property
76 @abstractmethod
77 def all_remote_names(self) -> List[str]:
78 """Name of all configured remote repositories."""
79
80 @property
81 @abstractmethod
82 def default_remote_name(self) -> str:
83 """Name the VCS defines for the remote repository when cloning
84 it for the first time. This name may not exist anymore if users
85 changed the default configuration, for instance."""
86
87 @property
88 @abstractmethod
89 def remote_name(self) -> str:
90 """Name of the remote repository."""
91
92 def _get_most_suitable_remote(self, remote_instructions) -> str:
93 remotes = self.all_remote_names
94
95 # in case all_remote_names raised a RuntimeError
96 if remotes is None:
97 raise RuntimeError("No valid remotes found")
98
99 if len(remotes) == 1:
100 return remotes[0]
101
102 if self.default_remote_name in remotes:
103 return self.default_remote_name
104
105 first_remote = remotes[0]
106 logger.warning(
107 f"Unable to determine which remote repository to use between: {remotes}. "
108 f'Arbitrarily using the first one "{first_remote}". Please set an '
109 f"`{self.default_remote_name}` remote if the arbitrarily selected one "
110 f"is not right. To do so: {remote_instructions}"
111 )
112
113 return first_remote
114
115 @property
116 @abstractmethod
117 def default_branch(self) -> str:
118 """Name of the default branch."""
119
120 @abstractmethod
121 def get_url(self, remote: Optional[str]) -> str:
122 """Get URL of the upstream repository."""
123
124 @abstractmethod
125 def get_commit_message(self, revision: Optional[str]) -> str:
126 """Commit message of specified revision or current commit."""
127
128 @abstractmethod
129 def get_tracked_files(self, *paths: str, rev: Optional[str] = None) -> List[str]:
130 """Return list of tracked files.
131
132 ``*paths`` are path specifiers to limit results to.
133 ``rev`` is a revision specifier at which to retrieve the files.
134 Defaults to the parent of the working copy if unspecified.
135 """
136
137 @abstractmethod
138 def get_changed_files(
139 self,
140 diff_filter: Optional[str],
141 mode: Optional[str],
142 rev: Optional[str],
143 base_rev: Optional[str],
144 ) -> List[str]:
145 """Return a list of files that are changed in:
146 * either this repository's working copy,
147 * or at a given revision (``rev``)
148 * or between 2 revisions (``base_rev`` and ``rev``)
149
150 ``diff_filter`` controls which kinds of modifications are returned.
151 It is a string which may only contain the following characters:
152
153 A - Include files that were added
154 D - Include files that were deleted
155 M - Include files that were modified
156
157 By default, all three will be included.
158
159 ``mode`` can be one of 'unstaged', 'staged' or 'all'. Only has an
160 effect on git. Defaults to 'unstaged'.
161
162 ``rev`` is a specifier for which changesets to consider for
163 changes. The exact meaning depends on the vcs system being used.
164
165 ``base_rev`` specifies the range of changesets. This parameter cannot
166 be used without ``rev``. The range includes ``rev`` but excludes
167 ``base_rev``.
168 """
169
170 @abstractmethod
171 def get_outgoing_files(self, diff_filter: str, upstream: str) -> List[str]:
172 """Return a list of changed files compared to upstream.
173
174 ``diff_filter`` works the same as `get_changed_files`.
175 ``upstream`` is a remote ref to compare against. If unspecified,
176 this will be determined automatically. If there is no remote ref,
177 a MissingUpstreamRepo exception will be raised.
178 """
179
180 @abstractmethod
181 def working_directory_clean(
182 self, untracked: Optional[bool] = False, ignored: Optional[bool] = False
183 ) -> bool:
184 """Determine if the working directory is free of modifications.
185
186 Returns True if the working directory does not have any file
187 modifications. False otherwise.
188
189 By default, untracked and ignored files are not considered. If
190 ``untracked`` or ``ignored`` are set, they influence the clean check
191 to factor these file classes into consideration.
192 """
193
194 @abstractmethod
195 def update(self, ref: str) -> None:
196 """Update the working directory to the specified reference."""
197
198 @abstractmethod
199 def find_latest_common_revision(self, base_ref_or_rev: str, head_rev: str) -> str:
200 """Find the latest revision that is common to both the given
201 ``head_rev`` and ``base_ref_or_rev``.
202
203 If no common revision exists, ``Repository.NULL_REVISION`` will
204 be returned."""
205
206 @abstractmethod
207 def does_revision_exist_locally(self, revision: str) -> bool:
208 """Check whether this revision exists in the local repository.
209
210 If this function returns an unexpected value, then make sure
211 the revision was fetched from the remote repository."""
212
213
214 class HgRepository(Repository):
215 @property
216 def tool(self) -> str:
217 return "hg"
218
219 @property
220 def default_remote_name(self) -> str:
221 return "default"
222
223 def __init__(self, *args, **kwargs):
224 super().__init__(*args, **kwargs)
225 self._env["HGPLAIN"] = "1"
226
227 @property
228 def head_rev(self):
229 return self.run("log", "-r", ".", "-T", "{node}").strip()
230
231 @property
232 def base_rev(self):
233 return self.run("log", "-r", "last(ancestors(.) and public())", "-T", "{node}")
234
235 @property
236 def branch(self):
237 bookmarks_fn = os.path.join(self.path, ".hg", "bookmarks.current")
238 if os.path.exists(bookmarks_fn):
239 with open(bookmarks_fn) as f:
240 bookmark = f.read()
241 return bookmark or None
242
243 return None
244
245 @property
246 def all_remote_names(self):
247 remotes = self.run("paths", "--quiet").splitlines()
248 if not remotes:
249 raise RuntimeError("No remotes defined")
250 return remotes
251
252 @property
253 def remote_name(self):
254 return self._get_most_suitable_remote(
255 "Edit .hg/hgrc and add:\n\n[paths]\ndefault = $URL",
256 )
257
258 @property
259 def default_branch(self):
260 # Mercurial recommends keeping "default"
261 # https://www.mercurial-scm.org/wiki/StandardBranching#Don.27t_use_a_name_other_than_default_for_your_main_development_branch
262 return "default"
263
264 def get_url(self, remote=None):
265 remote = remote or "default"
266 return self.run("path", "-T", "{url}", remote).strip()
267
268 def get_commit_message(self, revision=None):
269 revision = revision or "."
270 return self.run("log", "-r", revision, "-T", "{desc}")
271
272 def _format_diff_filter(self, diff_filter, for_status=False):
273 df = diff_filter.lower()
274 assert all(f in self._valid_diff_filter for f in df)
275
276 # When looking at the changes in the working directory, the hg status
277 # command uses 'd' for files that have been deleted with a non-hg
278 # command, and 'r' for files that have been `hg rm`ed. Use both.
279 return df.replace("d", "dr") if for_status else df
280
281 def _files_template(self, diff_filter):
282 template = ""
283 df = self._format_diff_filter(diff_filter)
284 if "a" in df:
285 template += "{file_adds % '{file}\\n'}"
286 if "d" in df:
287 template += "{file_dels % '{file}\\n'}"
288 if "m" in df:
289 template += "{file_mods % '{file}\\n'}"
290 return template
291
292 def get_tracked_files(self, *paths, rev=None):
293 rev = rev or "."
294 return self.run("files", "-r", rev, *paths).splitlines()
295
296 def get_changed_files(self, diff_filter=None, mode=None, rev=None, base_rev=None):
297 diff_filter = diff_filter or "ADM"
298 if rev is None:
299 if base_rev is not None:
300 raise ValueError("Cannot specify `base_rev` without `rev`")
301 # Use --no-status to print just the filename.
302 df = self._format_diff_filter(diff_filter, for_status=True)
303 return self.run("status", "--no-status", f"-{df}").splitlines()
304 else:
305 template = self._files_template(diff_filter)
306 revision_argument = rev if base_rev is None else f"{rev} % {base_rev}"
307 return self.run("log", "-r", revision_argument, "-T", template).splitlines()
308
309 def get_outgoing_files(self, diff_filter="ADM", upstream=None):
310 template = self._files_template(diff_filter)
311
312 if not upstream:
313 return self.run(
314 "log", "-r", "draft() and ancestors(.)", "--template", template
315 ).split()
316
317 return self.run(
318 "outgoing",
319 "-r",
320 ".",
321 "--quiet",
322 "--template",
323 template,
324 upstream,
325 return_codes=(1,),
326 ).split()
327
328 def working_directory_clean(self, untracked=False, ignored=False):
329 args = ["status", "--modified", "--added", "--removed", "--deleted"]
330 if untracked:
331 args.append("--unknown")
332 if ignored:
333 args.append("--ignored")
334
335 # If output is empty, there are no entries of requested status, which
336 # means we are clean.
337 return not len(self.run(*args).strip())
338
339 def update(self, ref):
340 self.run("update", "--check", ref)
341
342 def find_latest_common_revision(self, base_ref_or_rev, head_rev):
343 ancestor = self.run(
344 "log",
345 "-r",
346 f"last(ancestors('{base_ref_or_rev}') and ancestors('{head_rev}'))",
347 "--template",
348 "{node}",
349 ).strip()
350 return ancestor or self.NULL_REVISION
351
352 def does_revision_exist_locally(self, revision):
353 try:
354 return bool(self.run("log", "-r", revision).strip())
355 except subprocess.CalledProcessError as e:
356 # Error code 255 comes with the message:
357 # "abort: unknown revision $REVISION"
358 if e.returncode == 255:
359 return False
360 raise
361
362
363 class GitRepository(Repository):
364 @property
365 def tool(self) -> str:
366 return "git"
367
368 @property
369 def default_remote_name(self) -> str:
370 return "origin"
371
372 _LS_REMOTE_PATTERN = re.compile(r"ref:\s+refs/heads/(?P<branch_name>\S+)\s+HEAD")
373
374 @property
375 def head_rev(self):
376 return self.run("rev-parse", "--verify", "HEAD").strip()
377
378 @property
379 def base_rev(self):
380 refs = self.run(
381 "rev-list", "HEAD", "--topo-order", "--boundary", "--not", "--remotes"
382 ).splitlines()
383 if refs:
384 return refs[-1][1:] # boundary starts with a prefix `-`
385 return self.head_rev
386
387 @property
388 def branch(self):
389 return self.run("branch", "--show-current").strip() or None
390
391 @property
392 def all_remote_names(self):
393 remotes = self.run("remote").splitlines()
394 if not remotes:
395 raise RuntimeError("No remotes defined")
396 return remotes
397
398 @property
399 def remote_name(self):
400 try:
401 remote_branch_name = self.run(
402 "rev-parse",
403 "--verify",
404 "--abbrev-ref",
405 "--symbolic-full-name",
406 "@{u}",
407 stderr=subprocess.PIPE,
408 ).strip()
409 return remote_branch_name.split("/")[0]
410 except subprocess.CalledProcessError as e:
411 # Error code 128 comes with the message:
412 # "fatal: no upstream configured for branch $BRANCH"
413 if e.returncode != 128:
414 print(e.stderr)
415 raise
416
417 return self._get_most_suitable_remote("`git remote add origin $URL`")
418
419 @property
420 def default_branch(self):
421 try:
422 # this one works if the current repo was cloned from an existing
423 # repo elsewhere
424 return self._get_default_branch_from_cloned_metadata()
425 except (subprocess.CalledProcessError, RuntimeError):
426 pass
427
428 try:
429 # This call works if you have (network) access to the repo
430 return self._get_default_branch_from_remote_query()
431 except (subprocess.CalledProcessError, RuntimeError):
432 pass
433
434 # this one is the last resort in case the remote is not accessible and
435 # the local repo is where `git init` was made
436 return self._guess_default_branch()
437
438 def _get_default_branch_from_remote_query(self):
439 # This function requires network access to the repo
440 remote_name = self.remote_name
441 output = self.run("ls-remote", "--symref", remote_name, "HEAD") # type: ignore
442 matches = self._LS_REMOTE_PATTERN.search(output)
443 if not matches:
444 raise RuntimeError(
445 f'Could not find the default branch of remote repository "{remote_name}". '
446 "Got: {output}"
447 )
448
449 branch_name = matches.group("branch_name")
450 return f"{remote_name}/{branch_name}"
451
452 def _get_default_branch_from_cloned_metadata(self):
453 return self.run("rev-parse", "--abbrev-ref", f"{self.remote_name}/HEAD").strip()
454
455 def _guess_default_branch(self):
456 branches = [
457 line.strip()
458 for line in self.run(
459 "branch", "--all", "--no-color", "--format=%(refname)"
460 ).splitlines()
461 for candidate_branch in ("main", "master", "branches/default/tip")
462 if line.strip().endswith(candidate_branch)
463 ]
464
465 if len(branches) == 1:
466 return branches[0]
467
468 raise RuntimeError(f"Unable to find default branch. Got: {branches}")
469
470 def get_url(self, remote=None):
471 remote = remote or "origin"
472 return self.run("remote", "get-url", remote).strip()
473
474 def get_commit_message(self, revision=None):
475 revision = revision or "HEAD"
476 return self.run("log", "-n1", "--format=%B", revision)
477
478 def get_tracked_files(self, *paths, rev=None):
479 rev = rev or "HEAD"
480 return self.run("ls-tree", "-r", "--name-only", rev, *paths).splitlines()
481
482 def get_changed_files(self, diff_filter=None, mode=None, rev=None, base_rev=None):
483 diff_filter = diff_filter or "ADM"
484 mode = mode or "unstaged"
485 assert all(f.lower() in self._valid_diff_filter for f in diff_filter)
486
487 if rev is None:
488 if base_rev is not None:
489 raise ValueError("Cannot specify `base_rev` without `rev`")
490 cmd = ["diff"]
491 if mode == "staged":
492 cmd.append("--cached")
493 elif mode == "all":
494 cmd.append("HEAD")
495 else:
496 revision_argument = (
497 f"{rev}~1..{rev}" if base_rev is None else f"{base_rev}..{rev}"
498 )
499 cmd = ["log", "--format=format:", revision_argument]
500
501 cmd.append("--name-only")
502 cmd.append(
503 "--no-renames"
504 ) # Consider renames as deletion of old, addition of new.
505 cmd.append("--diff-filter=" + diff_filter.upper())
506
507 files = self.run(*cmd).splitlines()
508 return [f for f in files if f]
509
510 def get_outgoing_files(self, diff_filter="ADM", upstream=None):
511 assert all(f.lower() in self._valid_diff_filter for f in diff_filter)
512
513 not_condition = upstream if upstream else "--remotes"
514
515 files = self.run(
516 "log",
517 "--name-only",
518 f"--diff-filter={diff_filter.upper()}",
519 "--oneline",
520 "--pretty=format:",
521 "HEAD",
522 "--not",
523 not_condition,
524 ).splitlines()
525 return [f for f in files if f]
526
527 def working_directory_clean(self, untracked=False, ignored=False):
528 args = ["status", "--porcelain"]
529
530 # Even in --porcelain mode, behavior is affected by the
531 # ``status.showUntrackedFiles`` option, which means we need to be
532 # explicit about how to treat untracked files.
533 if untracked:
534 args.append("--untracked-files=all")
535 else:
536 args.append("--untracked-files=no")
537
538 if ignored:
539 args.append("--ignored")
540
541 # If output is empty, there are no entries of requested status, which
542 # means we are clean.
543 return not len(self.run(*args).strip())
544
545 def update(self, ref):
546 self.run("checkout", ref)
547
548 def find_latest_common_revision(self, base_ref_or_rev, head_rev):
549 try:
550 return self.run("merge-base", base_ref_or_rev, head_rev).strip()
551 except subprocess.CalledProcessError:
552 return self.NULL_REVISION
553
554 def does_revision_exist_locally(self, revision):
555 try:
556 return self.run("cat-file", "-t", revision).strip() == "commit"
557 except subprocess.CalledProcessError as e:
558 # Error code 128 comes with the message:
559 # "git cat-file: could not get object info"
560 if e.returncode == 128:
561 return False
562 raise
563
564
565 def get_repository(path):
566 """Get a repository object for the repository at `path`.
567 If `path` is not a known VCS repository, raise an exception.
568 """
569 for path in ancestors(path):
570 if os.path.isdir(os.path.join(path, ".hg")):
571 return HgRepository(path)
572 elif os.path.exists(os.path.join(path, ".git")):
573 return GitRepository(path)
574
575 raise RuntimeError("Current directory is neither a git or hg repository")