user2813274
user2813274

Reputation: 858

How to keep a folder up-to-date with a git repo?

This is for a shell script that will periodically check github for the latest code, and download, compile, and run it if there is any difference between what I already have locally and what was pulled.

I know I can always clone it to a new directory, and then check for changes, and go from there, but that seems incredibly wasteful, as git should already have the logic for checking for differences between files and updating only those.

To complicate the matter, the "local" version may at some point be the "latest" version, and in this case I want to discard the "new" changes and pull from the "stable" repository

I currently have this:

status=`cd $gitDir && git pull`
if [ "$status" != "Already up-to-date." ];
then
cd $gitDir  && git fetch origin
cd $gitDir  && git reset --hard origin/master

but it fails when the "local" is "newer" - suggestions?

update: I have looked into the clean option, however that gets rid of files excluded in the .gitignore - I want a solution that leave those alone, but discards any changes to the source files and pulls the latest from github.

update #2: I think this is what I need:

git fetch --all
git reset --hard origin/master

but I will need to do some testing, some confirmation that it does what I am looking for would be nice

update #3: it seems either

git reset --hard origin/master
git reset --hard HEAD

works as far as overwriting the local files, but now how do I know when the two are different (looking into git diff.. )

Upvotes: 2

Views: 2980

Answers (2)

reZach
reZach

Reputation: 9459

I wrote about this recently here: https://www.debugandrelease.com/how-to-automatically-keep-git-repositories-up-to-date/

My solution was in Powershell where the script iterates over folders, determines if there is a .git subfolder, calls git stash, git pull and then git stash pop. All of this functionality is available by installing the package and then running the command.

$ Install-Module -Name UpdateGitRepositories
$ Update-GitRepositories

Upvotes: 1

VonC
VonC

Reputation: 1324937

First, since git 1.8.5 (Nov 2013), you can use the -C option for git, as in "git --git-dir not working as expected".

status=`git -C $gitDir pull`
if [ "$status" != "Already up-to-date." ];
then
git -C $gitDir fetch origin
git -C $gitDir reset --hard origin/master

Second, you could listen on your client for a JSON payload coming from GitHub webhook triggered on a push to that GitHub repo.
That way, you wouldn't have to execute your script unless it is actually needed.

Upvotes: 2

Related Questions