|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import os |
| 4 | +from typing import Any, List, Optional |
| 5 | +from git import Repo |
| 6 | +from argparse import Action, ArgumentParser, Namespace |
| 7 | + |
| 8 | + |
| 9 | +MAX_LOOKBACK = 100 |
| 10 | + |
| 11 | + |
| 12 | +class ValidateDir(Action): |
| 13 | + def __call__( |
| 14 | + self, |
| 15 | + parser: ArgumentParser, |
| 16 | + namespace: Namespace, |
| 17 | + values: Any, |
| 18 | + option_string: Optional[str] = None, |
| 19 | + ) -> None: |
| 20 | + if os.path.isdir(values): |
| 21 | + setattr(namespace, self.dest, values) |
| 22 | + return |
| 23 | + |
| 24 | + parser.error(f"{values} is not a valid directory") |
| 25 | + |
| 26 | + |
| 27 | +def parse_args() -> Any: |
| 28 | + parser = ArgumentParser("Get the list of commits from a repo") |
| 29 | + parser.add_argument( |
| 30 | + "--repo", |
| 31 | + type=str, |
| 32 | + required=True, |
| 33 | + action=ValidateDir, |
| 34 | + help="the directory that the repo is checked out", |
| 35 | + ) |
| 36 | + parser.add_argument( |
| 37 | + "--from-commit", |
| 38 | + type=str, |
| 39 | + required=True, |
| 40 | + help="gather all commits from this commit (exclusive)", |
| 41 | + ) |
| 42 | + parser.add_argument( |
| 43 | + "--to-commit", |
| 44 | + type=str, |
| 45 | + default="", |
| 46 | + help="gather all commits to this commit (inclusive)", |
| 47 | + ) |
| 48 | + parser.add_argument( |
| 49 | + "--branch", |
| 50 | + type=str, |
| 51 | + default="main", |
| 52 | + help="the target branch", |
| 53 | + ) |
| 54 | + |
| 55 | + return parser.parse_args() |
| 56 | + |
| 57 | + |
| 58 | +def get_commits( |
| 59 | + repo_dir: str, branch_name: str, from_commit: str, to_commit: str |
| 60 | +) -> List[str]: |
| 61 | + commits = [] |
| 62 | + found_to_commit = True if to_commit == "" else False |
| 63 | + |
| 64 | + repo = Repo(repo_dir) |
| 65 | + # The commit is sorted where the latest one comes first |
| 66 | + for index, commit in enumerate(repo.iter_commits(branch_name)): |
| 67 | + if index > MAX_LOOKBACK: |
| 68 | + break |
| 69 | + |
| 70 | + if not found_to_commit and str(commit) == to_commit: |
| 71 | + found_to_commit = True |
| 72 | + |
| 73 | + if not found_to_commit: |
| 74 | + continue |
| 75 | + |
| 76 | + if str(commit) == from_commit: |
| 77 | + break |
| 78 | + |
| 79 | + commits.append(commit) |
| 80 | + |
| 81 | + return commits |
| 82 | + |
| 83 | + |
| 84 | +def main() -> None: |
| 85 | + args = parse_args() |
| 86 | + for commit in reversed( |
| 87 | + get_commits( |
| 88 | + args.repo, |
| 89 | + args.branch, |
| 90 | + args.from_commit, |
| 91 | + args.to_commit, |
| 92 | + ) |
| 93 | + ): |
| 94 | + print(commit) |
| 95 | + |
| 96 | + |
| 97 | +if __name__ == "__main__": |
| 98 | + main() |
0 commit comments