How to Import past history into new git repo

106 Views Asked by At

I have a lot of old scripts I want to import into GitHub. I’m wondering if there is a way to add history that happened before the git started tracking the changes.

What is happening now: I make a repo on Github or a local git. I add the old script files to it and it looks like I just created the file in git, but the file could have been originally created several years ago.

Example file

!/bin/bash
# <date> created this script to do this
# yyyymmdd added feature 
# yyyymmdd fixed something 

I was tracking my changes in the heading of the file I was updating. Is there a way to add the version control information on in the new git repo?

If there is s better way to add the old script’s history let me know.

1

There are 1 best solutions below

1
knittl On

It is possible to do it with a single repo only, but using two separate repositories in the process makes it easier and provides less chance for error.

First, create a new, empty Git repo and add your file(s):

git init old-history
cd old-history
# copy your file, make sure you use the expected directory structure
git add your_file
git commit -m 'adding file' # optionally specify --date=... if you require that
# change file content / add more files / create more commits, as desired
# note down the commit id of the last commit! (git rev-parse HEAD)

Once you have that, it is time to graft the two repositories together:

git remote add existing ../path/to/your/existing/new-repo
git fetch existing
# find the root commit of your existing repo (assuming a "master" branch):
root="$(git log --oneline existing/master | tail -1)"
# replace the root commit with a commit that links both histories:
git replace --graft "$root" "$(git rev-parse HEAD)"

At this point, when you run git log or gitk, you should see the grafted history that looks like your scripts were always part of the repo.

Ultimately, you want to persist the grafted history with git filter-branch. Please note that this will change the commit hashes of all commits of your existing repo!

git filter-branch --tag-name-filter cat -- --all

Finally, push the rewritten history pack to your existing repo/upstream or fetch the rewritten history. If this repo was shared, everybody with a clone (and you, if you had multiple clones of the same repo) needs to throw away their local version and replace it with the new, rewritten history.