Как изменить message коммита

If a commit message contains unclear, incorrect, or sensitive information, you can amend it locally and push a new commit with a new message to GitHub. You can also change a commit message to add missing information.

If a commit message contains unclear, incorrect, or sensitive information, you can amend it locally and push a new commit with a new message to GitHub. You can also change a commit message to add missing information.

Rewriting the most recent commit message

You can change the most recent commit message using the git commit --amend command.

In Git, the text of the commit message is part of the commit. Changing the commit message will change the commit ID—i.e., the SHA1 checksum that names the commit. Effectively, you are creating a new commit that replaces the old one.

Commit has not been pushed online

If the commit only exists in your local repository and has not been pushed to GitHub.com, you can amend the commit message with the git commit --amend command.

  1. On the command line, navigate to the repository that contains the commit you want to amend.

  2. Type git commit --amend and press Enter.

  3. In your text editor, edit the commit message, and save the commit.

    • You can add a co-author by adding a trailer to the commit. For more information, see «Creating a commit with multiple authors.»

    • You can create commits on behalf of your organization by adding a trailer to the commit. For more information, see «Creating a commit on behalf of an organization»

The new commit and message will appear on GitHub.com the next time you push.

You can change the default text editor for Git by changing the core.editor setting. For more information, see «Basic Client Configuration» in the Git manual.

Amending older or multiple commit messages

If you have already pushed the commit to GitHub.com, you will have to force push a commit with an amended message.

We strongly discourage force pushing, since this changes the history of your repository. If you force push, people who have already cloned your repository will have to manually fix their local history. For more information, see «Recovering from upstream rebase» in the Git manual.

Changing the message of the most recently pushed commit

  1. Follow the steps above to amend the commit message.
  2. Use the push --force-with-lease command to force push over the old commit.
    $ git push --force-with-lease origin EXAMPLE-BRANCH

Changing the message of older or multiple commit messages

If you need to amend the message for multiple commits or an older commit, you can use interactive rebase, then force push to change the commit history.

  1. On the command line, navigate to the repository that contains the commit you want to amend.

  2. Use the git rebase -i HEAD~n command to display a list of the last n commits in your default text editor.

    # Displays a list of the last 3 commits on the current branch
    $ git rebase -i HEAD~3

    The list will look similar to the following:

    pick e499d89 Delete CNAME
    pick 0c39034 Better README
    pick f7fde4a Change the commit message but push the same commit.
    
    # Rebase 9fdb3bd..f7fde4a onto 9fdb3bd
    #
    # Commands:
    # p, pick = use commit
    # r, reword = use commit, but edit the commit message
    # e, edit = use commit, but stop for amending
    # s, squash = use commit, but meld into previous commit
    # f, fixup = like "squash", but discard this commit's log message
    # x, exec = run command (the rest of the line) using shell
    #
    # These lines can be re-ordered; they are executed from top to bottom.
    #
    # If you remove a line here THAT COMMIT WILL BE LOST.
    #
    # However, if you remove everything, the rebase will be aborted.
    #
    # Note that empty commits are commented out
  3. Replace pick with reword before each commit message you want to change.

    pick e499d89 Delete CNAME
    reword 0c39034 Better README
    reword f7fde4a Change the commit message but push the same commit.
  4. Save and close the commit list file.

  5. In each resulting commit file, type the new commit message, save the file, and close it.

  6. When you’re ready to push your changes to GitHub, use the push —force command to force push over the old commit.

    $ git push --force origin EXAMPLE-BRANCH

For more information on interactive rebase, see «Interactive mode» in the Git manual.

As before, amending the commit message will result in a new commit with a new ID. However, in this case, every commit that follows the amended commit will also get a new ID because each commit also contains the id of its parent.

If you have included sensitive information in a commit message, force pushing a commit with an amended commit may not remove the original commit from GitHub. The old commit will not be a part of a subsequent clone; however, it may still be cached on GitHub and accessible via the commit ID. You must contact GitHub Support with the old commit ID to have it purged from the remote repository.

Further reading

  • «Signing commits»

