Git tips, tricks and some explanations

Git tips, tricks and some explanations

Полезные встроенные графические инструменты (для винды):
gitk - Графический просмотрщик для коммитов
git gui - Чё-то наподобие среды для GIT (ну GUI есть гуй :-)

Создаём псевдонимы:


$ git config --global alias.ch checkout
$ git config --global alias.br branch
$ git config --global alias.co commit
$ git config --global alias.st status
$ git config --global alias.visual '!gitk' 

Пример использования: $ git st

Чтобы создать ветку и сразу же перейти на неё, вы можете выполнить команду:
$ git checkout -b имя_ветки
Допустим, вы разобрались с проблемой hotfix и готовы объединить эту ветку и свой master.
Чтобы сделать это, мы сольём ветку имя_ветки в ветку master.
Всё, что вам нужно сделать, — перейти на ту ветку, в которую вы хотите слить свои изменения,
и выполнить команду git merge:
  $ git checkout master (переход в master)

  $ git merge имя_ветки (сливание[объединение])
 
Вы можете удалить ветку с помощью опции -d при использовании git branch:

$ git branch -d имя_ветки
$ git push origin --delete имя_ветки  (removing remote branch)
https://www.freecodecamp.org
/news/how-to-delete-a-git-branch-both-locally-and-remotely/ - for details

$ git add . добавить все файлы, кроме удалённых
$ git add -u добавить удаленные и измененные (без новых)
$ git add -A добавить все
$ git status -uno
$ git status -u
показать статус без неотслеживаемых файлов
$ git commit -a слежение за файлами
$ git commit -v добавление в описание лога изменений в виде diff-a

как убрать файл из отслеживания: 
$ git rm --cached readme.txt

убрать из отслеживания все файлы которые были изменены в текущем каталоге
(
-r --> рекурсивно)
$ git rm --cached -r .  
убрать из отслеживания все фалы в каталоге log
git rm --cached log/\*.log
отмена последнего коммита (файлы останутся в стейдже(индексе)): 
$ git reset HEAD~1 --soft
замещение последнего коммита без правки сообщения:
git commit --amend --no-edit

замещение последнего коммита c правкой сообщения:
$ git commit --amend -m " <new-message>"

если изменения уже запушены (не рекомендуется в распределённых командах, буде больно))

$ git commit --amend -m "<new-message>" 
$ git push --force

how to revert commit:
git revert <merge_commit_hash>

how to revert merge commit:
git revert -m 1 <merge_commit_hash>


How to change author of the git commit (great article on dev.to) and a few answers from Stack Overflow

поиск строки (например имени функции) по всему репозиторию (в результате вы 
получите коммиты в которых упоминалась данная строка:
git log -S someMethod --oneline
чтобы получить историю коммитов, в которых изменялся конкретный файл, можно 
использовать следующую команду:
git log --oneline -- filename

Beautiful log (1 row per commit for all branches)

git log --graph --oneline --all --decorate

    git log --graph main only branch main

How to git log in reverse order? 
    git log --reverse

How to git log in reverse order with a numbering? 
    git log --reverse --oneline --all | cat -n

how to show log in next format: hash - author - relativity time  - commit message
    git log --pretty=format:"%h - %an , %ar : %s"

or the same but with colors and creating alias, so after performing this call it by: git lg
    git config --global alias.lg "log --graph --pretty=format:'%C(yellow)%h%Creset -%C(auto)%d%Creset %s %C(green)(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

how to make your own git log colorized log 
https://share.google/aimode/Fp6loCKNfibvq4T3G

как создать ветку без истории (без парента) сиротку ))) в три шага/
how to create branch without parent(history) in three steps
$ git checkout --orphan <name_you_choose_for_orphan_branch>
$ git commit
$ git push <remote-name> <branch-name>


how to apply commits from one branch to another without merging just
cherry pick them (and adds referrer to the commit message because new commits will have a
a new sha1):


git cherry-pick "-x" a1b2c3d
"-x": Appends confirmation to the log. It adds a standard line saying "(cherry picked from
commit...)" to the new commit message so developers can track its origin.

a1b2c3d: Target commit hash you want to copy.



This command displays a clean, compact history of unique commits made in your current
branch since it split from main:

git log --oneline --no-merges main..

--oneline: Condenses output into single lines. It shows only the short commit hash and
the commit subject line.
--no-merges: Hides merge commits. It filters out the clutter of automated
 
 "Merge branch..." messages to show only direct code changes.
main..: Defines range of the log. The double dots .. tell Git to show commits that are in
 your current branch but not in the main branch. Leaving the right side blank defaults to 
your current checked-out branch.


git add - Difference between "git add -A" and "git add ." - Stack Overflow
Если вы хотите использовать графические инструменты для разрешения конфликтов, можете выполнить команду git mergetool, которая запустит соответствующий графический инструмент и покажет конфликтные ситуации

прячем изменения от коммита: git stash
восстанавливаем спрятанное git stash apply

BigMax notes: Какая разница между .gitkeep и .gitignore

if we want to store empty folder📂 we need to put .gitkeep file inside this 📂. This file is a special placeholder

вот ещё полезное про .gitignore  Ignore files in your Git repo - Azure Repos | Microsoft Docs (временное отключение отслеживания для конкретных файлов)




how to find sha1 for the branch:
git rev-parse HEAD   or  git show -s --format="%H" HEAD
git rev-parse <branch_name>   or   git show -s --format="%H" <branch_name>
git rev-parse <remote_name>/<branch_name>
git rev-parse origin/main





How to push all branches altogether git push --all

Скорая помощь по GIT - http://firstaidgit.io/
и ещё чуть-чуть:
http://eax.me/git-commands/
Git: наглядная справка

git add -p and git add -i are two different Git commands used for working with the index (staging area) and selectively adding changes to your commit. Here's the difference between them:
git add -p focuses on selectively adding changes within specific files, while
git add -i provides a broader range of operations for index management.

changing multiple commit messages in a whole git repo: 
Use the git rebase -i HEAD~n command to display a list of the last n commits in your default text editor. Replace pick with reword before each commit message you want to change.


Hiding local changes from git (very useful, link) 


Hint:
The Git command git config core.fsmonitor true enables Git's built-in filesystem monitor daemon to speed up operations like git status by avoiding full disk scans. In Windows, it works by utilizing platform-specific filesystem notification events.
core.fsmonitor is a performance optimization feature in Git (added in Git 2.37.0 as a built-in option).

Comments

Popular posts from this blog

30 маловідомих, але корисних команд Linux (repost)

15 поширених команд Linux (repost з ITEDU.center)