'git push fails if history changes in remote

I have scripts which run some git commands and try to push changes. Those changes are not conflicting changes, since each one works with a different file.

Now what is happening is that when one script pulls and tries to push. in that brief moment if history changes, it is not able to push.

How to make sure that if push fails? it rebases or just patches the code changes?

I dont want to force push since that will rewrite the history and i will lose changes.

Note: these all are working on the same branch.

git


Solution 1:[1]

i think i need NFS or something to make sure, commands run while taking a lock

Actually, since Git 2.23 (Q3 2019), git push has a --atomic option, which reinforces what was already a quasi-atomic operation before.

So as long as the server is set to reject any divergent push (unless --force is used), a git pull --rebase, as commented, will be enough.

# repeat until git push works:
git pull --rebase
git push --force      # which is quasi atomic

Note: go-git does not support rebase, so you might need to wrap that command (git pull --rebase) in a exec.Command call, using go-git/go-git plumbing/transport/file/client.go.


The OP Tilak Raj proposes in the comments:

retry 5 git update-ref -d refs/remotes/origin/main && git pull --rebase=false --no-edit -X ours origin "refs/heads/$BRANCH" && git push -u origin "$BRANCH" &> /tmp/gitplan

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tilak Raj