On this question there are a lot of answers, but none of them explains in super detail how to change older commit messages using Vim. I was stuck trying to do this myself, so here I’ll write down in detail how I did this especially for people who have no experience in Vim!

I wanted to change my five latest commits that I already pushed to the server. This is quite ‘dangerous’ because if someone else already pulled from this, you can mess things up by changing the commit messages. However, when you’re working on your own little branch and are sure no one pulled it you can change it like this:

Let’s say you want to change your five latest commits, and then you type this in the terminal:

git rebase -i HEAD~5

*Where 5 is the number of commit messages you want to change (so if you want to change the 10th to last commit, you type in 10).

This command will get you into Vim there you can ‘edit’ your commit history. You’ll see your last five commits at the top like this:

pick <commit hash> commit message

Instead of pick you need to write reword. You can do this in Vim by typing in i. That makes you go in to insert mode. (You see that you’re in insert mode by the word INSERT at the bottom.) For the commits you want to change, type in reword instead of pick.

Then you need to save and quit this screen. You do that by first going in to ‘command-mode’ by pressing the Escbutton (you can check that you’re in command-mode if the word INSERT at the bottom has disappeared). Then you can type in a command by typing :. The command to save and quit is wq. So if you type in :wq you’re on the right track.

Then Vim will go over every commit message you want to reword, and here you can actually change the commit messages. You’ll do this by going into insert mode, changing the commit message, going into the command-mode, and save and quit. Do this five times and you’re out of Vim!

Then, if you already pushed your wrong commits, you need to git push --force to overwrite them. Remember that git push --force is quite a dangerous thing to do, so make sure that no one pulled from the server since you pushed your wrong commits!

Now you have changed your commit messages!

(As you see, I’m not that experienced in Vim, so if I used the wrong ‘lingo’ to explain what’s happening, feel free to correct me!)

При работе с Git вы можете столкнуться с ситуацией, когда вам нужно отредактировать сообщение коммита. Существует ряд причин, по которым вы хотите внести изменения, например, исправление опечатки, удаление конфиденциальной информации или добавление дополнительной информации.

В этой статье объясняется, как изменить сообщение о самых последних или старых коммитах в Git.

Команда git commit –amend позволяет вам изменить самое последнее сообщение о коммите.

Чтобы изменить сообщение самого последнего коммита, который не был передан в удаленный репозиторий, передайте его снова, используя флаг –amend.

  1. Перейдите в каталог хранилища в вашем терминале.
  2. Выполните следующую команду, чтобы поправить (изменить) сообщение о последнем коммите:
    git commit --amend -m "New commit message."

    Команда выполняет перезапись самого последнего коммита новым.

    Опция -m позволяет записать новое сообщение в командной строке без открытия редактора сессии.

Перед изменением сообщения о коммите вы также можете добавить другие ранее забытые изменения:

git add .git commit --amend -m "New commit message."

Измененный коммит – это новый объект с другим SHA-1. Предыдущий коммит больше не будет существовать в текущей ветке.

Как правило, вам следует избегать внесения изменений в коммит, который уже выдвинут, поскольку это может вызвать проблемы у людей, которые основывают свою работу на этом коммите. Хорошей идеей будет проконсультироваться со своими коллегами-разработчиками перед изменением принудительного коммита.

Если вы изменили сообщение о самом последнем введенном коммите, вам придется принудительно нажать его.

  1. Перейдите в хранилище.
  2. Исправьте сообщение о последнем введенном коммите:
    git commit --amend -m "New commit message."
  3. Принудительно нажмите, чтобы обновить историю удаленного хранилища:
    git push --force branch-name

Если вам нужно изменить сообщение о старых или нескольких коммитах, вы можете использовать интерактив git rebase для изменения одного или нескольких старых коммитов.

