Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/blame.py

raw
1 from __future__ import annotations
2 from typing import Dict, Iterable, Tuple, TypedDict, cast
3
4 import argparse
5 import json
6 from os.path import join
7
8 from compare_locales.parser import Junk, getParser
9 from compare_locales.parser.fluent import FluentEntity
10
11 from .repo_client import RepoClient
12
13 BlameData = Dict[str, Dict[str, Tuple[int, float]]]
14 "File path -> message key -> [userid, timestamp]"
15
16
17 class BlameResult(TypedDict):
18 authors: list[str]
19 blame: BlameData
20
21
22 class Blame:
23 def __init__(self, client: RepoClient):
24 self.client = client
25 self.users: list[str] = []
26 self.blame: BlameData = {}
27
28 def attribution(self, file_paths: Iterable[str]) -> BlameResult:
29 for file in file_paths:
30 blame = self.client.blame(file)
31 self.handleFile(file, blame)
32 return {"authors": self.users, "blame": self.blame}
33
34 def handleFile(self, path: str, file_blame: list[Tuple[str, int]]):
35 try:
36 parser = getParser(path)
37 except UserWarning:
38 return
39
40 self.blame[path] = {}
41
42 self.readFile(parser, path)
43 entities = parser.parse()
44 for e in entities:
45 if isinstance(e, Junk):
46 continue
47 if e.val_span:
48 key_vals: list[tuple[str, str]] = [(e.key, e.val_span)]
49 else:
50 key_vals = []
51 if isinstance(e, FluentEntity):
52 key_vals += [
53 (f"{e.key}.{attr.key}", cast(str, attr.val_span))
54 for attr in e.attributes
55 ]
56 for key, (val_start, val_end) in key_vals:
57 entity_lines = file_blame[
58 (e.ctx.linecol(val_start)[0] - 1) : e.ctx.linecol(val_end)[0]
59 ]
60 user, timestamp = max(entity_lines, key=lambda x: x[1])
61 if user not in self.users:
62 self.users.append(user)
63 userid = self.users.index(user)
64 self.blame[path][key] = (userid, timestamp)
65
66 def readFile(self, parser, path: str):
67 parser.readFile(join(self.client.root, path))
68
69
70 if __name__ == "__main__":
71 parser = argparse.ArgumentParser()
72 parser.add_argument("repo_path")
73 parser.add_argument("file_path", nargs="+")
74 args = parser.parse_args()
75 blame = Blame(RepoClient(args.repo_path))
76 attrib = blame.attribution(args.file_path)
77 print(json.dumps(attrib, indent=4, separators=(",", ": ")))