In git, is there a simple way of introducing an unrelated branch to a repository?

前端 未结 9 2170
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:11

While helping a friend with a git problem today, I had to introduce a branch that needed to be totally separate from the master branch. The contents of this bra

9条回答
  •  深忆病人
    2020-11-22 07:03

    There is a new feature (since V1.7.2) which makes this task a little more high-level than what's in any of the other answers.

    git checkout now supports the --orphan option. From the man page:

    git checkout [-q] [-f] [-m] --orphan []

    Create a new orphan branch, named , started from and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.

    This doesn't do exactly what the asker wanted, because it populates the index and the working tree from (since this is, after all, a checkout command). The only other action necessary is to remove any unwanted items from the working tree and index. Unfortunately, git reset --hard doesn't work, but git rm -rf . can be used instead (I believe this is equivalent to rm .git/index; git clean -fdx given in other answers).


    In summary:

    git checkout --orphan newbranch
    git rm -rf .
    
    git add your files
    git commit -m 'Initial commit'
    

    I left unspecified because it defaults to HEAD, and we don't really care anyway. This sequence does essentially the same thing as the command sequence in Artem's answer, just without resorting to scary plumbing commands.

提交回复
热议问题