Команда rebase переписывает историю коммитов, и настоятельно не рекомендуется перебазировать коммиты, которые уже переданы в удаленный репозиторий Git .

  1. Перейдите в хранилище, содержащее сообщение фиксации, которое вы хотите изменить.
  2. Введите git rebase -i HEAD~N, где N число коммитов для выполнения перебазирования. Например, если вы хотите изменить 4-й и 5-й последние коммиты, введите:
    git rebase -i HEAD~5

    Команда отобразит последние X коммитов в текстовом редакторе по умолчанию :

    pick 43f8707f9 fix: update dependency json5 to ^2.1.1
    pick cea1fb88a fix: update dependency verdaccio to ^4.3.3
    pick aa540c364 fix: update dependency webpack-dev-server to ^3.8.2
    pick c5e078656 chore: update dependency flow-bin to ^0.109.0
    pick 11ce0ab34 fix: Fix spelling.
    
    # Rebase 7e59e8ead..11ce0ab34 onto 7e59e8ead (5 commands)
  3. Переход к линии сообщения фиксации, который вы хотите изменить, и замените pick на reword:
    reword 43f8707f9 fix: update dependency json5 to ^2.1.1
    reword cea1fb88a fix: update dependency verdaccio to ^4.3.3
    pick aa540c364 fix: update dependency webpack-dev-server to ^3.8.2
    pick c5e078656 chore: update dependency flow-bin to ^0.109.0
    pick 11ce0ab34 fix: Fix spelling.
    
    # Rebase 7e59e8ead..11ce0ab34 onto 7e59e8ead (5 commands)
  4. Сохраните изменения и закройте редактор.
  5. Для каждого выбранного коммита открывается новое окно текстового редактора. Измените сообщение о коммите, сохраните файл и закройте редактор.
    fix: update dependency json5 to ^2.1.1
  6. Принудительно отправить изменения в удаленный репозиторий:
    git push --force branch-name

Чтобы изменить самое последнее сообщение о коммите, используйте команду git commit –amend и, чтобы изменить более старое или несколько сообщений о коммите git rebase -i HEAD~N.

Не вносите изменения в принудительные коммиты, так как это может вызвать массу проблем у ваших коллег.

Если вы столкнулись с проблемой или у вас есть отзыв, оставьте комментарий ниже.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Intro

This tutorial will cover various methods of rewriting and altering Git history. Git uses a few different methods to record changes. We will discuss the strengths and weaknesses of the different methods and give examples of how to work with them. This tutorial discusses some of the most common reasons for overwriting committed snapshots and shows you how to avoid the pitfalls of doing so.

Git’s main job is to make sure you never lose a committed change. But it’s also designed to give you total control over your development workflow. This includes letting you define exactly what your project history looks like; however, it also creates the potential of losing commits. Git provides its history-rewriting commands under the disclaimer that using them may result in lost content.

Git has several mechanisms for storing history and saving changes. These mechanisms include: Commit --amend, git rebase and git reflog. These options give you powerful work flow customization options. By the end of this tutorial, you’ll be familiar with commands that will let you restructure your Git commits, and be able to avoid pitfalls that are commonly encountered when rewriting history.

Changing the Last Commit: git commit --amend

The git commit --amend command is a convenient way to modify the most recent commit. It lets you combine staged changes with the previous commit instead of creating an entirely new commit. It can also be used to simply edit the previous commit message without changing its snapshot. But, amending does not just alter the most recent commit, it replaces it entirely, meaning the amended commit will be a new entity with its own ref. To Git, it will look like a brand new commit, which is visualized with an asterisk (*) in the diagram below. There are a few common scenarios for using git commit --amend. We’ll cover usage examples in the following sections.

Git commit amend

Change most recent Git commit message

Let’s say you just committed and you made a mistake in your commit log message. Running this command when there is nothing staged lets you edit the previous commit’s message without altering its snapshot.

Premature commits happen all the time in the course of your everyday development. It’s easy to forget to stage a file or to format your commit message the wrong way. The --amend flag is a convenient way to fix these minor mistakes.

git commit --amend -m "an updated commit message"

Adding the -m option allows you to pass in a new message from the command line without being prompted to open an editor.

Changing committed files

The following example demonstrates a common scenario in Git-based development. Let’s say we’ve edited a few files that we would like to commit in a single snapshot, but then we forget to add one of the files the first time around. Fixing the error is simply a matter of staging the other file and committing with the --amend flag:

# Edit hello.py and main.py
git add hello.py
git commit 
# Realize you forgot to add the changes from main.py 
git add main.py 
git commit --amend --no-edit

