ローカルリポジトリからGitHubリポジトリを作成してpushする
手元でgit initしたリポジトリをGitHubに上げる場合、通常はGitHub上でリポジトリを作成し、git remote addでリモートを登録し、git pushする。
GitHub CLIのgh repo createに--sourceと--pushを指定すると、一連の手順をコマンド1つで完了できる。
gh repo create リポジトリ名 --source=. --push --public
--sourceはGitHubリポジトリの元にするローカルリポジトリのパスを指定する。--pushはローカルのコミットを作成したリポジトリへpushする。
実行すると以下のように出力される。実際にはgit pushの進捗表示も間に挟まる。
✓ Created repository suer/my-project on github.com
https://github.com/suer/my-project
✓ Added remote https://github.com/suer/my-project.git
✓ Pushed commits to https://github.com/suer/my-project.git
リポジトリの作成、リモートの登録、pushの3つが順に実行される。
可視性のフラグは省略できない
--sourceや--pushを指定する場合、--public、--private、--internalのいずれかも必要である。
フラグを1つでも指定した時点で非対話モードとして扱われ、可視性を対話で選択する余地がなくなるためである。
省略すると以下のエラーになる。
`--public`, `--private`, or `--internal` required when not running interactively
引数とフラグを一切指定せずにgh repo createだけを実行した場合は対話モードになり、可視性を含めた各項目をプロンプトで入力する。
リポジトリ名は省略できる
--sourceを指定する場合、リポジトリ名の引数は省略できる。省略時は--sourceで指定したディレクトリ名がリポジトリ名になる。
$ cd ~/work/my-project
$ gh repo create --source=. --push --private
上記ではmy-projectという名前のリポジトリが作成される。
リポジトリ名にowner/repoの形式でオーナーを含めると、組織のリポジトリとして作成できる。
gh repo create my-org/my-project --source=. --push --private
–pushで実行されるgitコマンド
--pushは内部で以下のコマンドを実行する。
git push --set-upstream origin HEAD
現在のブランチのみがpush対象であり、上流ブランチの設定も同時に実施される。他のローカルブランチはpushされない。
--sourceにbareリポジトリを指定した場合のみ、git push origin --mirrorが実行されすべてのrefがミラーされる。
リモート名を変更する
登録されるリモート名はデフォルトでoriginである。--remoteオプションで別の名前を指定できる。
gh repo create my-project --source=. --push --private --remote=upstream
--remoteと--pushは--sourceと組み合わせた場合にのみ使用できる。--sourceなしで指定すると以下のエラーになる。
the `--push` option can only be used with `--source`
事前にgit initとコミットが必要
--sourceに指定したディレクトリがGitリポジトリでない場合はエラーになる。
current directory is not a git repository. Run `git init` to initialize it
コミットが1つも存在しない状態で--pushを指定した場合もエラーになる。GitHub上のリポジトリを作成する前にエラー終了するため、空のリポジトリが残ることはない。
`--push` enabled but no commits found in /Users/suer/work/my-project
git initのあと、git addとgit commitを済ませてから実行する。
$ git init
$ git add .
$ git commit -m "initial commit"
$ gh repo create my-project --source=. --push --private
–sourceと併用できないオプション
--sourceは--clone、--template、--license、--gitignoreと併用できない。
the `--source` option is not supported with `--clone`, `--template`, `--license`, or `--gitignore`
--licenseや--gitignoreはGitHub側で初期ファイルを生成するオプションであり、既存のローカルリポジトリを元にする--sourceとは用途が競合する。
LICENSEや.gitignoreが必要な場合はローカルに配置してコミットしておく。
なお--descriptionや--disable-issuesなどのリポジトリ設定は--sourceと併用できる。
gh repo create my-project --source=. --push --public --description "サンプルアプリ" --disable-wiki
