Git

Install, config

sudo apt install git
vi .bashrc
alias git='LANG=en_US git'

Config :
git config --system : system wide : /etc/gitconfig
git config --global : all projects : ~/.gitconfig
git config --local (or git config) : one particular project : .git/config
'#' permits to comment full or partial line in config files

git config --global user.name "My name"
git config --global user.email "email@example.org"
git config --local user.email "otheremail@example.org"
git config --global core.editor vim
git config --global merge.tool vimdiff
git config --global color.ui true
git config --global push.default simple
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.cia 'commit -am'
git config --global alias.tree log --graph --decorate --pretty=oneline --abbrev-commit --all
git config --global alias.slog 'log -30 --graph
    --abbrev-commit
    --decorate
    --date=iso
    --format=format:"%C(bold blue)%h%C(reset)
    - %C(bold green)(%ad)%C(reset) %C(white)%s%C(reset) %C(dim white)-
    %an%C(reset)%C(bold yellow)%d%C(reset)"
    --all'
git config --global alias.br branch
git config --global alias.bl show-branch --list
git config --global alias.alias "config --get-regexp ^alias\." git alias

git config --list
git config user.name (check the value of one variable)

Completion :
cd ~
wget https://github.com/git/git/blob/main/contrib/completion/git-completion.bash
vi .bashrc
source git-completion.bash

Help, tools

git help <verb> or git <verb> --help or man git-<verb>
irc.freenode.net
gitk : compare branches graphically
sudo apt-get install gitk 
gitk branch1 branch2

Basics

Files can be tracked or untracked.
Tracked files can be : unmodified, modified, or staged (staging area also called the index)

git status

git add : to stage (add to the index) new files
git add .           # stage all the files of current dir
git add dirname     # stage all the files of a directory
git add -A          # equivalent of hg addremove

# If a file is staged with git add, then modified again : it will be modified AND staged ;
# the next commit will record the version of the file when git add was called.
# To record its last state, run git add again on the file.

git commit -m "my message" - will record the staged changes.
git commit -a automatically stages every file that is already tracked before doing the commit ; permits to skip the git add part

git checkout tags/version-3.1

git rm <file> : removes file from tracked files and from the filesystem
If file is staged, need to do git rm -f <file>
git rm --cached <file> untracks a staged file without deleting it from the filesystem 
glob patterns available in rm - but git does its own filename expansion => escape : git rm log/\*.log

git mv README.txt README equivalent to mv README.txt README ; git rm README.txt ; git add README

Miscelaneous

AuthorDate is when the patch was generated
CommitDate is when it was actually applied to the repository.

Git protocol - listens port 9418
similar to the SSH protocol with no authentication.
create git-export-daemon-ok file

Vocabulary : <refspec>

Gerrit intro to git : 
https://docs.google.com/presentation/d/1IQCRPHEIX-qKo7QFxsD3V62yhyGA9_5YsYXFOiBpgkk/edit#slide=id.g4d6b1121f4_0_510

Staging area = the index = modifications added to git, ready to be included in next commit.

# issue a git command in an external path
# The -C option must be specified first, before all other arguments
git -C ../z-my-old-repo/ status

htaccess

<Files ".gitignore">  
  Require all denied
</Files>

# Forbid browsing of .git/
RedirectMatch 403 ^/path/to/.git/.*$

Initialize repository / clone

git init new_repo # same as : mkdir new_repo; cd new_repo; hg init
    
git clone git://repo.or.cz/fast-export.git

# shallow clone:
git clone --depth=1 <remote_repo_url>

# Initializing a Repository in an Existing Directory
cd path/to/my/project
git init

# Cloning an Existing Repository
git clone git://github.com/schacon/grit.git => creates directory grit/
git clone git://github.com/schacon/grit.git mygrit => clones in directory mygrit/

# Cloning a specific branch
git clone -b <branch> <remote_repo>

Clone only a subdirectory within a repository
sudo apt install subversion
svn export https://github.com/github_user/github_repo/trunk/local/path/to/dir

