GitHubのPull RequestをローカルへcheckoutするPythonスクリプト

概要

GItHubでPull Requestの内容を手元のPCへcheckoutしてその内容を確認する際は以下の手順を実施します。

  1. 最初は普通にclone
  2. PRのIDとブランチ名を指定してgit fetch を実行
git fetch origin pull/1/develop

1 はPRのID、develop はブランチ名 3. ブランチが作成されたか確認

git branch -a

4.先程作成したブランチをチェックアウト

git checkout test

※詳細はGitHubの公式ドキュメントをご参照ください。

Pythonスクリプト化

Pull Requestをレビューする際に毎回上記の手順で複数回コマンドを打つのが大変だったのでスクリプト化することにしました。

Pull RequestのIDやbranch名などをスクリプトへオプションとして渡したかったのでPythonのclickというライブラリを使用してスクリプトの作成をおこないました。

作成したPythonスクリプト

#! /usr/bin/env python3

import click
import subprocess

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.command(context_settings=CONTEXT_SETTINGS)
@click.option(
    "-u",
    "--url",
    type=str,
    required=True,
    help="GitHub Repogitory URL",
)
@click.option(
    "-i",
    "--id",
    type=int,
    required=True,
    help="Pull Request ID",
)
@click.option(
    "-b",
    "--branch",
    type=str,
    required=True,
    help="Pull Request Branch",
)
def clone(
    url: str,
    id: int,
    branch: str,
):

    exec = f'git clone {url} && cd "$(basename "$_" .git)" && git fetch origin pull/{id}/head:{branch} && git checkout {branch}'

    try:
        subprocess.run(exec, shell=True)
    except BaseException:
        print("command failed")

Gitコマンドを実行する部分はsubprocessを利用しました。

スクリプト使い方

python3 github-pr-check.py --url git@github.com:example/test.git --id 1 --branch develop

上記のようにオプションを指定して実行することが可能です。

  • --url GitHubのリポジトリのURLを指定
  • --id Pull RequestのIDを指定
  • --branch branch名を指定

help

ヘルプの表示も可能です。 ライブラリのclickを使うことでヘルプ機能も簡単に実装することが出来ました。

Usage: github-pr-check.py [OPTIONS]

Options:
  -u, --url TEXT     GitHub Repogitory URL  [required]
  -i, --id INTEGER   Pull Request ID  [required]
  -b, --branch TEXT  Pull Request Branch  [required]
  -h, --help         Show this message and exit.