Home > OS >  Reinitialize an existing git repository
Reinitialize an existing git repository

Time:09-22

I have the following situation: there is a Gitlab repo, which has been initialized with the default branch XXX instead of master. The branch XXX already has some commits there.

The target is to reinitialize the repo where the master branch is the default and empty one. The existing changes need to be in a feature branch, which should be branched from the empty master.

update: in order to explain the target better, the current state:

1-2-3-...-n
^
xxx

the desired state:

master
▼
1
 \
  2-3-...-n
  ^
  xxx

it also makes sense to add that the situation allows to squash all existing commits in the branch xxx to one "initial" if it is required.

CodePudding user response:

To put it visually, it sounds like you want to go from this:

o---o---o
        ^
        master

To this:

o---o----o
^        ^
master   feature

However, you also said:

The existing changes need to be in a feature branch, which should be branched from the empty master.

In Git, there's no concept of an "empty" branch; a branch is a pointer to the last of a sequence of commits. This means that you have to point master to the first commit in the repository (i.e. the root commit).

Here's how you do it:

# Create the 'feature' branch pointing to the commit currently referenced by 'master'
git branch feature master

# Checkout the 'master' branch, if you haven't already
git switch master

# Reset 'master' to the root commit
git reset --hard master~2 

Alternatively, you could get rid of the master branch for the time being, and simply recreate it later when you want to "merge" feature into master.

Here's one quick way of doing it as suggested by @tripleee:

# Rename 'master' to 'feature'
git branch -m master feature

At this point, you'd just have feature:

o---o---o
        ^
        feature

Merging feature into master then becomes simply a matter of creating the master branch on the same commit as feature:

git branch master feature

Which would look like this:

o---o---o
        ^
        feature, master

CodePudding user response:

First, you can just create a feature branch at the current XXX:

git checkout -b feature XXX

To create a new master branch, use the --orphaned flag:

git checkout --orphaned master
git rm -rf .

The second command is necessary in order to clean up the working directory.

Aside

While I use feature branches for my work in existing projects, I often will make the first few commits of a new project directly to master. This is often where I'm just generating all the boilerplate for a new project in the current framework, so there isn't really a need for the typical code review process that my teams use.

  • Related