Guest mode. You can read posts without signing up. Comments, ratings, job contacts and your own posts open after you sign up and accept the rules. What is Kommit →

Редакция КоммитРедакция портала
commit 6eabcda · 15 days ago

Git for the command, part 1: setup, good commits, .gitignore, and how to undo any error

🌐 Machine-translated from Russian. Show original

In this part:

How Git works in 2 minutes#

Git stores the project history as a chain of snapshots (commits). Each commit has an author, date, message, and a link to the previous one.

ZoneWhat's thereTeam to hit
Working folderfiles you edit—
Stagingwhat will be included in the next commitgit add
Local repositorycommit history on your diskgit commit
Remote repositoryshared server: GitLab, GitHub, Giteagit push

The main thing to remember: what is committed is almost impossible to lose. Even after a "failed" reset, a commit can be found in git reflog (more on this below). Only what you never committed is lost.

Step 1. Installation and initial setup#

  • Windows — git-scm.com/install (installed together with Git Bash) or winget install --id Git.Git -e.
  • macOS — brew install git or Xcode Command Line Tools.
  • Ubuntu 24.04 — sudo apt install -y git. In the Ubuntu repository, the version is older but sufficient for operation.

Check:

git --version

Once on the computer:

git config --global user.name "Айгерим Сапарова"
git config --global user.email "a.saparova@company.kz"   # рабочая почта, та же, что в GitLab
git config --global init.defaultBranch main
git config --global pull.rebase true          # git pull без лишних merge-коммитов
git config --global fetch.prune true          # удалять ссылки на удаленные ветки
git config --global rebase.autoStash true
git config --global core.editor "code --wait" # или nano / vim

Line breaks are a common pain of mixed Windows + Linux commands:

# Windows
git config --global core.autocrlf true
# Linux и macOS
git config --global core.autocrlf input

More reliable is .gitattributes one file in the root of the repository, so the settings are the same for everyone:

* text=auto eol=lf
*.bat text eol=crlf
*.ps1 text eol=crlf
*.png binary
*.xlsx binary

SSH key for GitLab and GitHub#

ssh-keygen -t ed25519 -C "a.saparova@company.kz"
cat ~/.ssh/id_ed25519.pub     # этот публичный ключ вставляем в профиль GitLab → SSH Keys
ssh -T git@gitlab.company.kz  # проверка

🔐 Do not send the private key (id_ed25519 without .pub) to anyone and protect it with a password when created.

Step 2. Good commits#

Kommit is one logical change. "Fixed discount calculation" — good. "Friday, everything" — bad: such a commit cannot be rolled back or revoked.

Duty cycle:

git status                 # что изменилось
git diff                   # что именно
git add src/discount.ts    # добавить конкретный файл
git add -p                 # или выбрать куски изменений интерактивно
git commit -m "fix(discount): не применять скидку к товарам из акции"

Commit message#

Popular standard — Conventional Commits:

PrefixWhen
feat:a new opportunity
fix:fixing the
docs:documentation
refactor:modification without changing
test:tests
chore:dependencies, build, settings,

Rules that work in any team:

  • The first line — up to 72 characters, which is done, in imperative or past tense — the main thing, is the same for everyone.
  • An empty line, then why — unless it's obvious from the code.
  • Task number in the message: fix: округление НДС (#142) — GitLab will automatically associate the commit with the task.

Step 3. .gitignore — what should not enter the repository#

The repository does not include: passwords and keys, .env, collected files, dependencies (node_modules, vendor), logs, IDE settings, databases.

Example .gitignore:

# зависимости и сборка
node_modules/
dist/
build/
*.log

# секреты
.env
.env.*
!.env.example
*.pem
*.key

# IDE и ОС
.idea/
.vscode/*
!.vscode/extensions.json
.DS_Store
Thumbs.db

Ready-made templates for any language — github.com/github/gitignore.

If the file has already entered the repository, .gitignore won't help — first remove it from the index:

git rm --cached .env
git commit -m "chore: убрать .env из репозитория"

⚠️ If a password or token gets into the repository — consider it compromised: change it . Deleting from history (git filter-repo) is the second step, not the first: copies of the repository may have already been disconnected.

Step 4. How to undo the error#

Cheat sheet "what happened → what to do":

SituationTeam
Corrupted file, not committedgit restore файл
Added extra to the indexgit restore --staged файл
Typo in last commit (not yet pushed)git commit --amend
Forgot file in last commitgit add файл && git commit --amend --no-edit
Cancel the last commit leaving the changesgit reset --soft HEAD~1
Discard the last commit completely (not launched)git reset --hard HEAD~1
Cancel a commit that is already in the shared branchgit revert <sha>
You need to switch urgently, but the work isn't finishedgit stash, then git stash pop
"I Broke Everything with a Reset"git reflog → git reset --hard <sha>

The main rule: do not rewrite the history of shared branches. For what is already started in main— only git revert: it creates a new commit that overrides the old one and breaks nothing for anyone.

reflog — time machine#

git reflog
# a1b2c3d HEAD@{0}: reset: moving to HEAD~3
# 9f8e7d6 HEAD@{1}: commit: feat: отчет по продажам   ← вот он
git reset --hard 9f8e7d6

Reflog is local and stores records for about 90 days by default.

Useful for every day#

git log --oneline --graph --all -20   # история веток картинкой
git log -p -- src/discount.ts         # все изменения конкретного файла
git blame src/discount.ts             # кто и когда менял каждую строку
git switch -c feature/report          # новая ветка
git switch main                       # переключиться
git bisect start                      # поиск коммита, который сломал код

Part 1 checklist#

  • The user.name and working user.email are indicated
  • Default branch — main, pull.rebase true
  • The repository contains .gitignore and .gitattributes
  • SSH key with password added to GitLab
  • Commits are small, messages are clear, with a task number
  • For common branches — only revert, not reset

Next — how to work with branches as a whole team: Git for the team, part 2: branching, merge, or rebase strategies, and how to resolve conflicts.

Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up

Comments · 0

No comments yet.Sign in to comment, rate and see all comments.