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=openbmc.gerrit)",
18            default="openbmc.gerrit",
19        )
20        p.add_argument(
21            "--after",
22            "-a",
23            help="Timestamp for Gerrit 'after:' directive (ex. YYYY-MM-DD)",
24            required=True,
25        )
26        p.set_defaults(cmd=self)
27
28    def run(self, args: argparse.Namespace) -> int:
29        data_path: str = args.dir
30
31        if os.path.exists(data_path) and not os.path.isdir(data_path):
32            print(f"Path {data_path} exists but is not a directory.")
33            return 1
34
35        if not os.path.exists(data_path):
36            os.mkdir(data_path)
37
38        query = list(
39            ssh(
40                args.server,
41                "gerrit",
42                "query",
43                "--format=json",
44                "--patch-sets",
45                "--comments",
46                "--files",
47                "--no-limit",
48                f"after:{args.after} AND delta:>=10",
49            )
50        )[
51            0:-1
52        ]  # The last result from Gerrit is a query stat result.
53
54        for change in query:
55            data = json.loads(change)
56            formatted_data = json.dumps(data, indent=4)
57
58            with open(
59                os.path.join(data_path, str(data["number"]) + ".json"),
60                "w",
61            ) as file:
62                file.write(formatted_data)
63        return 0
64