Skip to content

Instantly share code, notes, and snippets.

@mendeza
Last active February 26, 2020 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mendeza/eaeafb1c0e018ffd472bc8fae2a8462c to your computer and use it in GitHub Desktop.
Save mendeza/eaeafb1c0e018ffd472bc8fae2a8462c to your computer and use it in GitHub Desktop.

Scenario: "Git Backup"

You are using git as a backup tool and wish to both push and pull between two local repos, the second of which is a clone of the first.

For example, you may initialize a Markdown notes repo on your laptop's startup drive. You author, save (and version) your notes primarily in this repo, but also "backup" the content by cloning the repo to an external drive. At intervals, you pull changes from the first repo into the second (either manually, or as a cron job).

Problem

You might assume there would be no problem with authoring in the cloned repo and pushing back to its origin (the first repo). However, attempting this is met with an unpleasant surprise:

remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: is denied, because it will make the index and work tree inconsistent
remote: with what you pushed, and will require 'git reset --hard' to match
remote: the work tree to HEAD.
remote:
remote: You can set the 'receive.denyCurrentBranch' configuration variable
remote: to 'ignore' or 'warn' in the remote repository to allow pushing into
remote: its current branch; however, this is not recommended unless you
remote: arranged to update its work tree to match what you pushed in some
remote: other way.
remote:
remote: To squelch this message and still keep the default behaviour, set
remote: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To /Users/aaron/Documents/notes
 ! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '/path/to/origin/notes'

Contrary to the last line above, not only does some ref fail to be pushed, in fact none are pushed. Prior to Git 2.3.0 workarounds existed for this problem, but they were either ugly or slightly laborious. From 2.3.0 onward the previous behavior is kept as the default, but a configuration option is added to obviate the problem.

Solution

Add this setting to the configuration of the origin repo. Nota Bene: Push will continue to fail if the origin repo is in a dirty state.

git config receive.denyCurrentBranch updateInstead

Reference

https://stackoverflow.com/questions/804545/what-is-this-git-warning-message-when-pushing-changes-to-a-remote-repository/28262104#28262104

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment