I have solved some merge conflicts, committed then tried to Push my changes and received the following error:
c:Program Files (x86)Gitbingit.exe push --recurse-submodules=check "origin" master:master
Done
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: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To C:/Development/GIT_Repo/Project
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to 'C:/Development/GIT_Repo/Project'
Does anyone know what could be causing this error?
Cœur
36.4k25 gold badges191 silver badges259 bronze badges
asked Jun 20, 2012 at 10:40
3
Reason:You are pushing to a Non-Bare Repository
There are two types of repositories: bare and non-bare
Bare repositories do not have a working copy and you can push to them. Those are the types of repositories you get in Github! If you want to create a bare repository, you can use
git init --bare
So, in short, you can’t push to a non-bare repository (Edit: Well, you can’t push to the currently checked out branch of a repository. With a bare repository, you can push to any branch since none are checked out. Although possible, pushing to non-bare repositories is not common). What you can do, is to fetch and merge from the other repository. This is how the pull request
that you can see in Github works. You ask them to pull from you, and you don’t force-push into them.
Update: Thanks to VonC for pointing this out, in the latest git versions (currently 2.3.0), pushing to the checked out branch of a non-bare repository is possible. Nevertheless, you still cannot push to a dirty working tree, which is not a safe operation anyway.
answered Jun 20, 2012 at 10:47
ShahbazShahbaz
45.7k18 gold badges118 silver badges180 bronze badges
11
I solved this problem by first verifying the that remote did not have anything checked out (it really was not supposed to), and then made it bare with:
$ git config --bool core.bare true
After that git push worked fine.
dotancohen
29.3k35 gold badges136 silver badges194 bronze badges
answered Jun 20, 2014 at 21:11
Sasha PachevSasha Pachev
5,0443 gold badges21 silver badges19 bronze badges
4
Summary
You cannot push to the one checked out branch of a repository because it would mess with the user of that repository in a way that will most probably end with loss of data and history. But you can push to any other branch of the same repository.
As bare repositories never have any branch checked out, you can always push to any branch of a bare repository.
Autopsy of the problem
When a branch is checked out, committing will add a new commit with the current branch’s head as its parent and move the branch’s head to be that new commit.
So
A ← B
↑
[HEAD,branch1]
becomes
A ← B ← C
↑
[HEAD,branch1]
But if someone could push to that branch inbetween, the user would get itself in what git calls detached head mode:
A ← B ← X
↑ ↑
[HEAD] [branch1]
Now the user is not in branch1 anymore, without having explicitly asked to check out another branch. Worse, the user is now outside any branch, and any new commit will just be dangling:
[HEAD]
↓
C
↙
A ← B ← X
↑
[branch1]
Hypothetically, if at this point, the user checks out another branch, then this dangling commit becomes fair game for Git’s garbage collector.
answered Feb 14, 2013 at 15:35
Nowhere manNowhere man
4,9673 gold badges30 silver badges42 bronze badges
1
For me, the following did the trick:
git config --global receive.denyCurrentBranch updateInstead
I set up drive F:, almost in its entirety, to sync between my Windows 10 desktop and my Windows 10 laptop, using Git. I ended up running the above command on both machines.
First I shared the desktop’s F drive on the network. Then I was able to clone it on my laptop by running:
F:
git clone 'file://///DESKTOP-PC/f'
Unfortunately, all the files ended up under «F:f» on my laptop, not under F: directly. But I was able to cut and paste them manually. Git still worked from the new location afterwards.
Then I tried making some changes to files on the laptop, committing them, and pushing them back to the desktop. That didn’t work until I ran the git config command mentioned above.
Note that I ran all these commands from within Windows PowerShell, on both machines.
UPDATE: I still had issues pushing changes, in some cases. I finally just started pulling changes instead, by running the following on the computer I want to pull the latest commit(s) to:
git pull --all --prune
Wai Ha Lee
8,41977 gold badges60 silver badges90 bronze badges
answered Mar 12, 2016 at 2:17
1
cd into the repo/directory that you’re pushing into on the remote machine and enter
$ git config core.bare true
answered May 20, 2015 at 3:09
Ricky SahuRicky Sahu
22.7k4 gold badges41 silver badges32 bronze badges
2
As there’s already an existing repository, running
git config --bool core.bare true
on the remote repository should suffice
From the core.bare documentation
If true (bare = true), the repository is assumed to be bare with no working directory associated. If this is the case a number of commands that require a working directory will be disabled, such as git-add or git-merge (but you will be able to push to it).
This setting is automatically guessed by git-clone or git-init when the repository is created. By default a repository that ends in «/.git» is assumed to be not bare (bare = false), while all other repositories are assumed to be bare (bare = true).
answered Dec 18, 2014 at 17:11
JohnnyJohnny
2662 silver badges6 bronze badges
0
TLDR
- Pull & push again:
git pull &&& git push
. - Still a problem? Push into different branch:
git push origin master:foo
and merge it on remote repo. - Alternatively force the push by adding
-f
(denyCurrentBranch
needs to be ignored).
Basically the error means that your repository is not up-to-date with the remote code (its index and work tree is inconsistent with what you pushed).
Normally you should pull
first to get the recent changes and push
it again.
If won’t help, try pushing into different branch, e.g.:
git push origin master:foo
then merge this branch on the remote repository back with master.
If you changed some past commits intentionally via git rebase
and you want to override repo with your changes, you probably want to force the push by adding -f
/--force
parameter (not recommended if you didn’t do rebase
). If still won’t work, you need to set receive.denyCurrentBranch
to ignore
on remote as suggested by a git message via:
git config receive.denyCurrentBranch ignore
answered Jul 31, 2014 at 10:34
kenorbkenorb
149k80 gold badges668 silver badges723 bronze badges
1
As mentioned in other answers, you can not push to a checked-out branch. Let’s start there.
From the remote server, Let’s checkout our remote repository to a temporary branch.
git checkout -b temp
Now from our local repository, we can push to the master branch.
git push
But this is not a permanent solution. Future pushes will bring the same problem. To solve this once and for all, you need to turn the remote repository into a bare repository. From the remote server, enter:
git config core.bare true
Now you can push to the remote without any problems.
In future, create your remote repositories using the --bare
option like so:
git init --bare
answered Oct 2, 2021 at 18:17
GilbertGilbert
2,28523 silver badges28 bronze badges
Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.
answered Jun 23, 2013 at 5:25
JZAUJZAU
3,52030 silver badges36 bronze badges
I has this error because the git repo was (accidentally) initialised twice on the same location : first as a non-bare repo and shortly after as a bare repo. Because the .git folder remains, git assumes the repository is non-bare. Removing the .git folder and working directory data solved the issue.
answered Jun 16, 2017 at 8:20
xastorxastor
4825 silver badges17 bronze badges
1
It’s works for me
-
git config --global receive.denyCurrentBranch updateInstead
-
git push origin master
answered Jul 11, 2020 at 8:00
I has the same issue and try to do this:
- Ssh to gitlab server (remote server machine not your personal machine) and found [core]:bare value is false in yourRepo/.git/config
2. vim config and edit it to true
Now,it’s fine.I can push to master.
answered Jan 26, 2022 at 6:29
I got this error when I was playing around while reading progit. I made a local repository, then fetched it in another repo on the same file system, made an edit and tried to push. After reading NowhereMan’s answer, a quick fix was to go to the «remote» directory and temporarily checkout another commit, push from the directory I made changes in, then go back and put the head back on master.
answered Dec 31, 2019 at 16:13
In another post’s answer explain this problem.
In my view, a better way to do is:
- For the repository in your remote server:
git branch -b work
,work
is a working branch specially for remote server. - Push your local commits to your remote server and local branch’s name (
dev
) should be different fromwork
to avoid mess up, and now no errors will appear forgit push origin dev
. - Merge
dev
towork
in your remote server.git merge
.
answered Sep 17, 2022 at 6:03
Содержание
- Git: выделяем глобальный репозитарий для проекта
- Записная книжка рассеянного [в пространстве и времени] программиста
- Git: выделяем глобальный репозитарий для проекта
- Git Push error: refusing to update checked out branch (Source Control)
- Set Repository as ‘Bare’
- Change the checked out branch
- refusing to update checked out branch: refs/heads/master error #20
- Comments
- GIT — Errors
- git pull fails : fatal: ‘ /path/to/some/dir ‘ does not appear to be a git repository
- Situation
- Details
- Solution
- git clone fails : fatal: unable to access ‘ https://github.com/ . /. .git/ ‘: gnutls_handshake() failed: An unexpected TLS packet was received.
- patch fragment without header + Your edited hunk does not apply during git add —interactive
- Situation
- Details
- Solution
- Git command fails : fatal: unable to access ‘ https:// git.domain.tld/path/to/myRepository/ ‘: server certificate verification failed.
- Situation
- Solution
- git push origin master ends up with remote: error: refusing to update checked out branch: refs/heads/master
- Your branch is ahead of ‘origin/master’ by n commits. after successfully pulling from origin to remote
- Situation
- Details
- Solution
- git pull complains Your local changes to ‘ myFile ‘ would be overwritten by merge. Aborting.
- Git — вопрос от новичка
Git: выделяем глобальный репозитарий для проекта
Записная книжка рассеянного [в пространстве и времени] программиста
Git: выделяем глобальный репозитарий для проекта
Иногда мы копируем папку с проектом на отдельную машину, а затем пытаемся использовать его в качестве мастер-репозитария.
Но при попытке сделать пуш в этот репозитарий нас подстерегает ошибка.«` $ git push origin master
Counting objects: 30, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (16/16), done.
Writing objects: 100% (17/17), 3.31 KiB | 0 bytes/s, done.
Total 17 (delta 4), reused 0 (delta 0)
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: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require ‘git reset –hard’ to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set ‘receive.denyCurrentBranch’ configuration variable to
remote: error: ‘ignore’ or ‘warn’ in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: ‘receive.denyCurrentBranch’ configuration variable to ‘refuse’.
To /project/path
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to ‘/project/path’
Если нет — смотрим выше.
А еще можно сказать иниту, чтобы создавал bare сразу.
Источник
Git Push error: refusing to update checked out branch (Source Control)
August 4, 2014
Recently, I cloned a repository on my machine and made some changes to it. As I was pushing my changes back to the original repo, push failed with the error message:
“refusing to update checked out branch: refs/heads/master. By default, updating the current branch in a non-bare repository is denied…”
There are two things to note here in the error message. First the original repo is non-bare, secondly the push is to a branch which is currently checked out. Following are two possible ways to overcome the issue relating to bare repos and currently checked out branch.
Set Repository as ‘Bare’
Bare repositories do not have any working copy. Changes are not done directly to these repositories, rather changes are pushed from clones. Repositories hosted at GitHub are of this type.
One way to resolve the above issue is to make the repository ‘bare’. This can be done by running below command in original repo folder:
Change the checked out branch
If you don’t want to convert your original repository to bare, another option is change the current branch. This can be done by:
In case, there is only one branch in the repository, a temporary branch could be created and checked out:
Once the push is executed, run the following commands to bring things back to original state:
Above will delete the temporary branch and checkout the master branch.
Источник
refusing to update checked out branch: refs/heads/master error #20
It seems that now edeliver does not handle well cases when SSH connection was dropped.
I’ve tried to run my build twice:
/.profile cd /app/myapp/build &> /dev/null if [ «mix» = «rebar» ]; then echo «using rebar to generate release» &> /dev/null ./rebar -f generate &> /dev/null elif [ «mix» = «relx» ]; then echo «using relx to generate release» &> /dev/null ./relx release &> /dev/null elif [ «mix» = «mix» ]; then echo «using mix to generate release» &> /dev/null MIX_ENV=prod mix release &> /dev/null fi &> /dev/null vagrant@trusty64:/vagrant$ mix edeliver build release BUILDING RELEASE OF PLUMBER APP ON BUILD HOST ——> Authorizing hosts ——> Ensuring hosts are ready to accept git pushes ——> Pushing new commits with git to: app@edeliver.stag.srv.myapp.org ——> Resetting remote hosts to 97f757b0fee0f7ac7602152472cf11bc301bc346 ——> Stashing build directory on remote build host FAILED 1: ssh -o ConnectTimeout=3 app@edeliver.stag.srv.myapp.org set -e [ -f
/.profile cd /app/myapp/build &> /dev/null [[ $(git stash list | wc -l) -gt 0 ]] && _oldest_stash=$(git stash list | tail -1 | grep -o ‘stash@<[0-9]+>‘ | grep -o ‘[0-9]+’) || _oldest_stash=0 [[ $ <_oldest_stash>-gt 50 ]] && git stash drop stash@ <$_oldest_stash>&> /dev/null git stash —all &> /dev/null &> /dev/null»>
And then, for the next time I got the following error:
Removing and cloning the repo again on the target machine resolves the issue. It would be nice if edeliver cleaned up repo by itself in case of trouble.
I must admit that the generally speaking, requirement to have valid, cloned git repo on the target machine is a trouble-maker.
First of all, while provisioning build servers you must clone the repo, which forces you to use different authentication scheme to clone it from git than one that is used by the developers on a daily basis.
Than you must ensure that it is valid to avoid problems mentioned before.
Wouldn’t it be just easier to always clone fresh repo before building starts and use SSH key forwarding to ensure that developer’s credentials are used?
The text was updated successfully, but these errors were encountered:
Источник
GIT — Errors
git pull fails : fatal: ‘ /path/to/some/dir ‘ does not appear to be a git repository
Situation
Details
- you have either explicitly typed it or configured Git so that it receives a command such as :
Solution
Several reasons may cause this error :
- the URL you’re trying to connect to actually is not available :
- for an https://. URL or a git@. SSH URL :
- network / connectivity issue
- server down
- for a /path/to/some/dir URL :
- is the storage media actually mounted ?
- for an https://. URL or a git@. SSH URL :
- OR : the Git repository you’re trying to pull from has several configured remotes — some of which that are intermittently available (only at home / only at work) — and you’re actually trying to pull from the wrong remote. Make sure you’ve not typed git pull origin master automatically
git clone fails : fatal: unable to access ‘ https://github.com/ . /. .git/ ‘: gnutls_handshake() failed: An unexpected TLS packet was received.
Situation
Details
This answer has some interesting information about editing hunks (but not the answer to the current issue, though )
Solution
Possible cause | Solution |
---|---|
a Git bug (sources: 1, 2) | Don’t split + edit hunks, edit them directly. |
My editor ( Emacs ) is configured to delete trailing whitespace before saving, which deletes context lines from the patch (these lines contain only a single SPACE character) (source) |
|
Git command fails : fatal: unable to access ‘ https:// git.domain.tld/path/to/myRepository/ ‘: server certificate verification failed.
Situation
git clone https:// git.domain.tld/path/to/myRepository/
Solution
- This applies to any Git command, not only git clone.
- To make this permanent :
git push origin master ends up with remote: error: refusing to update checked out branch: refs/heads/master
When trying to git push from a remote back to the origin , I get this error message :
As said by this error message : you just can NOT push to a non- bare Git repository (details).
Some solutions are still available :
- pull from your origin instead of push ing from a remote
- OR check out a different branch in the target repository, then push
- OR make the original repository bare , and push whatever you like
- OR set the receive.denyCurrentBranch in config as suggested to allow pushing to checked-out branches, and take care of the discrepancies
- OR possibly even force push would work, I don’t suggest that
Your branch is ahead of ‘origin/master’ by n commits. after successfully pulling from origin to remote
Situation
Working with local and remote branches, when sitting on a remote branch and after pulling from origin to remote , git status says :
Details
On the remote , the commits I made on the origin are there. It looks like only the count of commits is wrong.
Solution
On the remote branch, run :
git pull complains Your local changes to ‘ myFile ‘ would be overwritten by merge. Aborting.
This error message is fairly explicit. To fix this :
- git stash : save your work in progress
- git pull -f : get updates from the repository
- git stash pop : apply the local changes on top of the update
Источник
Git — вопрос от новичка
Осваиваю git. В самом начале пути.
Есть удаленный сервер. Есть локальный компьютер. Создал на сервере папку /home/alex/test/. В ней тестовый файл 1.test
Далее на сервере в консоли ввел команды: cd /home/alex/test/ git init git add . git commit
Далее на локальном компьютере ввел команду: git clone ssh://alex@123.45.678.910:22/home/alex/test/
Все успешно скопировалось на локальный компьютер в созданную папку test
Далее я на локальном компьютере переименовал файл 1.test в 2.test и выполнил команды git add . git commit
Далее я ввожу команду git push но получаю сообщение: fatal: Not a git repository (or any parent up to mount point /home) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
Такое же сообщение я получаю если изменяю файл на сервере, делаю commit а потом на локальном пытаюсь выполнить git pull, git fetch.
Перевод этого текста мне ничего не дает. В рунете информации я не нашел. Может кто подскажет что я делаю не так?
А git демон точно есть и запущен ?
нужно сделать git init?
google://git bare repository
а его разве нужно запускать если соединение по ssh ?
По-моему, ты просто умудрился из каталога test вывалиться в alex.
Это значит, что git не нашел директорию .git в текущей или родительских директориях. Проверь, где находишься, перед тем, как писать git push.
Далее я ввожу команду git push но получаю сообщение:
По дефолту git push в не-bare репозиторий не работает же (безотносительно твоей ошибки).
Я перешел из папки alex в test, и выполнил git push еще раз: Сейчас ошибка имеет такой вид:
Подсчет объектов: 2, готово. Delta compression using up to 4 threads. Сжатие объектов: 100% (2/2), готово. Запись объектов: 100% (2/2), 244 bytes | 0 bytes/s, готово. Total 2 (delta 0), reused 0 (delta 0) 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: error: is denied, because it will make the index and work tree inconsistent remote: error: with what you pushed, and will require ‘git reset —hard’ to match remote: error: the work tree to HEAD. remote: error: remote: error: You can set ‘receive.denyCurrentBranch’ configuration variable to remote: error: ‘ignore’ or ‘warn’ in the remote repository to allow pushing into remote: error: its current branch; however, this is not recommended unless you remote: error: arranged to update its work tree to match what you pushed in some remote: error: other way. remote: error: remote: error: To squelch this message and still keep the default behaviour, set remote: error: ‘receive.denyCurrentBranch’ configuration variable to ‘refuse’. To ssh://alex@123.456.78.910:22/home/alex/test/.git ! [remote rejected] master -> master (branch is currently checked out) error: не удалось отправить некоторые ссылки в «ssh://alex@123.456.78.910:22/home/alex/test/.git»
Скажите, как я могу отправить изменения в серверный репозиторий?
Теперь вы можете создать пустой репозиторий для них, запустив git init с параметром —bare
Скажите, как я могу отправить изменения в серверный репозиторий?
Есть несколько вариантов:
- Делай push в другую ветку (например, $ git push origin master:remote-master ), а затем делай merge/rebase.
- Переключай текущую checked-out ветку в удалённом репозитории перед push’ем.
- Используй bare-репозиторий.
remote: error: You can set ‘receive.denyCurrentBranch’ configuration variable to
remote: error: ‘ignore’ or ‘warn’
Неправда. Не работает только в зачекаутенную ветку.
Источник
27 Jul 2014
Иногда мы копируем папку с проектом на отдельную машину, а затем пытаемся использовать его в качестве мастер-репозитария.
Но при попытке сделать пуш в этот репозитарий нас подстерегает ошибка.«`
$ git push origin master
Counting objects: 30, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (16/16), done.
Writing objects: 100% (17/17), 3.31 KiB | 0 bytes/s, done.
Total 17 (delta 4), reused 0 (delta 0)
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: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require ‘git reset –hard’ to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set ‘receive.denyCurrentBranch’ configuration variable to
remote: error: ‘ignore’ or ‘warn’ in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: ‘receive.denyCurrentBranch’ configuration variable to ‘refuse’.
To /project/path
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to ‘/project/path’
Вообще почему она возникает-то? Разве гит это не распределенная система контроля версий? Распределенная и даже чутка децентрализованная. Совсем-совсем распределенная. А это значит, что пушить изменения можно не только на одно хранилище, а вообще в любой репозитарий. Хоть чуваку за соседний комп. Таким образом разработчикии могут делиться своими наработками.
Но это подразумевает один нюанс: нельзя пушить в ту ветку удаленного репозитария с которой сейчас идет работа.
Суть сообщения в том, что в удаленном репозитарии ветвь, которую мы хотим запушить сейчас, активна (т.е. сделан чекаут на удаленной машине).
А значит и правки в эту ветвь якобы удаленной машиной вносятся (слава роботам!).
Способ первый. Мы заходим в репозитарий и просто чекаутим другую ветку проекта. Профит. :)
Способ второй. Мы узнаем, что существует два типа хранилищ: bare и non bare. Дефолтно при выполнении git init будет создано хранилище второго типа (и при чекауте чужого репощитария так же создается локальный non-bare репозитарий).
Bare значит, то это не рабочий репозитарий, а просто склад веток, куда каждый может пушить. И если мы попробуем поработать с ним напрямую (покоммитить), то нас ждет облом.
Гитхаб предоставляет хранилища именно такого типа.
Второй же тип - это репозитарии разработчика. Активная в данный момент ветвь блокируется на изменение от нелокальных клиентов.
А что делать?
Если реп у нас удаленный и для совместной работы - конвертируем его в bare
```shell
git config --bool core.bare true
Если нет — смотрим выше.
А еще можно сказать иниту, чтобы создавал bare сразу.
Теги:
git
Категории:
Разработка
Добрый день,
При создании локального git хранилища, столкнулся со следующей проблемой.
[git@su-git-01 testdir]$ git init
Initialized empty Git repository in /git/testdir/.git/
[git@su-git-01 testdir]$ touch test.txt && echo "HELLO" >> test.txt
[git@su-git-01 testdir]$ git add test.txt
[git@su-git-01 testdir]$ git commit -m "First Init"
[master (root-commit) d6825e1] First Init
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 test.txt
[git@su-git-01 testdir]$
На клиенте делаю следующие шаги:
$ git clone ssh://git@172.24.4.100:/git/testdir
Cloning into 'testdir'...
git@172.24.4.100's password:
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
Checking connectivity... done.
$ echo "WORL" >> test.txt
$ git commit -m "Second Init"
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
modified: test.txt
no changes added to commit
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
nothing to commit, working directory clean
$ git push origin master
git@172.24.4.100's password:
Counting objects: 5, done.
Writing objects: 100% (3/3), 263 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
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: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To ssh://git@172.24.4.100:/git/testdir
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to 'ssh://git@172.24.4.100:/git/testdir'
Соответственно, после git reset —hard, ошибка остается прежней.
Впервые столкнулся с git, прошу совета, что я делаю не так?
Yaba!!! Made a couple of changes to a Git clone of my project; tried to push the changes to my remote repository and got the errors below.
phiri@PHRLIG001:~/Projects/saldru$ git push laboratory Counting objects: 6, done. Delta compression using up to 4 threads. Compressing objects: 100% (4/4), done. Writing objects: 100% (4/4), 38.96 KiB, done. Total 4 (delta 1), reused 0 (delta 0) 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: error: is denied, because it will make the index and work tree inconsistent remote: error: with what you pushed, and will require 'git reset --hard' to match remote: error: the work tree to HEAD. remote: error: remote: error: You can set 'receive.denyCurrentBranch' configuration variable to remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into remote: error: its current branch; however, this is not recommended unless you remote: error: arranged to update its work tree to match what you pushed in some remote: error: other way. remote: error: remote: error: To squelch this message and still keep the default behaviour, set remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'. To lphiri.cs.uct.ac.za:~/Projects/saldru ! [remote rejected] master -> master (branch is currently checked out) error: failed to push some refs to 'lphiri.cs.uct.ac.za:~/Projects/saldru' phiri@PHRLIG001:~/Projects/saldru$
Git status clearly shows that my current working tree is ahead of my remote repository by one commit.
phiri@PHRLIG001:~/Projects/saldru$ git status # On branch master # Your branch is ahead of 'laboratory/master' by 1 commit. # nothing to commit (working directory clean) phiri@PHRLIG001:~/Projects/saldru$
A quick search online reveals that its a very well documented problem with varying solutions [1, 2]. I particularly found the options below helpful and use them in the order they appear. Note that Option #3 is not a recommended best practice, especially if working in a team.
Option #1: Fool Git by using a dummy branch
cd [remote repo]
git check -b [dummy branch name]
Option #2: Create a bare repo
cd [remote repo]
rm -rf *
mv .git/* .
vi config [and change bare option from false to true]
Option #3: Alter receive.denyCurrentBranch configuration variable
cd <remote repo>
git config receive.denyCurrentBranch warn
phiri@PHRLIG001:~/Sandbox/git/repo$ man git config receive.denyCurrentBranch If set to true or "refuse", git-receive-pack will deny a ref update to the currently checked out branch of a non-bare repository. Such a push is potentially dangerous because it brings the HEAD out of sync with the index and working tree. If set to "warn", print a warning of such a push to stderr, but allow the push to proceed. If set to false or "ignore", allow such pushes with no message. Defaults to "refuse".
Please comment if you notice an anomaly or if you know of other ways to solve this problem.
Bibliography
[1] http://stackoverflow.com/questions/2816369/git-push-error-remote-rejected-master-master-branch-is-currently-checked-o
[2] http://sitaramc.github.com/concepts/bare.html#yeah_yeah_but_why_do_I_need_a_bare_repo_
I solved this problem by first verifying the that remote did not have anything checked out (it really was not supposed to), and then made it bare with:
$ git config --bool core.bare true
After that git push worked fine.
For me, the following did the trick:
git config --global receive.denyCurrentBranch updateInstead
I set up drive F:, almost in its entirety, to sync between my Windows 10 desktop and my Windows 10 laptop, using Git. I ended up running the above command on both machines.
First I shared the desktop’s F drive on the network. Then I was able to clone it on my laptop by running:
F:
git clone 'file://///DESKTOP-PC/f'
Unfortunately, all the files ended up under «F:f» on my laptop, not under F: directly. But I was able to cut and paste them manually. Git still worked from the new location afterwards.
Then I tried making some changes to files on the laptop, committing them, and pushing them back to the desktop. That didn’t work until I ran the git config command mentioned above.
Note that I ran all these commands from within Windows PowerShell, on both machines.
UPDATE: I still had issues pushing changes, in some cases. I finally just started pulling changes instead, by running the following on the computer I want to pull the latest commit(s) to:
git pull --all --prune
Summary
You cannot push to the one checked out branch of a repository because it would mess with the user of that repository in a way that will most probably end with loss of data and history. But you can push to any other branch of the same repository.
As bare repositories never have any branch checked out, you can always push to any branch of a bare repository.
Autopsy of the problem
When a branch is checked out, committing will add a new commit with the current branch’s head as its parent and move the branch’s head to be that new commit.
So
A ← B
↑
[HEAD,branch1]
becomes
A ← B ← C
↑
[HEAD,branch1]
But if someone could push to that branch inbetween, the user would get itself in what git calls detached head mode:
A ← B ← X
↑ ↑
[HEAD] [branch1]
Now the user is not in branch1 anymore, without having explicitly asked to check out another branch. Worse, the user is now outside any branch, and any new commit will just be dangling:
[HEAD]
↓
C
↙
A ← B ← X
↑
[branch1]
Hypothetically, if at this point, the user checks out another branch, then this dangling commit becomes fair game for Git’s garbage collector.
Reason:You are pushing to a Non-Bare Repository
There are two types of repositories: bare and non-bare
Bare repositories do not have a working copy and you can push to them. Those are the types of repositories you get in Github! If you want to create a bare repository, you can use
git init --bare
So, in short, you can’t push to a non-bare repository (Edit: Well, you can’t push to the currently checked out branch of a repository. With a bare repository, you can push to any branch since none are checked out. Although possible, pushing to non-bare repositories is not common). What you can do, is to fetch and merge from the other repository. This is how the pull request
that you can see in Github works. You ask them to pull from you, and you don’t force-push into them.
Update: Thanks to VonC for pointing this out, in the latest git versions (currently 2.3.0), pushing to the checked out branch of a non-bare repository is possible. Nevertheless, you still cannot push to a dirty working tree, which is not a safe operation anyway.