LoginSignup
5
3

More than 3 years have passed since last update.

GitHub上のリポジトリからファイルをダウンロードするワンライナー

Posted at

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>
5
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3