ghコマンドの基本的な使い方

ghコマンド

みなさんはGitHubを使っているでしょうか。

私は趣味で作ったコードを管理するために使用していて、仕事では使ってきませんでした。

※今までは別のGit管理ツールでした

私の職場でも今後GitHubを使い始めるらしく、趣味レベルでの使い方では足らない気がしたのでこれを期に普段何気なく使っているコマンドの整理をしてみようと思います。

まずはインストール

公式の手順にしたがってインストールします。

github.com

注意点は特にない気はしますが、強いて言えばGPG署名キー(apt-key)が変更されているので公式の手順を見てインストールしたほうが良いと思います。

例えば[C99B11DEB97541F0]は期限切れです。

$sudo apt-key list
/etc/apt/trusted.gpg
--------------------
pub   rsa3072 2020-09-02 [SC] [期限切れ: 2022-09-02]
  ┆ ┆ 2CA3 2056 ED20 6CB8 1F44  A8CA C99B 11DE B975 41F0
uid           [期限切れ] Nate Smith <vilmibm@github.com>

公式ページより

We were recently forced to change our GPG signing key. If you've previously downloaded the githubcli-archive-keyring.gpg file, you should re-download it again per above instructions. If you are using a keyserver to download the key, the
ID of the new key is 23F3D4EA75716059.

新しいのは[23F3D4EA75716059]だよとのことです。(2023.08.28時点)

キーサーバ経由で入れている方は新しいものか確認してみると良いかもしれません。

ちなみに古いやつは以下のように消します。

$sudo apt-key del B97541F0
OK

期限切れのキーがあればこの際整理しましょう。

ちなみにdelの次に指定する引数はlistで表示されたキーの下8桁です。

余談ですがapt-key運用は非推奨の流れです。

apt-keyを使うとこんなメッセージが出ます

Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).

公式の手順で.gpgファイルが出てくるのもそのためです。

また、Macの場合はbrewでインストールします。

brew install gh

Windowsの場合はWSLを使ってると思います(過激派)

GitHubにログインする

インストールが終わったらghコマンドを用いてGitHubにログインします。

gh auth login

認証の方法はおまかせしますが、私はいつもGitHubページ上で認証しています。

上記コマンドを実行するとどうするか聞かれます。ブラウザでのログインを選択するとGitHubページが開き、ターミナル上に表示された認証コードをブラウザに入力することでログインできます。

GitHub.comを選択

? What account do you want to log into?  [Use arrows to move, type to filter]
> GitHub.com
  GitHub Enterprise Server

ブラウザでログイン

? How would you like to authenticate?  [Use arrows to move, type to filter]
> Login with a web browser
  Paste an authentication token

一度ログインしてしまえばPCを閉じてもログインしたままになるので便利です。

コマンドを使ってみる

使えるようになっているか確認するためにも下記を実行します。

$gh repo list

このコマンドはログインしているユーザの所持しているリポジトリ一覧が表示されるコマンドです。

一つでも所持していれば以下のように表示されます。

username/repo                               this repo is repo                               private       2d
username/repo2                             this repo is repo2                             public        3d

※usernameは今回説明用に書き換えているダミーのユーザー名です

試しにcloneしてみる

所持しているリポジトリのコンテンツをクローンしてみます。

git cloneの代わりに以下を実行してみてください。

$gh repo clone username/repo

これにより簡単にローカルへクローンすることができます。

私の場合はgh repo listしてusername/repoをコピペしています。

ちなみにforkする場合は以下です

$gh repo fork other-username/repo

余談ですがforkをお試しでやってみたい場合は以下のようにしてみてください。

$gh repo fork octocat/Spoon-Knife

このリポジトリはforkの練習用に公式が用意してくれているリポジトリですので、練習に使ってみると良いと思います。

github.com

リポジトリの情報を表示する

cloneしたディレクトリに移動して以下のようにしてみてください。

$gh repo view

こうすることでリポジトリのREADME.mdを見ることが出来ます。

例:Spoon-Knifeで実行

octocat/Spoon-Knife
This repo is for demonstration purposes only.


  ### Well hello there!

  This repository is meant to provide an example for forking a repository on GitHub.

  Creating a fork is producing a personal copy of someone else's project. Forks act as a sort of bridge between the
  original repository and your personal copy. You can submit Pull Requests to help make other people's projects better
  by offering your changes up to the original project. Forking is at the core of social coding at GitHub.

  After forking this repository, you can make some changes to the project, and submit a Pull Request
  https://github.com/octocat/Spoon-Knife/pulls as practice.

  For some more information on how to fork a repository, check out our guide, "Forking Projects"
  http://guides.github.com/overviews/forking/. Thanks! 💖



View this repository on GitHub: https://github.com/octocat/Spoon-Knife"

リポジトリを作成してみる

新規にリポジトリを作成するときに使用するコマンドです。

これを実行することで公開範囲やオーナーや名前はどうするか、ついでにcloneもするかを対話形式で聞いてくれます。

$gh repo create
? What would you like to do? Create a new repository on GitHub from scratch
? Repository name test-repo
? Repository owner username
? Description
? Visibility  [Use arrows to move, type to filter]
> Public
  Private
  Internal

いちいち聞かれたくない場合はオプションを指定してやれば完了になります。

オプションは以下です

--add-readme            (Add a README file to the new repository)
--gitignore             (Specify a gitignore template for the repository)
--license               (Specify an Open Source License for the repository)
--source                (Specify path to local repository to use as source)
--clone                 (Clone the new repository to the current directory)
--help                  (Show help for command)
--private               (Make the new repository private)
--team                  (The `name` of the organization team to be granted access)
--description           (Description of the repository)
--homepage              (Repository home page `URL`)
--public                (Make the new repository public)
--template              (Make the new repository based on a template `repository`)
--disable-issues        (Disable issues in the new repository)
--include-all-branches  (Include all branches from template repository)
--push                  (Push local commits to the new repository)
--disable-wiki          (Disable wiki in the new repository)
--internal              (Make the new repository internal)
--remote                (Specify remote name for the new repository)

issue周り

GitHubを使うならぜひ使いたい機能のissueの使い方を見ていきます。

確認する

まずは自身のリポジトリからクローンしたディレクトリに移動して、以下のコマンドを実行してみます。

$gh issue list
no open issues in username/repo

開いているissueがなければ何も表示されません。

また、クローズされたissueを確認するには引数に--state closedを指定します。

$gh issue list --state closed
Showing 1 of 1 issue in username/repo that matches your search

#1  Test issue from CLI    about 1 days ago

こんな感じで確認することができます。

新規作成

次にissueを新しく立てて見ます。

と、その前にissue等で文章を書くときに使いたいエディタがあれば設定します。

ここで設定しない場合はnanoを使わされますので、それが苦痛な方はエディタを指定すると良いと思います。

$gh config set editor vim

こうすることでvimを指定することができます。最高にクールです。

issueの新規作成は簡単で以下のようにします。

$gh issue create

これにより対話形式でissueを作成できます。

$gh issue create

Creating issue in username/repo

? Title Test123
? Body <Received>
? What's next?  [Use arrows to move, type to filter]
> Submit
  Continue in browser
  Add metadata
  Cancel

作成できたかlistで確認してみます

$gh issue list

Showing 1 of 1 open issue in username/repo

#4  Test123    less than a minute ago

内容を確認するには以下のようにします。

今回はlistで表示されているナンバーが#4なので引数に4を指定しています。

$gh issue view 4
Test123 #4
Open • username opened about 1 minute ago • 0 comments

  テストで作成しています

issueに返信する

それでは試しに#4のissueに対して返信してみます。

下記を実行するとこのように表示されますのでEnterを押下します。

$gh issue comment 4
- Press Enter to draft your comment in vim...

中身をてきとーに書いてみて

テスト返信です

Submitします

- Press Enter to draft your comment in vim...
? Submit? (Y/n)

その後、再度issueの中身を見てみます

$gh issue view 4
Test123 #4
Open • username opened about 7 minutes ago • 1 comment

  テストで作成しています

username (Owner) • 0m • Newest comment

  テスト返信です

これでissueへの返信をすることができました。

他にも興味があれば色々やってみてほしいです。

WorkFlowの確認

ここまでやってみると大体勘付いていると思いますがGitHub Actionsの内容もここで確認できます。

$gh workflow list
publish  active  67060434

あとは端折りますがissueと同じような感じで色々できます。

$gh workflow view 67060434
publish - build.yaml
ID: 67060434

Total runs 3
Recent runs
X  ttt                           publish  testrun  push  5970709502
X  add driver                    publish  testrun  push  5961274831
X  run test                      publish  testrun  push  5961094283

To see more runs for this workflow, try: gh run list --workflow build.yaml
To see the YAML for this workflow, try: gh workflow view build.yaml --yaml

なんとなく開いたやつが全部失敗してましたが気にしないでください。

pull requestしてみる

いきなり他の人のリポジトリでやるのもあれなので自身のリポジトリで試してみます。

※権限が必要って言われたらそのとおりに適宜追加してください。

テキトーにbranchを切ってください

$git branch test
$git branch
* main
  test

次に切ったブランチに移動します

$git checkout test
Switched to branch 'test'

試しに変更を加えてみます

$vim testing123.txt

テキトーに内容を書いて保存します

testing123.txtの中身です

変更を確認&コミットします

$git status
ブランチ test
追跡されていないファイル:
  (use "git add <file>..." to include in what will be committed)
  ┆ ┆ ┆ testing123.txt

$git add testing123.txt
$git commit -m "testing123.txt"
[test 25bc172] testing123.txt
 1 file changed, 1 insertion(+)
 create mode 100644 testing123.txt

それではmainに対してpull requestを書いてみます。

使用するコマンドはgh prで、使い方はissueとかと同じです。

試しにlistしてみます(何もありません)

$gh pr list
no open pull requests in username/repo

pull requestを作成してみます

gh pr create --base main

--base mainはどのブランチに対して投げるかを指定しています。

今回はtestブランチからmainブランチに投げるのですが、

ターミナル上ですでにtestブランチにいるので--head testの指定は不要です。

余談

余談ですがforkしている場合はset-defaultが必要になります。

以前はデフォルトで設定されていたのですが、最近は自身でセットするようになったようです。

$gh repo set-default
This command sets the default remote repository to use when querying the
GitHub API for the locally cloned repository.

gh uses the default repository for things like:

 - viewing and creating pull requests
 - viewing and creating issues
 - viewing and creating releases
 - working with Actions
 - adding repository and environment secrets

? Which repository should be the default?  [Use arrows to move, type to filter]
> octocat/Spoon-Knife
  username/Spoon-Knife

✓ Set octocat/Spoon-Knife as the default repository for the current directory

こんな感じでfork元を指定してやると、pull requestが相手に届くようになります。

続き

とりあえず実行すると以下のように対話してくれます。

? Where should we push the 'test' branch?  [Use arrows to move, type to filter]
> username/repo
  Skip pushing the branch
  Cancel

こんな感じになります

? Title Test Title Testing123.txt
? Body <Received>
? What's next?  [Use arrows to move, type to filter]
> Submit
  Submit as draft
  Continue in browser
  Add metadata
  Cancel

Enter押下で

remote:
To https://github.com/username/repo.git
 * [new branch]      HEAD -> test
Branch 'test' set up to track remote branch 'test' from 'origin'.
https://github.com/username/repo/pull/5

こんな感じで作成された感のある出力があります。

今回は#5で作成されたことが最終行を見ることでわかります。

試しにlistしてみます

$gh pr list

Showing 1 of 1 open pull request in username/repo

#5  Test Title Testing123.txt  test  about 2 minutes ago

作成したpull request(#5)が表示されました。

あとはこれに返信したり、完了させたりをissueと同じような容量でやっていきます。

マージする

今回は試しにリクエストをマージしてみます。

$gh pr merge 5
? What merge method would you like to use?  [Use arrows to move, type to filter]
> Create a merge commit
  Rebase and merge
  Squash and merge

こんな感じでどのようにマージするか聞かれます。今回はmerge commitしちゃいます。

対話をしていくと最終的にこんな感じになります

$gh pr merge 5
? What merge method would you like to use? Create a merge commit
? Delete the branch locally and on GitHub? Yes
? What's next? Submit
✓ Merged pull request #5 (Test Title Testing123.txt)
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 1 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (1/1), 632 bytes | 632.00 KiB/s, done.
From https://github.com/username/repo
 * branch            main       -> FETCH_HEAD
  ┆fc8b96a..d76d1b5  main       -> origin/main
Updating fc8b96a..d76d1b5
Fast-forward
 testing123.txt | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 testing123.txt
✓ Deleted local branch test and switched to branch main
✓ Deleted remote branch test

これでマージすることができました。

今回は軽く整理したいだけなのでこの辺にしておきます。(疲れました)

仕事で使うようになったらもっと使いこなせるようになれそうで楽しみです。