Contents APIを使う
REST API v3のContents APIを使う。
Get contents
Gets the contents of a file or directory in a repository.
前提
- jqをインストールする
- GitHubのリポジトリ操作権限を持ったpersonal access tokenを取得する
リポジトリのファイルをダウンロードするワンライナー
次のワンライナーでGitHub上のファイルをダウンロードできる:
curl -sSL -H "Accept: application/vnd.github.v3+json" -u <user name>:<token> \
https://api.github.com/repos/<owner>/<repo>/contents/<file_path> \
| jq -r .content \
| base64 --decode > <output file name>
このワンライナーは次の順番で処理を実行している:
- Contents APIを呼び出してファイルの内容をJSONで取得する
- JSONからBase64エンコードされたファイルの内容を表わすフィールド
content
を取得する- このとき、
raw-output
(-r
) オプションでJSON文字列ではない生の文字列としてstdoutに出力することで、"
などを取り除く
- このとき、
- Base64デコードして、標準出力の内容をファイルへリダイレクトする
例として、rails/railsのactiverecord/lib/active_record.rbをダウンロードするときは次のようになる:
REPOS=rails/rails
FILE_PATH=activerecord/lib/active_record.rb
curl -sSL -H "Accept: application/vnd.github.v3+json" -u <user name>:<token> \
https://api.github.com/repos/${REPOS}/contents/${FILE_PATH} \
| jq -r .content \
| base64 --decode > <output file name>