Importing an existing heritage project into Git

Tags:

For many years I have kept my projects in various archive directories. Now I am converting most of them to git, as a useful means of version control and because it's convenient to use with my repositories on GitHub and BitBucket.

Here is an amusing little Bash script which may help you create and populate new git repositories, with existing file history based on the files' dates.

#!/usr/bin/bash

# call as:
#   git-create.sh myfile.pl.*
# Assuming a directory containing files
    # myfile.pl.20090627
    # myfile.pl.20101202
    # myfile.pl.20120123
    # myfile.pl.20120409
    # myfile.pl.20130123
    # myfile.pl.20130220
    # myfile.pl.20130817
# ...or any set of files where the final extension part is different,
# we want to:
# * create a git repository, if it does not already exist
# * delete the existing myfile.pl~
# * for each of the files on the command line, remove the final
#   extension (date part) so the file is renamed to (in this example)
#   myfile.pl
# * "git add" the first myfile.pl to the repository
# * "git commit" each of the versions, using the file's date as the
#   "Author Date" of the commit.
# * When finished, rename myfile.pl~ back to myfile.pl

if [ ! -e .git -a ! -d .git ]
then
  echo "Creating Git Repository"
  git init
fi

firstfile=$(basename "$1")
base="${firstfile%.*}"

# If both primary and backup file exist -- erase the backup.
# (If only backup file exists, it will remain after)
if [ -e "${base}~" -a -e "${base}" ]
then
  rm "${base}~"
fi

if [ -e "${base}" ]
then
    mv "${base}" "${base}~"
    backup=1
fi

firsttime=1

# OK now we have clearance to start renaming and committing files.

for oldfile in "$@"
  do
    newfile="${oldfile%.*}"

    mv "$oldfile" "$newfile"
    if [ $firsttime ]
    then
        # Add the file, if not already in git
        git add "${newfile}"
        firsttime=0
    fi

    git commit --date="`stat -c %y $newfile`" "$newfile" -m "Automatic import (update comment later!)"
  done