To see all remote branch names, run git branch -r

To see all local and remote branches, run git branch -a

New branch

The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch. Once created you can then use git checkout new_branch to switch to that branch.

Revert the codebase to the last commit

git reset --hard HEAD

How to add my current project to an already existing GitHub repository

git init
git remote add origin https://github.com/cafecafe/lsm-link-preloader.git
git add .
git commit -m "Overwrite fresh project with managed installation boilerplate"

After this, run git branch -a, if it shows master, we would need to rename the branch

git branch -m master main

Push it to the server

git push -f origin main

or to use the shorter git push in the future, better set the upstream

git push -f --set-upstream origin main
git push

Check if local repo is up to date

git fetch --dry-run --verbose

or

git remote show origin

Cloning from a Specific Commit ID

We clone the whole repo, then git log it to see the hash for the needed commit and then we reset --hard to that commit

git clone https://github.com/cafecafe/lsm-link-preloader.git
git log //let's say we need commit 6bf5c5132e2cf6d7bf580627080537a420b0f9b
git reset --hard 6bf5c5132e2cf6d7bf580627080537a420b0f9b

Then you probably want to remove the .git folder and initialize a new project not to overwrite the source repo accidentally.

The reset command will delete all unnecessary tracked files. However, if you’re reverting to an existing project/folder, any new/untracked files added will still be left in the directory. In order to clean them, we’d need to run the git clean command.

git clean -n // Dry run
git clean -fd //-f for force, to actually delete, -d to include the directories

Now you should have a complete copy of what’s shown in the repo for the selected commit.


Sources

Git List Branches – How to Show All Remote and Local Branch Names

Git Checkout Commit - How to retrieve a specific previous commit

Removing Untracked Files with Git Clean

See also

Git - Basic Branching and Merging

Git: How to check if a local repo is up to date?

How to commit a change with both “message” and “description” from the command line?

git commit -m "Title" -m "Description ..........";

Comments

Well, a nice hack, but I prefer the answer below because it provides me a way to type a long description with newlines, with ease

But I feel if you’re doing commit after commit you don’t want to open the VIM every time. Can you add \n into the description doing it this way? E.g git commit -m "Title" -m "Description....\nNew line....\nAnother new line  Mar 13, 2018 at 22:00

Adding \n in the description to add a line break doesn’t work.

If you’re going to use \n you need to put it inside of $'' like this: $'test\ntext'

for those using github desktop : fwiw, I noticed that you need 2 new lines to make the description appear as such  Feb 17, 2022 at 14:11

u mean git commit -m "$'- searchScreen background added \n - SearchBar color matched'" ?

no, it should be used as git commit -m 'Title' -m $'Description line 1\nline 2\nline 3 ......'

I think this method is a better example to set for most users coming across this, to help enforce the 50 / 70 rule for git commits: Max 50 characters for message and max 70 for descriptions. This helps enforce users to be concise for others with their commits.


Use the git commit command without any flags. The configured editor will open (Vim in this case):

git commit command screenshot 1

To start typing press the INSERT key on your keyboard, then in insert mode create a better commit with description how do you want. For example:

git commit command screenshot 2

Once you have written all that you need, to returns to git, first you should exit insert mode, for that press ESC. Now close the Vim editor with save changes by typing on the keyboard :wq (w - write, q - quit):

git commit command screenshot 3

and press ENTER.

On GitHub this commit will looks like this:

preview of the commit on GitHub

As a commit editor you can use VS Code:

git config --global core.editor "code --wait"

From VS Code docs website: VS Code as Git editor

Gif demonstration:

git commit demonstration video

Git merge vs rebase

merge and rebase are two different ways to integrate changes from one branch into another in Git, and they each have distinct behaviors and use cases.

Merge

git merge <branch> integrates changes from the specified branch into the current branch by creating a new “merge commit”. This merge commit has two parent commits: one pointing to the head of the current branch and the other pointing to the head of the branch being merged.

Example:

git checkout deploy
git merge main

This merges changes from main into deploy and creates a merge commit on deploy.

