Git как изменить название коммита после push

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»

Рабочий процесс в системе контроля версий git сводится к тому, что разработчик создает от ветки develop новую ветку для реализации конкретной задачи. Принято, что в ветке каждому коммиту соответствует более-менее логически законченная единица работы или же изменения, которые в будущем может потребоваться отменить.

Однако порой в спешке под конец рабочего дня разработчик может закоммититься с подписью вроде такой «WIP» или «TMP». В статье рассмотрим, как в git переименовать коммит. При этом возможны два основных случая — коммит является последним или коммит не является последним.

Переименование последнего коммита

На следующий день разработчик приходит на работу, просматривает изменения в ветке и вспоминает, что нужно изменить комментарий к коммиту. Для этого достаточно использовать команду git commit --amend -m "Новое название коммита".

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

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

Итак, чтобы в git исправить комментарий такого коммита потребуется выполнить rebase в интерактивном режиме.

1. Сначала нужно посмотреть, на сколько коммитов назад находится тот коммит, которые нужно отредактировать. Для этого можно использоваться либо git log --oneline, либо консольный GUI для Git, например, tig.

Видим, что изменить комментарий нужно к коммиту «tmp», находящийся позади на четыре коммита относительно HEAD.

2. Теперь запускаем rebase в интерактивной режиме:

git rebase -i HEAD~5

3. В появившемся редакторе следует в строках коммитов изменить команду pick на reword.

Затем сохраняем файл и выходим.

4. Автоматически начнется ребейз и откроется файл редактирования коммита. Здесь необходимо ввести новую подпись к коммиту.

5. Остаётся сохранить и выйти. Теперь название коммита изменено.

Важно. Оба описанных способа приводят к изменению коммитов, а значит коммиты на сервере и в локальной ветке будут теперь отличаться. Поэтому запушить ветку так просто не получится — нужно использовать флаг --force.

git push --force

Однако, если работа в ветке ведётся несколькими разработчиками одновременно, тогда такой подход неприемлем.

Метки: Метки: git

Changing the latest Git commit message

If the message to be changed is for the latest commit to the repository, then the following commands are to be executed:

  1. git commit --amend -m "New message"
    
  2. git push --force repository-name branch-name
    

Note that using --force is not recommended unless you are absolutely sure that no one else has cloned your repository after the latest commit.

A safer alternative is to use:

git push --force-with-lease repository-name branch-name

Unlike --force, which will destroy any changes someone else has pushed to the branch, --force-with-lease will abort if there was an upstream change to the repository.

Changing older commit messages

If the message needs to be amended for an older commit, then the interactive rebase tool can be used:

  1. Navigate to the repository that contains the commit you want to amend and open a terminal window.
  2. Use the git rebase -i HEAD~n command to display a list of the last nn commits in your default text editor. For example, the following command would display a list of the last three commits in your current branch:
    git rebase -i HEAD~3 
    

The list would be similiar to
this:

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
  1. Replace pick with reword before each commit message that needs to be changed:
    pick e499d89 Delete CNAME
    reword 0c39034 Better README
    reword f7fde4a Change the commit message but push the same commit.
    
  2. Save and close the commit list file.
  3. In each resulting commit file, type the new commit message, save the file, and close it.
  4. Force push the amended commits using git push --force.

Many programmers underestimate the role of the commit message, while it is very important for managing the work. It helps other developers working on your project to understand the changes that you have made. So it must be as concrete, well-structured and clear as possible.

In this snippet, we will show you how to change your most recent commit message, as well as how to change any number of commit messages in the history.

Read on to see the options.

You can use --amend flag with the git commit command to commit again for changing the latest commit:

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

Running this will overwrite not only your recent commit message but, also, the hash of the commit. Note, that it won’t change the date of the commit.

It will also allow you to add other changes that you forget to make using the git add command:

git add more/changed/w3docs.txt
git commit --amend -m "message"

The -m option allows writing the new message without opening the Editor.

If you want to change the message of the commit that is already pushed to the server, you should force push it using the git push command with —force flag, otherwise, your push will be rejected.

Check out Force Pushing Local Changes to Remote for more details on how to force push your changes.

In this section, we will show you the steps to follow if you want to change multiple commit messages in the history.

Let’s assume that we want to take the 10 latest commit messages, starting from the HEAD.

Run Git Rebase in Interactive Mode

Firstly, you should run the git rebase in the interactive mode:

Type «Reword»

After the first step, the editor window will show up the 10 most recent commits. It will offer you to input the command for each commit. All you need to do is typing «reword» at the beginning of each commit you want to change and save the file. After saving, a window will open for each selected commit for changing the commit message.

Type Reword

Enter a New Commit Message

After the second step, an editor will open for each commit. Type a new commit message and save the file.

Enter a new commit message

Check out Force Pushing Local Changes to Remote for more details on how to force push your changes.

It is not recommended to change a commit that is already pushed because it may cause problems for people who worked on that repository.

If you change the message of the pushed commit, you should force push it using the git push command with --force flag (suppose, the name of remote is origin, which is by default):

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

git push --force origin HEAD

—force overwrites the remote branch on the basis of your local branch. It destroys all the pushed changes made by other developers. It refers to the changes that you don’t have in your local branch.

Here is an alternative and safer way to amend the last commit:

git push --force-with-lease origin HEAD

—force-with-lease is considered a safer option that will not overwrite the work done on the remote branch in case more commits were attached to it (for instance, by another developer). Moreover, it helps you to avoid overwriting another developer’s work by force pushing.

The git add command is used for adding changes in the working directory to the staging area. It instructs Git to add updates to a certain file in the next commit. But for recording changes the git commit command should also be run. The git add and git commitcommands are the basis of Git workflow and used for recording project versions into the history of the repository. In combination with these two commands, the git status command is also needed to check the state of the working directory and the staging area.

The git push command is used to upload the content of the local repository to the remote repository. After making changes in the local repository, you can push to share the modification with other members of the team.

Git refuses your push request if the history of the central repository does not match the local one. In this scenario, you should pull the remote branch and merge it into the local repository then push again. The --force flag matches the remote repository’s branch and the local one cleaning the upstream changes from the very last pull. Use force push when the shared commits are not right and are fixed with git commit --amend or an interactive rebase. The interactive rebase is also a safe way to clean up the commits before sharing. The git commit --amend option updates the previous commit.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Git как изменить аккаунт
  • Git как изменить адрес репозитория
  • Git игнорирует папку как исправить
  • Git xcrun error invalid active developer path
  • Git submodule error pathspec

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии