Интерактивное перебазирование и изменение коммитов
Научитесь переписывать историю с помощью `git rebase -i` для создания более чистых коммитов и использовать `git commit --amend` для изменения последнего коммита
«Интерактивное перебазирование и изменение коммитов» — бесплатный урок Git Advanced: Monorepo, Submodules & Workflows на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Git Advanced: Monorepo, Submodules & Workflows, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Git Advanced: Monorepo, Submodules & Workflows содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Clean Up Your Git History
Git history gets messy — a forgotten file, a typo'd message, ten tiny commits that should be one. Git lets you rewrite history to clean it up.
Amending Your Last Commit
git commit --amend fixes your most recent commit: change the message, add forgotten files, or tweak content. It replaces the last commit with a tidier one.
Amending a Commit Example
Forgot a file right after committing? Stage it, then git commit --amend folds it into the last commit. Here's the flow.
# 1. Make some changes and commit
echo "Initial content" > file1.txt
git add file1.txt
git commit -m "Add file1"
# 2. Realize you forgot file2.txt
echo "More content" > file2.txt
git add file2.txt
# 3. Amend the last commit to include file2.txt
git commit --amend --no-editIntroducing Interactive Rebase
Need to fix commits further back, not just the last one? Interactive rebase (git rebase -i) is a full editor for a series of commits.
Getting Started with Rebase -i
Start an interactive rebase by naming a commit before your target range. To edit the last three commits, use HEAD~3.
git rebase -i HEAD~3Rebase Commands: Pick, Reword, Squash
The rebase editor lists commits with commands you can swap: pick keeps it, reword edits the message, squash/fixup merge it up, edit pauses to amend.
Rewording a Commit Message
To change an older commit's message, switch its line from pick to reword in the editor. Git then prompts you for the new message.
# Original rebase editor content:
# pick 8a9b3c4 Add initial feature
# pick d1e2f34 Fix typo in docs
# Change 'pick' to 'reword' for the first commit:
# reword 8a9b3c4 Add initial feature
# pick d1e2f34 Fix typo in docsSquashing Commits Together
Got several small commits that belong together? squash merges them into one meaningful commit — change the lines below pick to squash.
# Original commits:
# pick abc1234 Add user registration form
# pick def5678 Add validation for email field
# pick ghi9012 Fix styling on form
# To squash the last two into the first:
# pick abc1234 Add user registration form
# squash def5678 Add validation for email field
# squash ghi9012 Fix styling on formEditing an Older Commit
The edit command pauses the rebase at a specific commit. Make changes, git add, git commit --amend, then git rebase --continue.
When to Be Careful with Rewriting
Rewriting changes commit IDs — safe for local-only commits. Never rewrite history that's already pushed and shared; it wrecks your collaborators' work.
Quick Check: History Rewriting
You've made a commit with the message "Fix bug". You then realize you forgot to include one small file in that commit. What is the most appropriate Git command to fix this, assuming you haven't pushed the commit yet?
Recap: Cleaner Commits
Recap: git commit --amend fixes the last commit, while git rebase -i rewrites a series — reword, squash, fixup, or edit. Just be careful on shared branches.
Часто задаваемые вопросы
Урок «Интерактивное перебазирование и изменение коммитов» бесплатный?
Да — полный текст урока «Интерактивное перебазирование и изменение коммитов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Git Advanced: Monorepo, Submodules & Workflows, подпишись на CoddyKit PRO. Курс Git Advanced: Monorepo, Submodules & Workflows содержит 4 уроков всего.
Чему я научусь в уроке «Интерактивное перебазирование и изменение коммитов»?
Научитесь переписывать историю с помощью `git rebase -i` для создания более чистых коммитов и использовать `git commit --amend` для изменения последнего коммита Ты практикуешь Git Advanced: Monorepo, Submodules & Workflows с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Git Advanced: Monorepo, Submodules & Workflows?
Предыдущий опыт не требуется. Git Advanced: Monorepo, Submodules & Workflows на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Интерактивное перебазирование и изменение коммитов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Git Advanced: Monorepo, Submodules & Workflows?
Да. Каждый урок Git Advanced: Monorepo, Submodules & Workflows включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Интерактивное перебазирование и изменение коммитов
- Откладывание и выборочное применение изменений
- Reflog для восстановления
- Бисекция: поиск проблемных коммитов