首页 > 解决方案 > Push local git repository to a user's remote git repository using PyGithub and Python

问题描述

Task is to

  1. Clone a public repository and store it locally
  2. Initialize a user's new repository(target) with the repository content that you downloaded locally.

The CLI commands work perfectly but I need to do it using python, and when I run this code, a github login dialogue box opens and I enter the credentials and then the push works but nothing is seen on the remote repository, can we push nothing?

I have tried using subprocess module too, it does not work. I have checked every other stackoverflow solution and did not find a working solution.I need a new solution or a correction to this asap. Thanks.

import git

git.Repo.clone_from('https://github.com/kristej/Uniform-Database-Management.git','Uniforms')

repo = git.Repo('Uniforms')
target_repo = "https://github.com/kristej/Jojorabit.git"

# List remotes
# Reference a remote by its name as part of the object
print(f'Remote name: {repo.remotes.origin.name}')
print(f'Remote URL: {repo.remotes.origin.url}')

# Delete a default remote if already present
if repo.remotes.origin.url != target_repo:
    repo.delete_remote(repo.remotes.origin.name)

# Create a new remote
try:
    remote = repo.create_remote('origin', url=target_repo)
except git.exc.GitCommandError as error:
    print(f'Error creating remote: {error}')
    
# Reference a remote by its name as part of the object
print(f'Remote name: {repo.remotes.origin.name}')
print(f'Remote URL: {repo.remotes.origin.url}')

#Push changes
print(repo.git.push("origin", "HEAD:refs/for/master"))

标签: pythongitpygithub

解决方案


can we push nothing?

Yes. If there's nothing to push, the push will succeed.

$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

$ git push
Everything up-to-date

But you're pushing to an odd location. HEAD:refs/for/master says to push HEAD to refs/for/master. refs/for/master is not a thing. I think you mean refs/heads/master.

But you shouldn't specify the destination unless you really need to, what HEAD is not master? Let Git figure out the source (the currently checked out branch) and its destination (the upstream of the current branch, or its best guess based on push.default).

You just went through a bunch of work to change origin, you don't need to specify it again. Again, its safer to let push figure out where to push to based on the local branch configuration.

print(repo.git.push())

You also don't need to change origin just for one push. You can instead add a new remote and push to that.

repo.create_remote('other_remote', url=target_repo)
repo.git.push("other_remote")

推荐阅读