Change remote url:
git remote set-url <remote> git@github.com:OWNER/REPOSITORY.git
git remote set-url origin git@github.com:OWNER/REPOSITORY.git

http password

git config remote.origin.url https://login:password@github.com/login/example.git
# writes in .git/config
https://login:password@github.com/login/example.git

# Use these escapes for the following characters in password
 !   #   $   &   '   (   )   *   +   ,   /   :   ;   =   ?   @   [   ]
%21 %23 %24 %26 %27 %28 %29 %2A %2B %2C %2F %3A %3B %3D %3F %40 %5B %5D

More secure : tell git to remember your password for a while :

git config --global credential.helper cache     # default timeout = 15 min
git config --global credential.helper "cache --timeout=3600"

git clone --depth=1 <url>
Creates a shallow clone. These clones truncate the commit history to reduce the clone size. This creates some unexpected behavior issues, limiting which Git commands are possible. These clones also put undue stress on later fetches, so they are strongly discouraged for developer use. They are helpful for some build environments where the repository will be deleted after a single build.

git clone --filter=blob:none <url>
Creates a blobless clone. These clones download all reachable commits and trees while fetching blobs on-demand. These clones are best for developers and build environments that span multiple builds.

git clone --filter=tree:0 <url>
Creates a treeless clone. These clones download all reachable commits while fetching trees and blobs on-demand. These clones are best for build environments where the repository will be deleted after a single build, but you still need access to commit history.

.gitignore

- Blank lines or lines starting with # are ignored.
- Standard glob patterns work.
- You can end patterns with a forward slash (/) to specify a directory.
- You can negate a pattern by starting it with an exclamation point (!).

# to ignore files locally without modifying .gitignore:
.git/info/exclude

Comment a full line (not possible to comment part of a line):
# a comment

no .a files:
*.a

But do track lib.a, even though you’re ignoring .a files above:
!lib.a

