Reputation: 21
For deploying files to some target (Windows) computers, I wanted to create a Python module I can feed with the necessary parameters. The module should then check if the specified repo exists in the outputpath.
a) If it doesn't exist: clone the latest commit from remote
b) If it exists: discard all local changes, pull the latest commit from the remote
A way (that at least this worked for me) would be to delete the local target folder, recreate it and clone everything again.
My code, that only works for an empty dir:
stderr: 'fatal: remote origin already exists.'
import git, os, shutil
#outputfolder there?
if not os.path.exists(MY_outputfolder):
os.makedirs(MY_outputfolder)
repowrk = git.Repo.init(MY_outputfolder)
wrkr = repowrk.create_remote('origin',MY_REMOTE_URL)
wrkr.fetch()
wrkr.pull(wrkr.refs[0].remote_head)
print("---- DONE ----")
Upvotes: 0
Views: 5073
Reputation: 440
For those who would prefer to use gitpython proper, rather than the codified version of the command line interface:
# Create a new branch
new_branch = repo.create_head("new_branch")
# Point your head to the new branch. Note that no working tree changes have taken place yet
repo.head.reference=new_branch
# Perform a reset. Note that index and working_tree must be set to True
# to ensure that the staging area and working tree are overwritten
repo.head.reset(index=True, working_tree=True)
Upvotes: 1
Reputation: 21
This is the code, that solved my problem.
a.) Output directory contains a .git folder: Assume, this is a local repo. Revert all local changes, purge unversioned files
b.) Output directory does not contain a .git folder (or filetree does not exist): Assume the target directory is dirty or not a local repository. Delete target tree and clone the remote directory to the specified target.
outdir_checker = outdir+'\.git'
if os.path.exists(outdir_checker):
repo_worker = git.Repo.init(outdir)
repo_worker.git.fetch(remote_url)
repo_worker.git.reset('--hard')
repo_worker.git.clean('-fdx')
print('git dir not created; already existed')
if not os.path.exists(outdir_checker):
shutil.rmtree(outdir, ignore_errors=True)
os.makedirs(outdir)
git.Repo.clone_from(remote_url, outdir)
print('git dir created')
Upvotes: 1
Reputation: 2061
If the repo exists and you want to discard all local changes, and pull latest commit from remote, you can use the following commands:
# discard any current changes
repo.git.reset('--hard')
# if you need to reset to a specific branch:
repo.git.reset('--hard','origin/master')
# pull in the changes from from the remote
repo.remotes.origin.pull()
With these commands you don't have to delete the repo and clone again.
You can check the doc here for more information.
Upvotes: 3