Git Selected#

Git SSH Set Up Guide#

This is a tutorial for setting up SSH keys with GitHub.

SSH Key Generation#

First check for existing keys:

$ lc -al ~/.ssh

Use ssh-keygen to generate new the SSH key with the email registering GitHub:

$ ssh-keygen -t ed25519 -C "<xxx>@email.com"
Generating public/private ed25519 key pair.
Enter file in which to save the key:
...
Enter passphrase (empty for no passphrase):
...

Important

Your passphrase should be complicated, and you must store it safely.

Note

A passphrase is a memorized secret consisting of a sequence of words or other text that a claimant uses to authenticate their identity. Here, it refers to a secret used to protect an encryption key. Commonly, an actual encryption key is derived from the passphrase and used to encrypt the protected resource.

Fire up the SSH agent and add the SSH key to ~/.ssh on your local machine:

$ eval `ssh-agent -s`
$ ssh-add ~/.ssh/id_ed25519
Enter passphrase for /Users/<user>/.ssh/id_ed25519:
...
Identity added: /Users/<user>/.ssh/id_ed25519

Login Escape#

If it is asking you for a username and password when manipulating with GitHub, your origin remote is pointing at the HTTPS url rather than the SSH url. You need to change it to SSH url:

$ git remote set-url origin git@github.com:<username>/<repo>.git

Git Branch Recovery#

Remote branch recovery#

If we have pushed the branch to a remote server, we could use git reflog to recover easily and reliably. Suppose we have following commit history to the branch named main with corresponding activity id:

$ git reflog
1ed7510 HEAD@{1}: commit: message 1
70b3696 HEAD@{2}: commit: message 2
98f2fc2 HEAD@{3}: commit: message 3

we could find the target commit and push back to origin to recover:

$ checkout -b main 1ed7510
$ add -A
$ push origin main

Local branch recovery#

If we have not pushed the branch, we could create a list of all dangling or unreachable commits, where the commits are copied into .git/lost-found/commit/, and non-commit objects are copied into .git/lost-found/other/,

$ git fsck --full --no-reflogs --unreachable --lost-found
unreachable tree 4a407b1b09e0d8a16be70aa1547332432a698e18
unreachable tree 5040d8cf08c78119e66b9a3f8c4b61a240229259
unreachable tree 60c0ce61b040f5e604850f747f525e88043dae12

print a list of commit messages for all commits in the lost and found,

$ ls -1 .git/lost-found/commit/ | xargs -n 1 git log -n 1 --pretty=oneline
9ae38fc6b0548cab08ccee1178db0ba0edeafdb2 foo # target commit
6ed99e63db69ca04f0cc78081a1fd471289551b2 On master: search and reset
973d9be3e2cefcd0c5801ad9cd1b2e18774b4bee Rename decorator proxy
9efa6b28b3b0a89c312484f28cf589385d613dfd On master: mysql db config

and create a new branch with the missing commit as the branch head:

$ git checkout -b <branch-name> 9ae38fc
Switched to a new branch <branch-name>