Advantages:

  • Preserves History: The history of both branches is preserved, including all commit messages and branch structure.
  • Simple to Use: Ideal for situations where the history of how changes were integrated is important.

Disadvantages:

  • Complex History: Can lead to a more complex commit history with multiple merge commits, especially in long-lived branches.

Rebase

git rebase <branch> integrates changes from the specified branch into the current branch by “replaying” commits from the current branch onto the head of the specified branch. It essentially rewrites the commit history.

Example:

git checkout deploy
git rebase main

This moves the entire commit history of deploy to be based on the tip of main, replaying the commits of deploy on top of the latest commits from main.

Advantages:

  • Linear History: Creates a linear, cleaner commit history which can be easier to read and understand.
  • Bisecting: Easier to use git bisect for debugging, as there are no complex merges.

Disadvantages:

  • Rewriting History: Changes commit hashes and rewrites history, which can be problematic if the branch is shared with others.
  • Conflict Resolution: Requires resolving conflicts repeatedly if they occur, as each commit is replayed one by one.

When to Use Merge vs. Rebase

  • Use merge when:
    • You want to preserve the complete history of both branches.
    • You want to maintain the context of how features were integrated.
    • You are working in a shared repository where rewriting history would cause issues for other collaborators.
  • Use rebase when:
    • You want a cleaner, linear commit history.
    • You are working on a feature branch that is not yet shared with others.
    • You want to incorporate the latest changes from a base branch before merging back.

Practical Example

Let’s say you have two branches: main and feature.

Merge:

git checkout feature
git merge main

This will merge main into feature and create a merge commit on feature.

Rebase:

git checkout feature
git rebase main

This will rebase feature onto the latest main, replaying feature’s commits on top of main.

Summary

  • merge: Creates a new merge commit that preserves the history of both branches.
  • rebase: Replays commits from the current branch onto the target branch, creating a linear history.

Both methods are useful, and the choice depends on your workflow preferences and the specific needs of your project.

Автоматическое закрытие issue при коммите

В сообщении коммита можно сослаться на ID issue, и GitHub автоматически подвяжет этот коммит к issue.

Как правильно ссылаться на issue в коммите:

В сообщении коммита указывайте #<номер_issue>, например:

git commit -m "Исправляет ошибку с расчетом налога #42"

Но если вы хотите, чтобы issue автоматически закрылось после мержа этого коммита в main, используйте ключевые слова:

  • fixes #42
  • closes #42
  • resolves #42

Пример:

git commit -m "Fix incorrect tax calculation. Closes #42"

Как это работает?

  • Когда этот коммит попадает в основную ветку (обычно main), GitHub автоматически закроет issue #42.
  • В самом issue появится ссылка на коммит.

Если issue связано, но не должно автоматически закрываться, просто упомяните #42 без ключевых слов:

git commit -m "Добавляет логи для отладки проблемы #42"

Также можно привязать коммит к pull request, если вы работаете через PR. Тогда в описании PR тоже можно написать Closes #42, и issue закроется при мерже PR.

Update (deploy)

git add . `
; git commit -m "cicd test final" `
; git push `
; git checkout deploy `
; git merge main `
; git push origin deploy `
; git checkout main

Push to prod only (after “main branch push”)

git checkout deploy `
; git merge main `
; git push origin deploy `
; git checkout main

Если настроен husky с lint-staged на проверку перед коммитами и нужно обойти проверку

git commit --no-verify -m "Commit message"

Пуш при настроенном скрипте под тесты (см. в проекте 404-link-scanner) (флаг --no-ff)

git add .
git commit -m "Test husky final"
git push
npm run git:deploy

Как убедиться, что ветки main и deploy одинаковые по содержимому:

  1. Проверить историю коммитов без merge commit-ов:Если вывод пустой, значит различий по коду нет.

    git log main..deploy --no-merges
    
  2. Сравнить содержимое файлов напрямую:Если ничего не выводится, значит содержимое двух веток одинаково.

    git diff main..deploy
    
  3. Сравнить коммиты, исключив merge commit:Если результат пустой, значит нет уникальных коммитов, кроме merge commit-а.

    git rev-list main..deploy --no-merges