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