Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/repo_client.py

raw
1 from __future__ import annotations
2 from typing import Tuple
3
4 import json
5 from subprocess import run
6
7 from os.path import isdir, join
8
9 import hglib
10
11
12 def git(root: str, *args: str) -> str:
13 """
14 Wrapper for calling command-line git in the `root` directory.
15 Raises an exception on any error, including a non-0 return code.
16 Returns the command's stdout as a string.
17 """
18 git = ["git"]
19 git.extend(args)
20 proc = run(git, capture_output=True, cwd=root, encoding="utf-8")
21 if proc.returncode != 0:
22 raise Exception(proc.stderr or f"git command failed: {args}")
23 return proc.stdout
24
25
26 class RepoClient:
27 def __init__(self, root: str):
28 self.root = root
29 if isdir(join(root, ".hg")):
30 self.hgclient = hglib.open(root, "utf-8")
31 else:
32 self.hgclient = None
33 try:
34 stdout = git(self.root, "rev-parse", "--is-inside-work-tree")
35 except Exception:
36 stdout = ""
37 if stdout != "true\n":
38 raise Exception(f"Unsupported repository: {root}")
39
40 def close(self):
41 if self.hgclient:
42 self.hgclient.close()
43
44 def blame(self, file: str) -> list[Tuple[str, int]]:
45 "Return a list of (author, time) tuples for each line in `file`."
46 if self.hgclient:
47 args = hglib.util.cmdbuilder(
48 b"annotate",
49 file.encode("latin-1"),
50 template="json",
51 date=True,
52 user=True,
53 cwd=self.root,
54 )
55 blame_json = self.hgclient.rawcommand(args)
56 return [
57 (line["user"], int(line["date"][0]))
58 for line in json.loads(blame_json)[0]["lines"]
59 ]
60 else:
61 lines: list[Tuple[str, int]] = []
62 user = ""
63 time = 0
64 stdout = git(self.root, "blame", "--porcelain", file)
65 for line in stdout.splitlines():
66 if line.startswith("author "):
67 user = line[7:]
68 elif line.startswith("author-mail "):
69 user += line[11:] # includes leading space
70 elif line.startswith("author-time "):
71 time = int(line[12:])
72 elif line.startswith("\t"):
73 lines.append((user, time))
74 return lines
75
76 def commit(self, message: str, author: str):
77 "Add and commit all work tree files"
78 if self.hgclient:
79 self.hgclient.commit(message, user=author.encode("utf-8"), addremove=True)
80 else:
81 git(self.root, "add", ".")
82 git(self.root, "commit", f"--author={author}", f"--message={message}")
83
84 def head(self) -> str:
85 "Identifier for the most recent commit"
86 if self.hgclient:
87 return self.hgclient.tip().node.decode("utf-8")
88 else:
89 return git(self.root, "rev-parse", "HEAD").strip()
90
91 def log(self, from_commit: str, to_commit: str) -> list[str]:
92 if self.hgclient:
93 return [
94 rev.desc.decode("utf-8")
95 for rev in self.hgclient.log(f"{to_commit} % {from_commit}")
96 ]
97 else:
98 return (
99 git(
100 self.root,
101 "log",
102 "--reverse",
103 "--pretty=format:%s",
104 f"{from_commit}..{to_commit}",
105 )
106 .strip()
107 .splitlines()
108 )