The --no-edit flag will allow you to make the amendment to your commit without changing its commit message. The resulting commit will replace the incomplete one, and it will look like we committed the changes to hello.py and main.py in a single snapshot.

Don’t amend public commits

Amended commits are actually entirely new commits and the previous commit will no longer be on your current branch. This has the same consequences as resetting a public snapshot. Avoid amending a commit that other developers have based their work on. This is a confusing situation for developers to be in and it’s complicated to recover from.

Recap

To review, git commit --amend lets you take the most recent commit and add new staged changes to it. You can add or remove changes from the Git staging area to apply with a --amend commit. If there are no changes staged, a --amend will still prompt you to modify the last commit message log. Be cautious when using --amend on commits shared with other team members. Amending a commit that is shared with another user will potentially require confusing and lengthy merge conflict resolutions.

Changing older or multiple commits

To modify older or multiple commits, you can use git rebase to combine a sequence of commits into a new base commit. In standard mode, git rebase allows you to literally rewrite history — automatically applying commits in your current working branch to the passed branch head. Since your new commits will be replacing the old, it’s important to not use git rebase on commits that have been pushed public, or it will appear that your project history disappeared.

In these or similar instances where it’s important to preserve a clean project history, adding the -i option to git rebase allows you to run rebase interactive. This gives you the opportunity to alter individual commits in the process, rather than moving all commits. You can learn more about interactive rebasing and additional rebase commands on the git rebase page.

Changing committed files

During a rebase, the edit or e command will pause the rebase playback on that commit and allow you to make additional changes with git commit --amend Git will interrupt the playback and present a message:

Stopped at 5d025d1... formatting
You can amend the commit now, with

git commit --amend

Once you are satisfied with your changes, run

git rebase --continue

Multiple messages

Each regular Git commit will have a log message explaining what happened in the commit. These messages provide valuable insight into the project history. During a rebase, you can run a few commands on commits to modify commit messages.

  • Reword or ‘r’ will stop rebase playback and let you rewrite the individual commit message during.
  • Squash or ‘s’ during rebase playback, any commits marked s will be paused on and you will be prompted to edit the separate commit messages into a combined message. More on this in the squash commits section below.
  • Fixup or ‘f’ has the same combining effect as squash. Unlike squash, fixup commits will not interrupt rebase playback to open an editor to combine commit messages. The commits marked ‘f’ will have their messages discarded in-favor of the previous commit’s message.

Squash commits for a clean history

The s «squash» command is where we see the true utility of rebase. Squash allows you to specify which commits you want to merge into the previous commits. This is what enables a «clean history.» During rebase playback, Git will execute the specified rebase command for each commit. In the case of squash commits, Git will open your configured text editor and prompt to combine the specified commit messages. This entire process can be visualized as follows:

Git Tutorial: git rebase -i example

Note that the commits modified with a rebase command have a different ID than either of the original commits. Commits marked with pick will have a new ID if the previous commits have been rewritten.

Modern Git hosting solutions like Bitbucket now offer «auto squashing» features upon merge. These features will automatically rebase and squash a branch’s commits for you when utilizing the hosted solutions UI. For more info see «Squash commits when merging a Git branch with Bitbucket.»

Recap

Git rebase gives you the power to modify your history, and interactive rebasing allows you to do so without leaving a “messy” trail. This creates the freedom to make and correct errors and refine your work, while still maintaining a clean, linear project history.

The safety net: git reflog

Reference logs, or «reflogs» are a mechanism Git uses to record updates applied to tips of branches and other commit references. Reflog allows you to go back to commits even though they are not referenced by any branch or tag. After rewriting history, the reflog contains information about the old state of branches and allows you to go back to that state if necessary. Every time your branch tip is updated for any reason (by switching branches, pulling in new changes, rewriting history or simply by adding new commits), a new entry will be added to the reflog. In this section we will take a high level look at the git reflog command and explore some common uses.

Usage

This displays the reflog for the local repository.

git reflog --relative-date

This shows the reflog with relative date information (e.g. 2 weeks ago).

Example

To understand git reflog, let’s run through an example.

