如何使用不同用户的 gitPython 推送到 git

How to push to git using gitPython with different users

我使用 gitPython 使用登录到我们应用程序的不同用户推送到远程仓库。

现在我只是像下面这样推送回购协议:

logging.debug('Opening repo {}...'.format(repo_path))
repo = Repo(repo_path)
logging.debug('Repo is initialized :)')

logging.debug('git add: {} {}'.format(env, file_name))
repo.git.add(file_path)
commit_message = "Add new configs for {}".format(file_name)
logging.debug(commit_message)
repo.git.commit(commit_message)
repo.git.pull('origin', 'refs/heads/dev')
repo.git.push('origin', 'refs/heads/dev')

如果有帮助的话,我在我的 ssh 配置中为 git 用户设置了不同的用户:

Host user1
     HostName repo.remote.com
     User git
     Port 20022
     IdentityFile ~/.ssh/id_rsa_user1

Host user2
     HostName repo.remote.com
     User git
     Port 20022
     IdentityFile ~/.ssh/id_rsa_user2

现在我想推送特定用户。每个登录我们应用程序的用户都有不同的 git 用户。可能吗?这个问题应该怎么解决?

是的,这是可能的,您只需要而不是使用远程origin,而是使用 SSH URL

user1:path/to/repo

您需要构建远程 url 组成:

  • 用户名(方便的是您的 ~/.ssh/config 中的条目名称)
  • 远程 Git 存储库托管服务器中存储库的路径。

所以你的 repo.git.push('origin', 'refs/heads/dev') 变成:

repo.git.push('user1:path/to/repo', 'refs/heads/dev')