1#!/usr/bin/python3
2
3import argparse
4import json
5import os
6from sh import ssh  # type: ignore
7
8
9class subcmd:
10    def __init__(self, parser: argparse._SubParsersAction) -> None:
11        p = parser.add_parser(
12            "dump-gerrit", help="Dump commit data from Gerrit"
13        )
14        p.add_argument(
15            "--server",
16            "-s",
17            help="Gerrit server SSH alias (default=gerrit.openbmc-project.xyz)",
18            default="gerrit.openbmc-project.xyz",
19        )
20        p.add_argument(
21            "--port",
22            "-p",
23            help="Gerrit server SSH port (default=29418)",
24            default="29418",
25        )
26        p.add_argument(
27            "--after",
28            "-a",
29            help="Timestamp for Gerrit 'after:' directive (ex. YYYY-MM-DD)",
30            required=True,
31        )
32        p.set_defaults(cmd=self)
33
34    def run(self, args: argparse.Namespace) -> int:
35        data_path: str = args.dir
36
37        if os.path.exists(data_path) and not os.path.isdir(data_path):
38            print(f"Path {data_path} exists but is not a directory.")
39            return 1
40
41        if not os.path.exists(data_path):
42            os.mkdir(data_path)
43
44        query = list(
45            ssh(
46                args.server,
47                "-p", args.port,
48                "gerrit",
49                "query",
50                "--format=json",
51                "--patch-sets",
52                "--comments",
53                "--files",
54                "--no-limit",
55                f"after:{args.after} AND delta:>=10",
56            )
57        )[
58            0:-1
59        ]  # The last result from Gerrit is a query stat result.
60
61        for change in query:
62            data = json.loads(change)
63            formatted_data = json.dumps(data, indent=4)
64
65            with open(
66                os.path.join(data_path, str(data["number"]) + ".json"),
67                "w",
68            ) as file:
69                file.write(formatted_data)
70        return 0
71