0a2e358 HEAD@{0}: reset: moving to HEAD~2
0254ea7 HEAD@{1}: checkout: moving from 2.2 to main
c10f740 HEAD@{2}: checkout: moving from main to 2.2

The reflog above shows a checkout from main to the 2.2 branch and back. From there, there’s a hard reset to an older commit. The latest activity is represented at the top labeled HEAD@{0}.

If it turns out that you accidentally moved back, the reflog will contain the commit main pointed to (0254ea7) before you accidentally dropped 2 commits.

git reset --hard 0254ea7

Using Git reset, it is now possible to change main back to the commit it was before. This provides a safety net in case the history was accidentally changed.

It’s important to note that the reflog only provides a safety net if changes have been committed to your local repository and that it only tracks movements of the repositories branch tip. Additionally reflog entries have an expiration date. The default expiration time for reflog entries is 90 days.

For additional information, see our git reflog page. 

Summary

In this article we discussed several methods of changing git history, and undoing git changes. We took a high level look at the git rebase process. Some Key takeaways are:

  • There are many ways to rewrite history with git.
  • Use git commit --amend to change your latest log message.
  • Use git commit --amend to make modifications to the most recent commit.
  • Use git rebase to combine commits and modify history of a branch.
  • git rebase -i gives much more fine grained control over history modifications than a standard git rebase.

Learn more about the commands we covered at their individual pages:

  • git rebase
  • git reflog

Изменение комментария у последнего коммита

Чтобы изменить комментарий (сообщение) к последнему коммиту в вашем локальном репозитории используется команда:

git commit --amend

Данная команда предназначена для изменения комментария у последнего коммита только в вашем локальном репозитории. После ее выполнения, откроется текстовый редактор, в котором вы можете изменить сообщение коммита, а затем сохранить изменения.

Фактически при выполнении данной команды происходит создание нового коммита, который заменяет предыдущий. Это означает, что идентификатор коммита изменяется.

Изменение комментария у произвольного коммита

Чтобы изменить комментарий у произвольного коммита или у нескольких последних коммитов используется интерактивный ребейз.

Для этого используется команда:

rebase -i HEAD~n

Вместо n необходимо указать число, которое соответствует номеру коммита, комментарий которого вы хотите изменить, а если быть более точным, то это количество последних коммитов, комментарии у которых вы сможете изменить. Таким образом вы измените сообщения у соответствующих коммитов.

Например, чтобы изменить комментарии у трех последних коммитов используется команда:

git rebase -i HEAD~3

В результате выполнения данной команды откроется текстовый редактор примерно со следующим содержимым:

pick 64e2b94 Fixed data lost.
pick eb538db Added ability to create new files.
pick c427a24 Fixed removing incorrect lines.

# Rebase b06e2f1..c427a24 onto b06e2f1 (3 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Сверху расположены три строчки с сообщениями каждого коммита. В начале каждой строки находится слово pick и ID коммита. Для тех коммитов, у которых вы хотите изменить сообщение, необходимо изменить слово pick на reword (или просто на r). Например:

pick 64e2b94 Fixed data lost.
r eb538db Added ability to create new files.
r c427a24 Fixed removing incorrect lines.

Сохраните изменения и закройте редактор. После этого автоматически откроется редактор с первым коммитом (напротив которого вы только что изменили pick на r). Измените сообщение коммита, сохраните изменения и закройте редактор. Затем снова автоматически откроется редактор со следующим коммитом, измените сообщение коммита и снова закройте редактор.

Смотрите также:

  • Как изменить файлы в старом коммите (не последнем)
  • Как добавить все файлы в коммит, кроме одного
  • Как создать ветку из предыдущего коммита
  • Команда Git stash. Как прятать изменения в Git
  • Как показать файлы, которые будут добавлены в текущий коммит
  • Как отменить git add
  • Как клонировать репозиторий
  • Как посмотреть ветки
  • Как переключиться на ветку
  • Как удалить ветку

Понравилась статья? Поделить с друзьями:
  • Как изменить memoji на айфоне свой стикер
  • Как изменить mediainfo видеофайла
  • Как изменить mdb файл
  • Как изменить md5 сумму файла
  • Как изменить mcc код магазина