在 Google Colab 中使用 Git 的方法

是否有任何推荐的方法来集成 git 和 colab?

For example, is it possible to work off code from google source repositories or the likes?

Neither google drive nor cloud storage can be used for git functionality.

所以我想知道还有没有办法继续下去?

144624 次浏览

机器上安装了 git,可以使用 !调用 shell 命令。

例如,要克隆一个 git存储库:

!git clone https://github.com/fastai/courses.git

下面是一个完整的示例,它克隆一个存储库并加载存储在其中的 Excel 文件。 Https://colab.research.google.com/notebook#fileid=1v-yzk-w4yxoxltli7bekdw2zwzxww216

You can use ssh protocol to connect your private repository with colab

  1. Generate ssh key pairs on your local machine, don't forget to keep
    the paraphrase empty, check this 教程.

  2. 上传到 colab,查看下面的截图

    from google.colab import files
    uploaded = files.upload()

  3. 将 ssh kay 对移动到/root 并连接到 git

    • 删除以前的 ssh 文件
      ! rm -rf /root/.ssh/*
      ! mkdir /root/.ssh
    • uncompress your ssh files
      ! tar -xvzf ssh.tar.gz
    • 复制到 root
      ! cp ssh/* /root/.ssh && rm -rf ssh && rm -rf ssh.tar.gz ! chmod 700 /root/.ssh
    • add your git server e.g gitlab as a ssh known host
      ! ssh-keyscan gitlab.com >> /root/.ssh/known_hosts
      ! chmod 644 /root/.ssh/known_hosts
    • set your git account
      ! git config --global user.email "email"
      ! git config --global user.name "username"
    • finally connect to your git server
      ! ssh git@gitlab.com
  4. 验证您的私有存储库,请检查此 每个存储库部署密钥

  5. 使用 ! git@gitlab.com:{account}/{projectName}.git
    注意: 要使用 push,必须为
    the public ssh key that you authenticate git server with.

如果您想克隆一个私有存储库,最快的方法是创建一个 个人通行证个人通行证并只选择应用程序需要的特权。然后,GitHub 的克隆命令应该是这样的:

!git clone https://git_token@github.com/username/repository.git

使用 git 与 github 或 gitlab 同步 colab 的三个步骤。

  1. 生成一个私有-公共密钥对。将私钥复制到系统剪贴板,以便在步骤2中使用。将公钥粘贴到 github 或 gitlab。

    In Linux, ssh-keygen can be used to generate the key-pair in ~/.ssh. The resultant private key is in the file id_rsa, the public key is in the file id_rsa.pub.

  2. 在 Colab,执行

    key = \
    '''
    paste the private key here
    (your id_rsa or id_ecdsa file in the .ssh directory, e.g.
    -----BEGIN EC PRIVATE KEY-----
    M..............................................................9
    ...............................................................J
    ..................................==
    -----END EC PRIVATE KEY-----
    '''
    ! mkdir -p /root/.ssh
    with open(r'/root/.ssh/id_rsa', 'w', encoding='utf8') as fh:
    fh.write(key)
    ! chmod 600 /root/.ssh/id_rsa
    ! ssh-keyscan github.com >> /root/.ssh/known_hosts
    # test setup
    ! ssh -T git@github.com
    # if you see something like "Hi ffreemt! You've successfully
    # authenticated, but GitHub does not provide shell access."
    # you are all set. You can tweak .ssh/config for multiple github accounts
    
  3. 像往常一样使用 git 来拉/推。

对 colab 和 HostA 之间的 rsync (或 ssh)也可以采用同样的思路,只需稍作修改:

  1. 生成一个私有-公共密钥对。将私钥复制到系统剪贴板,以便在步骤2中使用。将公钥粘贴到。在 HostA 的 ssh。

  2. 在 Colab,执行

    key = \
    '''
    paste the private key here
    '''
    ! mkdir -p /root/.ssh
    with open(r'/root/.ssh/id_rsa', 'w', encoding='utf8') as fh:
    fh.write(key)
    ! chmod 600 /root/.ssh/id_rsa
    ! ssh -oStrictHostKeyChecking=no root@HostA hostnam  # ssh-keyscan
    

HostA >/root/. ssh/known _ hosts 似乎不适用于 IP。

  1. 像往常一样使用 rsync 同步 colab 和 HostA 之间的文件。

为了保护您的帐户用户名和密码,您可以使用 getPass并在 shell 命令中连接它们:

from getpass import getpass
import os


user = getpass('BitBucket user')
password = getpass('BitBucket password')
os.environ['BITBUCKET_AUTH'] = user + ':' + password


!git clone https://$BITBUCKET_AUTH@bitbucket.org/{user}/repository.git

安装驱动器使用:

from google.colab import drive
drive.mount('/content/drive/')

然后:

%cd /content/drive/

复制你硬盘里的回购文件

!git clone <github repo url>

从 repo 访问其他文件(例如: helper.py 是 repo 中的另一个文件) :

import imp
helper = imp.new_module('helper')
exec(open("drive/path/to/helper.py").read(), helper.__dict__)

You can almost use this link: Https://qiita.com/rowing0914/items/51a770925653c7c528f9

你可在此浏览上述连结的摘要,并按以下步骤进行:

1- 使用以下命令将你的 Google colab 运行时连接到你的 Google Drive:

from google.colab import drive
drive.mount('/content/drive')

It would need a authentication process. Do whatever it needs.

2- 设置 current directory路径你想克隆 Git 项目:

以我为例:

path_clone = "drive/My Drive/projects"
%cd path_clone

不要忘记在 cd命令的开头使用 !

3- 克隆 Git 项目:

!git clone <Git project URL address>

现在你可以在你的谷歌驱动器(它也连接到您的谷歌 Colab 运行时计算机)的 projects文件夹中克隆 Git 项目

4- 进入你的 Google Drive (使用浏览器等) ,然后进入“ Projects”文件夹,打开你想在 Google Colab 中使用的 .ipynb文件。

5- 现在你有了 Google Colab 运行时和你想要使用的 .ipynb,它也连接到你的 Google Drive,所有克隆的 git 文件都在 Colab 运行时的存储中。

注:

1- Check that your Colab runtime is connected to Google Drive. If it's not connected, just repeat the 第一步.

2-双重检查使用“ pwd”和“ cd”命令的 current directory是相关的克隆 git 项目在谷歌驱动器 (步骤 # 2)

在谷歌 Colab中克隆你的私人 Github回购的非常简单和容易的方法如下。

  1. 您的密码不会暴露
  2. 虽然您的密码包含特殊字符也工作
  3. 只要在 Colab 单元格中运行下面的代码片段,它就会以交互的方式执行
import os
from getpass import getpass
import urllib


user = input('User name: ')
password = getpass('Password: ')
password = urllib.parse.quote(password) # your password is converted into url format
repo_name = input('Repo name: ')


cmd_string = 'git clone https://{0}:{1}@github.com/{0}/{2}.git'.format(user, password, repo_name)


os.system(cmd_string)
cmd_string, password = "", "" # removing the password from the variable

如果你想分享你的回购和合作,这个工作。如果你有多个回购协议也有效。把它扔进牢房。

import ipywidgets as widgets
from IPython.display import display
import subprocess


class credentials_input():
def __init__(self, repo_name):
self.repo_name = repo_name
self.username = widgets.Text(description='Username', value='')
self.pwd = widgets.Password(description = 'Password', placeholder='password here')


self.username.on_submit(self.handle_submit_username)
self.pwd.on_submit(self.handle_submit_pwd)
display(self.username)


def handle_submit_username(self, text):
display(self.pwd)
return


def handle_submit_pwd(self, text):
cmd = f'git clone https://{self.username.value}:{self.pwd.value}@{self.repo_name}'
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
print(output, error)
self.username.value, self.pwd.value = '', ''


get_creds = credentials_input('github.com/username/reponame.git')
get_creds

解决方案 https://stackoverflow.com/a/53094151/3924118不适合我,因为表达式 {user}没有被转换为实际用户名(我收到了400个错误请求) ,所以我稍微将该解决方案更改为以下解决方案。

from getpass import getpass
import os


os.environ['USER'] = input('Enter the username of your Github account: ')
os.environ['PASSWORD'] = getpass('Enter the password of your Github account: ')
os.environ['REPOSITORY'] = input('Enter the name of the Github repository: ')
os.environ['GITHUB_AUTH'] = os.environ['USER'] + ':' + os.environ['PASSWORD']


!rm -rf $REPOSITORY # To remove the previous clone of the Github repository
!git clone https://$GITHUB_AUTH@github.com/$USER/$REPOSITORY.git


os.environ['USER'] = os.environ['PASSWORD'] = os.environ['REPOSITORY'] = os.environ['GITHUB_AUTH'] = ""

If you are able to clone your-repo, you should not see any password in the output of this command. If you get an error, the password could be displayed to the output, so make sure you do not share your notebook whenever this command fails.

克隆一个私人回购协议到 google colab:

生成一个令牌:

Settings -> Developer settings -> Personal access tokens -> Generate new token

复制令牌并克隆回购(相应地替换 用户名Token)

!git clone https://username:token@github.com/username/repo_name.git

我在这里尝试了一些方法,它们都工作得很好,但是我面临的一个问题是,在笔记本单元中处理所有 git 命令和其他相关命令变得很困难,例如使用 DVC 的版本控制。所以我转向了这个不错的解决方案戈拉。这种虚拟终端可以在 colab 中使用。这使得易于使用非常类似于终端在本地机。笔记本将仍然活着,我们可以像往常一样编辑文件和单元格。由于此控制台是临时的,因此不公开任何信息。可以像往常一样运行 GitHub 登录和其他命令。

https://pypi.org/project/kora/

用法:

!pip install kora
from kora import console
console.start()

我终于振作起来,为此编写了一个 Python 包。

pip install clmutils  # colab-misc-utils

在/content/drive/MyDrive 中创建 dotenv 或. env (如果将 google drive 安装到 drive 中)或/content/drive/. env

# for git
user_email = "your-email"
user_name = "your-github-name"
gh_key = "-----BEGIN EC PRIVATE KEY-----
...............................................................9
your github private key........................................J
..................................==
-----END EC PRIVATE KEY-----
"

在科拉布监狱

from clmutils import setup_git, Settings


config = Settings()
setup_git(
user_name=config.user_name,
user_email=config.user_email,
priv_key=config.gh_key
)

然后你就可以做所有的 git cloen,修改代码,git push的东西,就好像它是在你自己可爱的电脑在家里或在工作。

clmutils还有一个名为 setup_ssh_tunnel的函数,用于设置通往 Colab 的反向 ssh 隧道。中读取各种键、用户名、主机名。Env 文件。有点牵扯进去了。但是,如果您知道如何手动设置 revers ssh 隧道到 Colab,那么您就可以毫不费力地搞清楚它们的用途。详细信息可在 github 回购(谷歌 clmutils pypi)。

2021年9月更新ーー出于安全原因,现在不推荐使用 github 的密码。请使用 Personal Access Tokenーー转到 github.com ーー > 设置ーー > 开发人员设置ーー > 个人访问令牌,并为所需目的生成令牌。在本教程中提到的所有任务中使用此密码代替密码!

更多的细节你也可以看到我的文章中介: https://medium.com/geekculture/using-git-github-on-google-colaboratory-7ef3b76fe61b

没有一个答案能像下面这样直截了当:

GitColab

也许这就是你想要的答案。

Works on colab for both public and private repositories and don't change/skip any step: (Replace all {vars})

DR 全过程:

!git clone https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git
%cd /content/{destination_repo_username}


!git config --global user.name "{your_username}"
!git config --global user.email "{your_email_id}"
!git config --global user.password "{your_password}"

进行更改,然后运行:

!git add .
!git commit -m "{Message}"
!git push

克隆存储库:

!git clone https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git

将目录更改为

使用针对 jupyter 笔记本的行魔法命令 %cd,将目录更改为{ Destination _ repo _ username }。

%cd /content/{destination_repo_username}

确认!

检查一下是否一切正常!

!git pull

如果在克隆后没有对远程 git repo 进行任何更改,则应该显示以下输出:

Already up to date.

报告情况

类似地,检查暂存/非暂存更改的状态。

!git status

它应该显示这个,并选择默认的分支:

On branch main
Your branch is up to date with 'origin/main'.


nothing to commit, working tree clean

查查旧日志

检查你以前对回购所做的承诺:

!git log -n 4

输出带日志的 Git 提交 ID:

commit 18ccf27c8b2d92b560e6eeab2629ba0c6ea422a5 (HEAD -> main, origin/main, origin/HEAD)
Author: Farhan Hai Khan <njrfarhandasilva10@gmail.com>
Date:   Mon May 31 00:12:14 2021 +0530


Create README.md


commit bd6ee6d4347eca0e3676e88824c8e1118cfbff6b
Author: khanfarhan10 <njrfarhandasilva10@gmail.com>
Date:   Sun May 30 18:40:16 2021 +0000


Add Zip COVID


commit 8a3a12863a866c9d388cbc041a26d49aedfa4245
Author: khanfarhan10 <njrfarhandasilva10@gmail.com>
Date:   Sun May 30 18:03:46 2021 +0000


Add COVID Data


commit 6a16dc7584ba0d800eede70a217d534a24614cad
Author: khanfarhan10 <njrfarhandasilva10@gmail.com>
Date:   Sun May 30 16:04:20 2021 +0000


Removed sample_data using colab (testing)

在本地回购中做出改变

Make changes from the local repo directory.

这些可能包括,版本,删除,编辑。

专业提示: 如果你想,你可以复制粘贴东西从驱动器到一个 git 回购:

登上谷歌硬盘:

from google.colab import drive
drive.mount('/content/gdrive')

使用 shutil 复制内容:

import shutil


# For a folder:
shutil.copytree(src_folder,des_folder)


# For a file:
shutil.copy(src_file,des_file)


# Create a ZipFile
shutil.make_archive(archive_name, 'zip', directory_to_zip)

设置 Git 凭证

告诉 Git 你是谁?

!git config --global user.name "{your_username}"
!git config --global user.email "{your_email_id}"
!git config --global user.password "{your_password}"

再次检查遥控器

检查远程 URL 设置和配置是否正确:

!git remote -v

如果配置正确,它应该输出以下内容:

origin  https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git (fetch)
origin  https://{your_username}:{your_password}@github.com/{destination_repo_username}/{destination_repo_projectname}.git (push)

添加,提交,推送

你知道该怎么做。

!git add .
!git commit -m "{Message}"
!git push

好好享受吧!

另一个基于@Marafon Thiago 回答的解决方案:

注意 : 在具有特殊字符的密码中,使用字符的相应 encoding

你应该输入: passwd = '%40123'

from getpass import getpass
user = getpass('BitBucket user')
password = getpass('BitBucket password')


!git init
!git clone https://{user}:{password}@bitbucket.org/aqtechengenharia/aqtlibpy.git