LoginSignup
116
88

More than 3 years have passed since last update.

Google Colab上でGitHubからCloneして変更をPushするまでのまとめ

Last updated at Posted at 2020-03-21

何の記事?

Google Colaboratory上でGitHubのレポジトリをcloneし、変更をpushするまでのメモ。特に変わったところはないです。
ちなみにColabではノードブックに関してはコマンドを打たなくてもpushまでできる便利な機能があります。
参考記事:Colabratoryって画面上だけでGitHubにPushして差分まで見れちゃうって知ってた?

そもそもColabからGithubにpushする必要ってあるの?

環境難民にとっては結構起こりえます。
あと、いちいちローカル環境でcloneするまでも無いが、既存コードをforkしてちょっとreviseして試してバージョン管理したいときなど。

手順

流れとしてはDriveマウント→clone→config→add→commit→origin設定→pushです。
マウントは最初の1回だけでOK。
configとorigin設定はセッション中に1回だけでOK。

1. Google Driveをマウントする

ご存知の通りColabはインスタンスの12時間ルール&90分ルールがあるので、作業ディレクトリの内容が一定時間で消えてしまいます。
当然.gitなども保存されず、これではコード管理もやりようがないので、まずはGoogle Driveをマウントします。
UI上で左側のファイルボタンを押し、「ドライブをマウント」でマウントできます。
image.png
これで自分のGoogleDrive上のファイルをノートブック上で扱えるようになり、保存もできるようになります。

2. Clone

Google Drive上にColabDataというような作業ディレクトリを作ります(作らなくても良いです)。
カレントディレクトリを移動しcloneします。

%cd /content/drive/My Drive/Colabdata/
!git clone https://github.com/reponame.git

3. Config(ユーザ名とメールアドレスを設定)

これを設定しないとcommitで怒られます。

!git config --global user.email "yourmail@gmail.com"
!git config --global user.name "username"

4. Add, Commit

特に変わったところはないです。

!git add file.py
!git commit -m "Added new file."

5. リポジトリ情報を明示的に記述してOriginを設定

ここが若干のハマりポイントです。
git cloneした時点でリモートサーバにoriginがデフォルトで設定されるのですが、ここにpushしても下記のように怒られます。

!git push origin master
# fatal: could not read Username for 'https://github.com': No such device or address

Colabでは、下記のように明示的にoriginに認証情報(ユーザ名、パスワード)を渡して設定する必要があります。

!git remote set-url origin https://username:password@github.com/reponame.git
!git push origin master

無事pushが通れば成功です。快適なColabライフをお送りください。

まとめ

Colab上で、git cloneからpushまでの流れをまとめました。
下記に、一連のコマンドをまとめます。

%cd /content/drive/My Drive/Colabdata/
!git clone https://github.com/reponame.git
!git config --global user.email "yourmail@gmail.com"
!git config --global user.name "username"
!git add file.py
!git commit -m "Added new file."
!git remote set-url origin https://username:password@github.com/reponame.git
!git push origin master

以上です。

116
88
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
116
88