Git push error '[remote rejected] master -> master (branch is currently checked out)'

前端 未结 30 2660
半阙折子戏
半阙折子戏 2020-11-22 00:07

Yesterday, I posted a question on how to clone a Git repository from one of my machines to another, How can I \'git clone\' from another machine?.

I am now

30条回答
  •  没有蜡笔的小新
    2020-11-22 00:23

    Older versions of Git used to allow pushes to the currently checked out branch of a non-bare repository.

    It turns out this was a terribly confusing thing to allow. So they added the warning message you see, which is also terribly confusing.

    If the first repository is just acting as a server then convert it to a bare repository as the other answers recommend and be done with it.

    If however you need to have a shared branch between two repos that are both in use you can achieve it with the following setup

    Repo1 - will act as the server and also be used for development

    Repo2 - will be for development only

    Setup Repo1 as follows

    Create a branch to share work on.

    git branch shared_branch
    

    To be safe, you should also create a $(REPO).git/hooks/update that rejects any changes to anything other than shared_branch, because you don't want people mucking with your private branches.

    repo1/.git/hooks  (GIT_DIR!)$ cat update
    #!/bin/sh
    refname="$1"
    oldrev="$2"
    newrev="$3"
    
    if [ "${refname}" != "refs/heads/shared_branch" ]
    then
       echo "You can only push changes to shared_branch, you cannot push to ${refname}"
       exit 1
    fi
    

    Now create a local branch in repo1 where you will do your actual work.

    git checkout -b my_work --track shared_branch
    Branch my_work set up to track local branch shared_branch.
    Switched to a new branch 'my_work'
    

    (may need to git config --global push.default upstream in order for git push to work)

    Now you can create repo2 with

    git clone path/to/repo1 repo2 
    git checkout shared_branch 
    

    At this point you have both repo1 and repo2 setup to work on local branches that push and pull from shared_branch in repo1, without needing to worry about that error message or having the working directory get out of sync in repo1. Whatever normal workflow you use should work.

提交回复
热议问题