Git click through GitPython

I have this code in Python (using "import git"):

repo = git.Repo("my_repository")
repo.git.add("bla.txt")
repo.git.commit("my commit description")

Now I want to push this commit. I tried a lot, not succeeding. The Python command should look like this Bash command:

git push origin HEAD:refs/for/master
+5
source share
5 answers

You can try the following. Perhaps your problem has been resolved ...

repo.git.pull('origin', new_branch)
repo.git.push('origin', new_branch)
+2
source

Below is the code for git add, git commitand then git pushusing GitPython .

Install GitPython using pip install gitpython.

from git import Repo

PATH_OF_GIT_REPO = r'path\to\your\project\folder\.git'  # make sure .git folder is properly configured
COMMIT_MESSAGE = 'comment from python script'

def git_push():
    try:
        repo = Repo(PATH_OF_GIT_REPO)
        repo.git.add(update=True)
        repo.index.commit(COMMIT_MESSAGE)
        origin = repo.remote(name='origin')
        origin.push()
    except:
        print('Some error occured while pushing the code')
    finally:
        print('Code push from script succeeded')       

git_push()
+2
source

gitpython http://gitpython.readthedocs.io/en/stable/tutorial.html. - origin = repo.create_remote('origin', repo.remotes.origin.url)

origin.pull()

" "

empty_repo = git.Repo.init(osp.join(rw_dir, 'empty'))
origin = empty_repo.create_remote('origin', repo.remotes.origin.url)
assert origin.exists()
assert origin == empty_repo.remotes.origin == empty_repo.remotes['origin']
origin.fetch()                  # assure we actually have data. fetch() returns useful information
# Setup a local tracking branch of a remote branch
empty_repo.create_head('master', origin.refs.master)  # create local branch "master" from remote "master"
empty_repo.heads.master.set_tracking_branch(origin.refs.master)  # set local "master" to track remote "master
empty_repo.heads.master.checkout()  # checkout local "master" to working tree
# Three above commands in one:
empty_repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout()
# rename remotes
origin.rename('new_origin')
# push and pull behaves similarly to `git push|pull`
origin.pull()
origin.push()
# assert not empty_repo.delete_remote(origin).exists()     # create and delete remotes
0
source

I had the same problem. I solved it by calling

repo.git.push("origin", "HEAD:refs/for/master")
0
source

This can be achieved using an index ( described a little here ), for example, like this:


from git import Repo
repo = Repo('path/to/git/repo')  # if repo is CWD just do '.'

repo.index.add(['bla.txt'])
repo.index.commit('my commit description')
origin = repo.remote('origin')
origin.push()
0
source

Source: https://habr.com/ru/post/1667678/


All Articles