Skip to content

Instantly share code, notes, and snippets.

@kekru
Last active February 26, 2024 05:51
Show Gist options
  • Save kekru/88808f7dfbdcc5375cfcc99f9812d19f to your computer and use it in GitHub Desktop.
Save kekru/88808f7dfbdcc5375cfcc99f9812d19f to your computer and use it in GitHub Desktop.
git: Copy files to new branch without history, using a squash merge

Git: New branch with files but no history

This is how to copy your files from a given git branch to a new empty branch, using a squash merge.
This example will copy files from branch old-branch to target-branch

# First be sure, that you don't have uncommitted working changes. They will be deleted

# Checkout a new empty branch without history
git checkout --orphan target-branch

# clear index and working tree
git rm -rf .

# Create empty commit
echo "Initial Commit" > test.md && git add test.md && git commit -m "Initial Commit"

# Merge the old branch to new one, using a squash
git merge --squash old-branch --allow-unrelated-histories

# Perform a commit, because the squash merge did not create a commit yet
git commit -m "sources from old repo"
@aljgom
Copy link

aljgom commented Sep 12, 2022

Is there a difference between the posted code and this?

git checkout old-branch
git checkout --orphan target-branch
git commit -m "sources from old repo"

other than the test.md file, but as I understand it, that was created only to create an empty commit?

@kekru
Copy link
Author

kekru commented Sep 14, 2022

@aljgom I just found it cleaner to work with git merge than with git add . && git commit -m ...
Maybe on git add we could have any unwanted changes, for example on Windows, when file modifiers (read, write, exec) or the line endings easily change, because of wrong git config.

I think git merge is a little safer.

The test.md is needed, because the new branch needs any initial commit, otherwise the git merge would not work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment