使用pygit2模块基于ssh密钥对的方式clone gitlab代码

1. 安装pygit2模块

pip3 install pygit2

2. 编写脚本

import pygit2

keypair = pygit2.Keypair("git", "/Users/joseph.wang/.ssh/id_rsa.pub", "/Users/joseph.wang/.ssh/id_rsa", "")
callbacks = pygit2.RemoteCallbacks(credentials=keypair)

# Open the local repository
repo_path = "/Users/joseph.wang/py_script/components"
remote_url = "ssh://git@192.168.31.100:2222/jenkins_ci1/rmp.git"

repo = pygit2.clone_repository(
    remote_url,
    repo_path,
    #callbacks=MyRemoteCallbacks(),
    callbacks=callbacks
)

# Create a new branch
new_branch_name = "my-feature-branch-111-100"
branch = repo.create_branch(new_branch_name,repo.head.peel())

# Checkout the new branch
repo.checkout(branch)

# commit message
index = repo.index
index.add_all()
tree = index.write_tree()
signature = pygit2.Signature("wkx", "wkx_0422@163.com")
commit_message = "Commit message: create branch my-feature-branch-111-100"
commit_oid = repo.create_commit("HEAD", signature, signature, commit_message, tree, [repo.head.target])

# Set up the remote URL and create a remote reference
remote_name = "origin"
#repo.remotes.create(remote_name, remote_url)

# Push changes to the remote repository
remote = repo.remotes[remote_name]
refspec = f"refs/heads/{new_branch_name}:refs/heads/{new_branch_name}"
callbacks = pygit2.RemoteCallbacks(credentials=keypair)
#callbacks = MyRemoteCallbacks()
#remote.push([refspec], callbacks=callbacks)
print("start push...")
remote.push([refspec],callbacks=callbacks)
print("push end")

3. 测试

python test-4.py

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值