GitHubのPull RequestをローカルへcheckoutするPythonスクリプト
概要
GItHubでPull Requestの内容を手元のPCへcheckoutしてその内容を確認する際は以下の手順を実施します。
- 最初は普通にclone
- 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
上記のようにオプションを指定して実行することが可能です。
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.
PythonでJSONデータを受け取りそのままJSONデータを表示させる
概要
JSONデータがPOSTされたらそのままJSONデータを表示させるPythonスクリプトです。 POSTでデータを受け取る際にどういったデータが送信されてくるのか検証をおこなう際に便利でした。
リクエストを受け取るPythonスクリプト
#!/usr/bin/env python # -*- coding:utf-8 -*- import json from http.server import BaseHTTPRequestHandler from http.server import HTTPServer import signal signal.signal(signal.SIGINT, signal.SIG_DFL) class LogHandler(BaseHTTPRequestHandler): def do_POST(self): self.send_response(200) self.end_headers() length = int(self.headers['Content-Length']) data = json.loads(self.rfile.read(length).decode('utf-8')) print(json.dumps(data, indent=2))
スクリプト実行
json-reciever.py
といった名前で以下のようにスクリプトを動かします。
python json-reciever.py
これで1234番ポートで待受け状態になります。
JSONデータをPOST
例として以下のJOSNデータを別ターミナルからPOSTしてみます。
curl -X POST \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -d '{"user":{"first_name":"hoge","last_name":"test","email":"test@example.com","role":"admin"}}' \ http://127.0.0.1:1234/
表示結果
以下のように表示されどういったJSONデータがPOSTされてきたかが分かるようになります。
{ "user": { "first_name": "hoge", "last_name": "test", "email": "test@example.com", "role": "admin" } }
Ubuntuのpipでmysqlclientをインストールした際に遭遇したエラーとその対応
概要
Ubuntu環境でpipで mysqlclient
をインストールしようとした際に遭遇したエラーとその対応のメモ
pipのインストール
以下でpipコマンドをインストール
apt -y install python3-pip
pipで mysqlclient
をインストール
pip3 install mysqlclient
出力されたエラー
Collecting mysqlclient Downloading mysqlclient-2.0.3.tar.gz (88 kB) |████████████████████████████████| 88 kB 352 kB/s ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-pnhw9vzq/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-pnhw9vzq/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-pnhw9vzq/mysqlclient/pip-egg-info cwd: /tmp/pip-install-pnhw9vzq/mysqlclient/ Complete output (15 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-pnhw9vzq/mysqlclient/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-pnhw9vzq/mysqlclient/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-pnhw9vzq/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
対応
pipで mysqlclient
をインストールする前に ibmysqlclient-dev
パッケージをインストール
apt -y install libmysqlclient-dev
再度pipで mysqlclient
をインストール
pip3 install mysqlclient
インストールに成功した際に出力されたメッセージ
Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... done Created wheel for mysqlclient: filename=mysqlclient-2.0.3-cp38-cp38-linux_x86_64.whl size=109284 sha256=ff4cf549254f27c167fc3afe5d6d436a841136151c625a6649bab998d07f2cbe Stored in directory: /root/.cache/pip/wheels/3a/c1/c3/5a19639a551c921c2c2b39468f4278ce5aa27b4e386a4158e4 Successfully built mysqlclient Installing collected packages: mysqlclient Successfully installed mysqlclient-2.0.3