Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git merge conflict to always take the newest file

Tags:

git

git-merge

How can I make a git conflict ALWAYS get resolved by taking the newest file (latest changed timestamp), completley without a prompt?

I am building a syncscript with git backend, and I never want to actually merge a file, just override all older copies with the one that was edited/deleted/added last.

Edit: With newest file, I mean newest commit containing that file.

like image 565
Lilleman Avatar asked Sep 30 '11 07:09

Lilleman


People also ask

How do you continue a merge after conflict?

merge : add ' --continue ' option as a synonym for ' git commit ' Teach ' git merge ' the --continue option which allows 'continuing' a merge by completing it. The traditional way of completing a merge after resolving conflicts is to use ' git commit '.

What happens if you get a conflict during a merge?

A merge conflict is an event that occurs when Git is unable to automatically resolve differences in code between two commits. When all the changes in the code occur on different lines or in different files, Git will successfully merge commits without your help.


2 Answers

If anyone came here searching for a solution to avoid resolve conflicts arose from automatically generated files such as package-lock.json, pubspec.lock, *.pbxproj, then you can create a .gitattributes file defining a merge strategy

package-lock.json merge=union

See more info on git attributes

like image 111
ruwan800 Avatar answered Sep 25 '22 09:09

ruwan800


I came up this little merge driver that does what I want. For my purpose it is hard coded to the "master" branch and to the "origin" remote. I do not know how to make these parts dynamic.

#!/usr/bin/env sh
if git merge-file -p -q "$2" "$1" "$3" > /dev/null;
        then git merge-file "$2" "$1" "$3";
        else
                MINE=$(git log --format="%ct" --no-merges master -1);
                THEIRS=$(git log --format="%ct" --no-merges origin/master -1);
                if [ $MINE -gt $THEIRS ];
                        then git merge-file -q --ours "$2" "$1" "$3";
                        else git merge-file -q --theirs "$2" "$1" "$3";
                fi
fi

In short I look for the last commit with git-log that was not a merge, formatted as UNIX timestamp, then I compare them and run a custom git-merge with eiter ours or their version.

As a little bonus, it first makes a check to see if it is possible to merge the file without conflict. If that is possible, it merges both files.

like image 35
Lilleman Avatar answered Sep 21 '22 09:09

Lilleman