# Don't version a directory but version some files in this dir
1-manage/sctl-update/*
!1-manage/sctl-update/sctl-mdb2csv


Only ignore the root TODO file, not subdir/TODO:
/TODO

Ignore all files in the build/ directory:
build/

Ignore doc/notes.txt, but not doc/server/arch.txt:
doc/*.txt

# see which rule ignores a file:
git check-ignore -v src/commands/output/templates/gallery.html

.gitattributes
---------------------------------------------------------------------------
cf https://rehansaeed.com/gitattributes-best-practices/

git show / git log / git diff

https://git-scm.com/docs/git-log --> commit formatting --> placeholders

git log /path/to/file                   # shows commits concerning a particular file
git log -L:function_name:/path/to/file  # shows commits concerning a particular function in a file
git log -2                              # shows 2 last revisions
git log --stat                          # shows nb of added / removed lines for each tracked file
git log --oneline                       # = git log --pretty=oneline  (one line per commit)
git log --pretty=short
git log --pretty=full
git log --pretty=format:"%h %cd %s"
git log --graph
git log --since=2.weeks
git log --before="2014-11-10"

# Show commits done on a specific branch
# commits done on release-3.0 but not on prod
git log prod..release-3.0 --oneline


# Show commits done on a specific branch
git log master..branchA
git log prod..release-3.0 --oneline
# List commits that changed a file
git log --follow -- /path/to/file

git log --after="2024-09-01 00:00" --before="2024-09-10 23:59"

# show commits on branch2 that are not on branch1
git cherry -v branch1 branch2
# ex: to know what is not already pushed :
git cherry -v origin/37-feat-bank-endpoint-to-generate-callback-url 37-feat-bank-endpoint-to-generate-callback-url

---------------------------------------------------------------------------
# List files modified by a commit
git show --name-only <commit-sha1>

# Show modifications done in a commit
git show <commit-sha1>
# or
git diff <commit-sha1>~ <commit-sha1>

# List all files modified in a commit:
git diff-tree --no-commit-id --name-only -r <commit-sha1>

# Find the modifications on a given file (-n 1 = only 1 commit shown)
git log --follow -p -- /path/to/file
# one line
git log --follow --oneline -- /path/to/file
# one line with date
git log --follow --pretty=format:"%h %ad - %s" --date=short -- /path/to/file-or-dir
# one line with date and author name
git log --follow --pretty=format:"%h %ad %an - %s" --date=short -- /path/to/file-or-dir

git diff
---------------------------------------------------------------------------
# Show all differences between 2 commits
git diff <commit1-sha1>..<commit2-sha1>

See old versions of files

# See the whole repo
git checkout c0e2ba2

# Only cat a file
git show c0e2ba2:path/to/file
git show HEAD~4:src/main.c
git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt

Reset, revert, amend

# Oh shit, I committed and immediately realized I need to make changes!
git add .       # or add individual files
# overrides last commit, and uses current state of staging area to perform the new commit
git commit --amend
git commit --amend --no-edit

# Change last commit message
git commit --amend -m "initial commit"

Then change commit in editor
if already pushed : git push origin main --force

# Unstage, remove from the index, without doing anything else:
git reset
git reset <file>

# Throw away all uncommitted changes in the working directory, restore to last commit
# WRANING, NOT RECOVERABLE - cannot be done on a particular file
git reset --hard

# Throw away uncommitted changes on a file
git checkout -- <file>

Change previous commit message

git rebase -i HEAD~X
# X is the number of commits to go back
# Move to the line of your commit, change pick into edit,
# then change your commit message:
git commit --amend
# Finish the rebase with:
git rebase --continue

Rebase opened your history and let you pick what to change. With edit you tell you want to change the message.
Git moves you to a new branch to let you --amend the message.
git rebase --continue puts you back in your previous branch with the message changed.

# Unstaging a staged file
git reset HEAD <file>

Reverting a file to last commit - WARNING : unrecoverable
git checkout -- <file>

# Modify 3 last commits
git rebase -i HEAD~3
# this edits .git/refs/git-rebase-todo
# change the commit messages and replace 'pick' by 'reword' or other command, save and quit 
git rebase --continue
git push --force-with-lease

See also http://git-scm.com/book/fr/v2/Git-Tools-Rewriting-History

Remote repositories

git clone git://github.com/schacon/ticgit.git
=> creates a local copy in directory ticgit
cd ticgit
git remote -v       # hg paths
    origin  git://github.com/schacon/ticgit.git (fetch)
    origin  git://github.com/schacon/ticgit.git (push)
'origin' is the default name given to a path when cloning a repo (edit .git/config to change)

Bare repos

# Clonig a local repo on a remote machine
# In order to initially set up any Git server, you have to export an existing repository into a new bare
# repository — a repository that doesn’t contain a working directory.
# By convention, bare repository directories end in .git
git init --bare newrepo.git
git clone --bare my_project my_project.git
scp -r my_project.git user@git.example.com:/opt/git
# At this point, other users who have SSH access to the same server which has read-access to the /opt/git directory can clone your repository by running
git clone user@git.example.com:/opt/git/my_project.git
# Convert the bare repo to working tree
ssh user@git.example.com
cd /opt/git
mkdir my_project
mv my_project.git my_project/.git
cd my_project
git config --local --bool core.bare false # or vi .git/config
git checkout

git remote -v               # list remote paths and branches
git remote add <name> git://github.com/schacon/ticgit.git       # add a remote path
git remote rename <name1> <name2>       # rename a remote path
git remote rm <name>        # remove a remote path

git remote show origin      # hg incoming origin

git fetch origin            # hg pull ; doesn’t automatically merge it with any of your work or modify what you’re
                                        currently working on. You have to merge it manually into your work when you’re ready
git pull origin             # automatically fetch and then merge a remote branch into your current branch

git push

# See http://git-scm.com/docs/git-push
git push origin main        # push to 'origin' remote, 'main' branch
git push origin +main       # push only to 'main' branch
'git push' [--all | --mirror | --tags] [--follow-tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
	   [--repo=<repository>] [-f | --force] [--prune] [-v | --verbose]
	   [-u | --set-upstream] [--signed]
	   [--force-with-lease[=<refname>[:<expect>]]]
	   [--no-verify] [<repository> [<refspec>...]]

# When the command line does not specify where to push with the <repository> argument, branch.*.remote configuration for the current branch is consulted to determine where to push.
# If the configuration is missing, it defaults to origin.
config :
git config --global push.default simple : push only the current branch to the one that git pull would pull from
git config --global push.default matching : push all your local branches to the ones with the same name on the remote 

# Pushing on a non-bare repository = "bad" ?
# "bad" but convenient : on the remote repository :
# but possible : on the non-bare repo where you want to push, do on the remote repo :
git config --local receive.denyCurrentBranch ignore
then git checkout -f or git checkout and git reset --hard
See http://stackoverflow.com/questions/12265729/what-are-the-consequences-of-using-receive-denycurrentbranch-in-git

For "good" practice, see git/deploy-2repos-2hooks.html (intermediate bare repo + 2 hooks).
Or write a post-recieve hook to automate : see http://stackoverflow.com/questions/7152607 and http://toroid.org/ams/git-website-howto

Branching

Default branch name: main ; HEAD = pointer to current branch
See http://www.micahcarrick.com/show-git-branch-in-shell-prompt.html for bash integration.

git switch = git checkout (abbreviated git co)

# switch to the previous branch
git co -            # = shortcut of git checkout @{-1}


git branch testing # creates a new branch (doesn't switch to that branch)
git checkout testing # switches to branch testing (the HEAD pointer goes to testing).
git checkout -b testing # create a branch and switch to it

Go back to main and merge testing branch :
git checkout main
git merge testing

git branch -a           # list all branches, local and remote
git branch -r           # list remote branches

Associate current branch to a remote branch
---------------------------------------------------------------------------
# You have created a new local branch ; from this branch, create a remote branch and push
git push --set-upstream github 13-titre-chantier
# or specify remote branch name
git branch --set-upstream-to=origin/branch_name

# list all branches and their last commit
git branch -v

# list remote branches
git ls-remote

# push local branch to a specific remote branch
git push origin 'feature/mobile-commercial-offer'

# list branches merged or not merged in the current branch
git branch --merged and git branch --no-merged

# echo the curent branch
git rev-parse --abbrev-ref HEAD or git symbolic-ref HEAD

# track a new branch :
git checkout --track origin/another-branch

# checkout local branch from remote branch
git checkout -b 'feature/mobile-commercial-offer' 'origin/feature/mobile-commercial-offer'

Rename a branch
---------------------------------------------------------------------------
git branch -m old_branch new_branch         # Rename branch locally
git branch -m master main
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

# integrate changes in main
# see https://www.atlassian.com/blog/git/simple-git-workflow-simple
git fetch origin
git rebase origin/main

Delete a branch
---------------------------------------------------------------------------
# local branches
git branch -d testing # delete the testing branch
git branch -D testing # delete the testing branch even if not merged with current branch


# delete remote branch
git push origin --delete the_remote_branch

# Remove local branches that were deleted on remote
git remote prune origin

Clone all remote branches
---------------------------------------------------------------------------
https://www.geeksforgeeks.org/git/how-to-clone-all-remote-branches-in-git/

git clone https://github.com/username/repository
cd repository
git fetch --all
for branch in $(git branch -r | grep -v '\->'); do
    git branch --track ${branch#origin/} $branch
done
git pull --all

Squashing

# Convert 30 commits of branch toto in a single commit 
git reset --soft $(git merge-base main toto)
git commit -m "My unique commit message"
# git merge-base finds the common ancestor to main and toto
# git reset --soft <commit-id> brings back the branch toto at this common commit, keeping all the changes in the staging area.

# start a branch from main branch
git co main && git pull     # to be sure that main is up to date
git co my-branch
# squash commits of my-branch since it was created from main
git reset --soft $(git merge-base main HEAD)

Diff

# show the modifications that will be commited (staged)
git diff --cached
git diff --cached <myFile>
# or synonym
git diff --staged


# between 2 branches

# list the different files
git diff --name-status main..branch1

# detailed diff
git diff main..branch
git diff main..branch | grep "^diff"

TO CHECK
git log main..branch
git shortlog main..branch

cherry-pick

git switch main         # first go to the branch where you want to apply the commit
git cherry-pick <commit-hash>

Stash

git stash list

git stash                   # stash uncommited work
# change branch, do things, commit.
# come back to the branch

git stash apply             # retrieve stashed data

# stash
git stash -u                # --include-untracked
git stash --keep-index      # include staged content and leave it in the index.
git stash -a                # --all (include ignored files)
git stash --patch           # interactive - ask which files to stash
git stash branch new_branch # create a branch, checks out the commit you were on when you stashed,
                            # reapplies your work there, and then drops the stash if it applies successfully
# unstash
git stash apply
git stash apply stash@{2}   # if several stashes - see git stash list
git stash apply --index     # reapply also the staged changes

# Delete stash
git stash drop              # delete the top stash
git stash drop stash@{0}    # delete a specific stash
git stash pop               # apply the stash and then immediately drop it

# See what's inside a stash
git stash show stash@{0}

# Show the differences from a stashed file
git diff stash@{0}^1 stash@{0} -- <filename>

TODO  https://stackoverflow.com/questions/1105253/how-would-i-extract-a-single-file-or-changes-to-a-file-from-a-git-stash

# If you started to make changes to the working tree but the wrong branch is checked-out:
# just try to checkout the correct branch, if there are no conflicts this will just work
# if there are conflicts the checkout fails, in this case you can do:
git stash
git checkout <correct-branch>
git stash pop
<resolve conflicts>
git stash drop

Tags

# Annotated tag:
git tag -a v1.4 -m "my version 1.4"
# -a for annotated ; v1.4 is the tag name
git show v1.4

git tag : list all tags
git tag -l <pattern>
# echoes the last tag
git describe --always --tag
# list tags with their dates
git log --tags --simplify-by-decoration --pretty="format:%ci %d"
# delete a tag
git tag -d <tagname>

# By default, the git push command doesn’t transfer tags to remote servers
git push origin v1.5           : push one tag
git push origin --tags   : push all tags

Sub-modules

git submodule add https://github.com/chaconinc/DbConnector
# => see .gitmodules
### example of .gitmodules ###
[submodule "vendor/tig12/tigdraw"]
	path = vendor/tig12/tigdraw
	url = https://github.com/tig12/tigdraw
### ###

git diff --submodule
git diff --cached --submodule
git commit -am 'added DbConnector module'

git clone https://github.com/chaconinc/MainProject
git submodule init
# or in one command :
git clone --recurse-submodules https://github.com/chaconinc/MainProject

# pull updates from submodule :
cd DbConnector
git fetch
git merge origin/main

Specifying revisions

man git-rev-parse

<sha1>, e.g. dae86e1950b1277e545cee180551750029cfe735, dae86e
<describeOutput>, e.g. v1.7.4.2-679-g3bee7fb
<refname>, e.g. master, heads/master, refs/heads/master

.git/<refname> if it exists;
.git/<refs/tags/<refname> if it exists;
.git/<refs/heads/<refname> if it exists;
.git/<refs/remotes/<refname> if it exists;
.git/<refs/remotes/<refname>/HEAD 

HEAD                    names the commit on which you based the changes in the working tree.
FETCH_HEAD              records the branch which you fetched from a remote repository with your last git fetch invocation.
ORIG_HEAD               is created by commands that move your HEAD in a drastic way (git am, git merge, git rebase, git reset),
                        to record the position of the HEAD before their operation, so that you can easily change the tip
                        of the branch back to the state before you ran them.
MERGE_HEAD              records the commit(s) which you are merging into your branch when you run git merge.
REBASE_HEAD             during a rebase, records the commit at which the operation is currently stopped, either because of conflicts or an edit command in an interactive rebase.
REVERT_HEAD             records the commit which you are reverting when you run git revert.
CHERRY_PICK_HEAD        records the commit which you are cherry-picking when you run git cherry-pick.
BISECT_HEAD             records the current commit to be tested when you run git bisect --no-checkout.
AUTO_MERGE              records a tree object corresponding to the state the ort merge strategy wrote to the working tree when a merge operation resulted in conflicts.

@                       shortcut for HEAD
[<refname>]@{<date>}    e.g. master@{yesterday}, HEAD@{5 minutes ago} HEAD@{1979-02-26 18:30:00}
<refname>@{<n>}         n-th prior value of that ref. e.g. master@{1}
@{<n>}                  reflog entry of the current branch.

<rev>                   Include commits that are reachable from <rev> (i.e. <rev> and its ancestors).
^<rev>                  Exclude commits that are reachable from <rev> (i.e. <rev> and its ancestors).
<rev1>..<rev2>          Include commits that are reachable from <rev2> but exclude those that are reachable from <rev1>.
                        When either <rev1> or <rev2> is omitted, it defaults to HEAD.
<rev1>...<rev2>         Include commits that are reachable from either <rev1> or <rev2> but exclude those that are reachable from both.
                        When either <rev1> or <rev2> is omitted, it defaults to HEAD.
<rev>^@, e.g. HEAD^@    A suffix ^ followed by an at sign is the same as listing all parents of <rev>
                        (meaning, include anything reachable from its parents, but not the commit itself).
<rev>^!, e.g. HEAD^!    A suffix ^ followed by an exclamation mark is the same as giving commit <rev> and all its parents prefixed with ^ to exclude them (and their ancestors).
<rev>^-<n>              e.g. HEAD^-, HEAD^-2    Equivalent to <rev>^<n>..<rev>, with <n> = 1 if not given.

tag1..tag2              every commit between tig1 and tag2

G   H   I   J
 \ /     \ /
  D   E   F
   \  |  / \
    \ | /   |
     \|/    |
      B     C
       \   /
        \ /
         A

Args   Expanded arguments    Selected commits
D                            G H D
D F                          G H I J D F
^G D                         H D
^D B                         E I J F B
^D B C                       E I J F B C
C                            I J F C
B..C   = ^B C                C
B...C  = B ^F C              G H D E B C
B^-    = B^..B
       = ^B^1 B              E I J F B
C^@    = C^1
       = F                   I J F
B^@    = B^1 B^2 B^3
       = D E F               D G H E F I J
C^!    = C ^C^@
       = C ^C^1
       = C ^F                C
B^!    = B ^B^@
       = B ^B^1 ^B^2 ^B^3
       = B ^D ^E ^F          B
F^! D  = F ^I ^J D           G H D F

Conventional commits

See conventionalcommits.org
feat(api)!: send an email to the customer when a product is shipped
<type>[optional scope]: <description>
! to draw attention to breaking change
Recommanded verbs:
fix:
feat:
build:
chore:
ci:
docs:
style:
refactor:
perf:
test:

Convert hg to git

hggit extension :
sudo apt-get install mercurial-git
vi ~/.hgrc
    hgext.bookmarks =
    git =
cd /path/to/hg-repo
hg bookmarks hg
hg push /path/to/git-repo
# optional, if hg repo not needed anymore
cd  /path/to/git-repo
git checkout -b main
git branch -d hg

hg-fast-export.sh : http://hivelogic.com/articles/converting-from-mercurial-to-git
git init newrepo
# git init --bare newrepo
cd newrepo
/path/to/hg-fast-export.sh -r /path/to/hg_repo
git checkout HEAD