1

I want to disable committing if you are not on a branch.

I have lost some code on a development server, because code was committed, but never pushed...

Is it possible to stop git from committing, if you are not on a branch?

Update: I am not on a branch since I have done "git checkout mytag" before.

guettli
  • 25,042
  • 81
  • 346
  • 663
  • You are always on a branch if you have done `git init` on that directory. – lukas.pukenis Jan 29 '14 at 10:27
  • 2
    It may help to use a shell prompt which includes the branch name in it, it's much easier to spot such mistakes then. – Jakub Kotowski Jan 29 '14 at 10:27
  • 1
    Actually your commits were not lost, they are just not accessible by any branch. You can still type 'git reflog' and see these commits and their hashes. Then you can add these commits to your current branch, using git cherry-pick (or in any other way you'd like to). – Michał Ciuba Jan 29 '14 at 11:00

2 Answers2

1

You can use Git Hooks to achieve that.

I've found a pre-commit hook on GitHub that does exactly what you want:

#!/bin/sh


if ! git symbolic-ref HEAD &> /dev/null; then
  echo "You are in a detached head state! Commit has been blocked. (Use --no-verify to bypass this check.)"
  exit 1
fi

Put it in a file named pre-commit in .git/hooks directory and make this file executable.

Michał Ciuba
  • 7,876
  • 2
  • 33
  • 59
0

In principal, if you use a git repository for your project you are always on a branch, so the first part of your question is confusing. Then, for the second statement, it should not be possible to lose code with git, you can retrace your commits to find the code back. But the confusing part of this part is that you make commits locally and push them to your remote branch. Then, lastly, to answer your question, depending on your environment/IDE, it is possible to stop committing by simply not committing. Since this is mostly a manual task.

I would have like to comment this (not enough points), since it is wise that you explain your situation a bit better and mention what IDE you're using and the branch and possible commits/commands you made.

About losing the code, you can revert your branch to a previous commit. If you stash your current changes you even not necessarily lose any of the code since that commit. Check the following thread:

How to revert Git repository to a previous commit?

Community
  • 1
  • 1
jvdp
  • 149
  • 8
  • 2
    There is a state called 'detached HEAD' when you are not on any branch. It happens after 'git checkout , for example. – Michał Ciuba Jan 29 '14 at 10:53
  • True; this is also further demonstrated in the top answer in the link, and hence the 'In principal' in the answer. – jvdp Jan 29 '14 at 11:20