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