17 June 2023

Git - Some useful snippets

This is a collection of useful Git scripts and snippets that I have collected over time.

Remove files and ignore

  1. Create a project .gitignore file.
  2. Add rules to your .gitignore for the files/folders you want ignored
  3. Removed the cached copy from git git rm –cached path/to/file,
    1. This will leave the local copy unchanged.
  4. Commit

Delete a file from history completely

Useful for accidently committed secrets; this will delete a committed database.yml in a rails project.

git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch config/datatbase.yml' \
  --prune-empty --tag-name-filter cat -- --all

Separate RSA keys for different accounts

This is useful if you have multiple Github / Gitlab accounts.

Host OtherGit
    Hostname github.com
    IdentityFile ~/.ssh/otherGit
    IdentitiesOnly yes

Host github.com
    Hostname github.com
    IdentityFile ~/.ssh/mainGit
    IdentitiesOnly yes

Then you set the URL’s like so and it will use the different key per.

$ git remote -v
origin  [email protected]:organisation/project.git (fetch)
origin  git@otherGit:organisation/project.git (push)

Manually working with patches

Take a diff

git diff > the_reason.patch

Apply the diff

git apply the_reason.patch

Apply a remote diff

curl https://josephmullins.au/file-0.0.1.diff | git apply

Update author email

If you need to adjust the authors email of commits. You will need to force push after this.

git filter-branch --env-filter 'if [ "$GIT_AUTHOR_EMAIL" = "<old-email>" ]; then
     GIT_AUTHOR_EMAIL=<new-email>;
     GIT_AUTHOR_NAME="<new-name>";
     GIT_COMMITTER_EMAIL=$GIT_AUTHOR_EMAIL;
     GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; fi' -- --all

Set commit date when committing

If you need to set the date when you are committing.

GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git commit -m '...'

Examples

echo "$(date -d'2 days ago')"
-> Wed 26 May 2021 11:49:26 PM ACST
echo "$(date -d'2020-06-13')"
-> Sat 13 Jun 2020 12:00:00 AM ACST

Ammend commit dates

If you need to adjust the date of a commit made.

GIT_COMMITTER_DATE="Wed Jan 6 00:13:46 2021 +1030" git commit --amend --date="Wed Jan 6 00:13:46 2021 +1030"
tags: git - software development - version control