aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/git-sync-noconflict
blob: e0117d7730987f991d206565c7c2f492b9038846 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/bin/bash
set -eu

verbose=0
hosthash=$(python3 -c "import uuid, hashlib
print(hashlib.new('sha1', str(uuid.getnode()).encode('utf8')).hexdigest())")
#hostident="${HOSTNAME}"
hostident="${hosthash}"

if [ -d "$(git rev-parse --git-dir)/annex" ]; then
    echo 'Sync: using git annex'
    exec git annex sync "$@"
fi

# determine current branch name
branch_name=$(git symbolic-ref -q --short HEAD)

# remote name
remote_name=$(git config --get branch.${branch_name}.remote || true)

# conflict commit message
conflict_message="Merge conflict autocommit on ${hostident}"

if [ -z "$remote_name" ]; then
    echo "No remote for this repository" >&2
    exit 1
fi

if [ "$(git config --get --bool branch.${branch_name}.sync)" != "true" ]; then
    echo "Branch is not configured to accept git-sync" >&2
    echo "To accept git-sync operation, set current branch sync to true:" >&2
    echo "    git config --bool branch.${branch_name}.sync true" >&2
    exit 1
fi

if [ "$verbose" -ne 0 ]; then
    echo 'Sync: git autocommit'
fi
git add -A "./$(git rev-parse --show-cdup)"
if ! git diff --cached --quiet; then
    git status --short
    git commit -m "Auto-commit on ${hostident}"
fi

if [ "$verbose" -ne 0 ]; then
    echo 'Sync: fetch and merge'
fi

git fetch --quiet

# might fail one time if conflict detected
git merge -m "$conflict_message" || true

if [ "$verbose" -ne 0 ]; then
    echo 'Sync: conflict autocommit'
fi

git status --porcelain | while read -r filename; do
    state="${filename:0:2}"
    filename="${filename:3}"
    ours="${filename}.${hostident}.conflict"
    theirs="${filename}.${remote_name}.conflict"
    case "$state" in
        *U*)
            git checkout --ours -- "$filename"
            mv -i -- "$filename" "$ours"
            git add -- "$ours"
            git checkout --theirs -- "$filename"
            cp -ai -- "$filename" "$theirs"
            git add -- "$filename"
            git add -- "$theirs"
        ;;
    esac
done

# no action is done if there is nothing to commit
if git status --porcelain | grep -q .; then
    git status --short
    git commit -m "$conflict_message"
fi

# should not fail again
git merge -m "$conflict_message"

if [ "$verbose" -ne 0 ]; then
    echo 'Sync: pushing changes'
fi

git push --quiet

if [ "$verbose" -ne 0 ]; then
    echo 'Sync: done'
fi