author identity unknown git что делать
Git author Unknown
but still the author/committer name shows [unknown]
my config file now looks like this but is still committing as [unknown]
7 Answers 7
/.gitconfig file directly. Look and see if there’s a section for [user] with the relevant information. For example, my
/.gitconfig has this.
I was having the issue of Github not properly linking my commits to my account. If you believe your email is correct, you should ensure that email is also in the Github settings for your account, as per this help page. The last section of caching is also good to note.
Copied in case of a catastrophic event in which Github goes down or ceases to exist.
Why are my commits linked to the wrong user?
GitHub uses the email saved in a commit’s header to link the commit to a GitHub user. If you find your commits are being blamed on another user, or not linked to a user at all, you should check your settings.
Good to know: commit blame does not grant access to a repo. If you are seeing commits blamed on a user you do not know, don’t worry. The user does not have access to your repo unless you’ve explicitly added them as a collaborator on that repo or to a team that has access to the repo.
Make them match
In order for GitHub to properly blame you for your commits, make sure your git email setting is correct and matches an email attached to your account.
Configuring git
To check your git setting, run this command:
If this email is not correct, you can change the global setting:
Good to know: if you work on multiple machines, you will need to check this setting on each one.
Attach the email to your GitHub account
If your email is not attached to your GitHub account you will need to add it for your future commits to be blamed correctly.
The past is history
If you used an invalid email, or an email that’s already attached to another account, then your previous commits will not be blamed correctly. While git does allow you to modify the repo’s history and correct this, it is strongly discouraged to change commits which you’ve pushed to a remote repo.
In the case where your previous commits used the correct email, after you add the email to your account they will start to link. However, it may take some time for the old data to fall out of the server’s cache before this happens.
Moving forward, if your settings match then all your new commits will be blamed on you and linked to your account.
Git happens! 6 типичных ошибок Git и как их исправить
Прим. перев.: На днях в блоге для инженеров любимого нами проекта GitLab появилась небольшая, но весьма полезная заметка с инструкциями, которые помогают сохранить время и нервы в случае различных проблем, случающихся по мере работы с Git. Вряд ли они будут новы для опытных пользователей, но обязательно найдутся и те, кому они пригодятся. А в конец этого материала мы добавили небольшой бонус от себя. Хорошей всем пятницы!
Все мы делаем ошибки, особенно при работе с такими сложными системами, как Git. Но помните: Git happens!
Если вы только начинаете путь с Git, обучитесь основам работы с ним в командной строке. А здесь я расскажу о том, как можно исправить шесть наиболее распространённых ошибок в Git.
1. Упс… Я ошибся в сообщении к последнему коммиту
После нескольких часов кодинга легко допустить ошибку в сообщении коммита. К счастью, это легко исправить:
С этой командой откроется текстовый редактор и позволит внести изменения в сообщение к последнему коммиту. И никто не узнает, что вы написали «addded» с тремя «d».
2. Упс… Я забыл добавить файл к последнему коммиту
Добавьте недостающий файл и выполните эту верную команду:
Теперь вы можете либо откорректировать сообщение, либо просто сохранить его в прежнем виде (с добавленным файлом).
3. Упс… Я добавил файл, который не должен быть в этом репозитории
Но что, если у вас обратная ситуация? Что, если вы добавили файл, который не хотите коммитить? Обманчивый ENV-файл, директорию сборки или фото с котом, что было случайно сохранено в неправильном каталоге… Всё решаемо.
Если вы сделали только stage для файла и ещё не коммитнули его, всё делается через простой reset нужного файла (находящегося в stage):
Если же вы всё-таки коммитнули изменение, потребуется дополнительный предварительный шаг:
Коммит будет откачен, картинка удалена, а затем сделан новый коммит.
4. Упс… Я коммитнул изменения в master
Итак, вы работаете над новой фичей и поспешили, забыв создать новую ветку для неё. Вы уже коммитнули кучу файлов и все эти коммиты оказались в master’е. К счастью, GitLab может предотвращать push’ы прямо в master. Поэтому мы можем откатить все нужные изменения в новую ветку следующими тремя командами:
Примечание: Убедитесь, что сначала коммитнули или stash‘нули свои изменения — иначе все они будут утеряны!
Будет создана новая ветка, в master’е — произведён откат до состояния, в котором он был до ваших изменений, а затем сделан checkout новой ветки со всеми вашими изменениями.
5. Упс… Я сделал ошибку в названии ветки
Самые внимательные могли заметить в предыдущем примере ошибку в названии ветки. Уже почти 15:00, а я всё ещё не обедал, поэтому мой голод назвал новую ветку (branch) как future-brunch. Вкуснотища!
Переименуем эту ветку аналогичным способом, что используется при переименовании файла с помощью команды mv, то есть поместив её в новое место с правильным названием:
Если вы уже push’нули эту ветку, понадобится пара дополнительных шагов. Мы удалим старую ветку из remote и push’нем новую:
Прим. перев.: Удалить ветку из remote ещё можно с помощью:
6. Oops… I did it again!
Последняя команда на тот случай, когда всё пошло не так. Когда вы накопировали и навставляли кучу решений со Stack Overflow, после чего в репозитории всё стало ещё хуже, чем было в начале. Все мы однажды сталкивались с подобным…
git reflog показывает список всех выполненных вами операций. Затем он позволяет использовать магические возможности Git’а по путешествию во времени, т.е. вернуться к любому моменту из прошлого. Должен отметить, что это ваша последняя надежда — не стоит прибегать к ней в простых случаях. Итак, чтобы получить список, выполните:
Каждый наш шаг находится под чутким наблюдением Git’а. Запуск команды на проекте выше выдал следующее:
Обратите внимание на самый левый столбец — это индекс. Если вы хотите вернуться к любому моменту в истории, выполните следующую команду, заменив
Итак, теперь у вас есть шесть способов выбраться из самых частых Gitfalls (игра слов: pitfall переводится как «ловушка, ошибка» — прим. перев.).
Бонус от переводчика
Теперь — небольшие полезные дополнения из нашего опыта:
Самые типичные ошибки и вопросы, связанные с Git, и удобные способы их решения
Авторизуйтесь
Самые типичные ошибки и вопросы, связанные с Git, и удобные способы их решения
Если вы хотите получше узнать те части Git, про которые раньше боялись спросить, то этот список для вас. Тут собраны наиболее типичные ситуации и способы их решения как из личного опыта автора, так и собранные по всему Интернету.
Ошибка в комментарии к коммиту
Если коммит ещё не был отправлен на сервер (push), то можно воспользоваться простой командой, позволяющей редактировать текст сообщения к последнему коммиту:
Как отменить последний коммит?
1 означает один коммит до HEAD, т.е. до текущего положения. Стоит заметить, что это «ядерный» способ, который отменит все изменения. Если вам нужно сохранить всё, что вы сделали, но еще не успели закоммитить, используйте:
Удалить ветку на сервере
В чём разница между «git pull» и «git fetch»?
Как отменить «git add» до коммита?
Вы выполнили git add имя_файла случайно и хотите отменить добавление файла. Если коммит ещё не был сделан, то поможет:
git reset имя_файла
Как разрешать конфликты слияния?
Удалить все локальные файлы и директории, которые не отслеживает Git, из вашей текущей копии
Осторожно! Лучше сделайте перед этим бэкап.
Клонировать все ветки с сервера
Скорее всего, вы это уже сделали, а ветки просто скрыты. Вот команда, чтобы показать их:
Переименовать локальную ветку
Вернуться к любому коммиту
Ещё раз повторим: команда отменит все текущие изменения, так что убедитесь, что вам это действительно нужно. Или используйте --soft вместо --hard.
Удалить подмодуль (submodule)
Создание подмодулей используется довольно редко, но иногда они всё-таки встречаются. Вот, что вам нужно:
Перезаписать локальные файлы во время git pull
Вам снова поможет git reset :
Как добавить пустую директорию в репозиторий?
Экспортирование исходников аналогично «svn export»
Отменить все изменения, кроме тех, что уже добавлены в планируемый коммит
Создать новую ветку на сервере из текущей локальной ветки
Восстановить удалённый файл
Сначала нужно найти последний коммит, где файл ещё существует:
Потом восстановить этот файл:
Вернуть один конкретный файл в состояние, в котором он был в каком-либо коммите
Почти как в прошлом примере, только чуть проще:
git checkout идентификатор_коммита имя_файла
3 ways to set up author information in Git
Tips on setting up Git author information for solo and pair programming
Setting up author info is one of the first tasks to do before you can start using Git. Doing it right and carefully can be much value when digging into the project history later on.
The global user
After installing it, you have to set your name and email address in order to use Git. This information will be attached to each commit you make, so without it, you won’t be able to create commits.
It’s important to specify your name and email correctly because it is the only way for developers to find you in case they have any question regarding your changeset.
We write articles like this regularly. Join our mailing list and let’s keep in touch.
If you are not sure what your current user.name or user.email is, you can check them with the following command:
Note that it lists other settings as well, such as aliases and the default push action.
Repository-specific authors
This can come in handy if you have hobby projects on your work machine.
Git does not support switching between preconfigured authors, so if you need to change the author name or email frequently, I suggest creating an alias or a script for it. (Check this post for some useful tips.)
Multiple authors for pair programming
Git currently does not support multiple authors for a single commit, but there are several options to overcome this shortcoming.
In this section I’ll go through some of them:
1. Using multiple names in the user.name
The easiest solution is to list all the authors in the user.name setting.
This can work well, if the pair-programming session lasts for a couple of hours, spanning multiple commits, as it has to be set only once. Just don’t forget to revert to your original settings afterward.
2. Adding trailers to the commit messages
Another solution might be to mention the other author in each relevant commit message. As it’s mentioned in the Git Wiki’s Commit Message Conventions section, Trailers provide a way to include additional information in a header-like, searchable, easy-to-parse format at the end of a commit message.
Consider this example commit message:
Conveniently, there is a tool to add trailers, called git-interpret-trailers.
(Of course, you can set it up globally just like any other git config.)
Finally, you can augment your commit messages all at once with the necessary co-author information just before pushing with interactive rebasing.
Be careful with this though, make sure to only edit unpushed commits, or commits on private branches. As it rewrites Git history, it can cause problems if others are on the affected branch.
3. Encoding in the author and committer fields of the commit
Git store the name and the email of two persons for each commit: the committer and the author. The difference between the two is that the author is the person who wrote the changes, while the committer is the person who uploaded them the repository.
You can list this information with git-log:
Typically they are the same if you commit your changes by yourself, but this can be a handy tool if somebody sends you a patch via e-mail. You can preserve the identity of the original author while taking credit for the commit:
This infrastructure might be used for pair programming as well as to mark the participants, but I think the other alternatives mentioned in this post are better because most of the tools don’t show both the committer and the author by default.
Summary
Git supports various workflows and can be bent to work in most situations. It’s worth the time to carefully craft appropriate metadata associated with each commit, as they can provide valuable information later on.
We write articles like this regularly. Let’s keep in touch and:
yano3 / gist:1378948
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This comment has been minimized.
Copy link Quote reply
Nikaraqua commented Jan 26, 2017 •
I tried that (precisely to do that)
But I typed it in just like that verbatum (did not substitute author for my name or anything)
= went into some sort of editing mode of that committed doc that I was trying to change the auithor of.
This «editing mode» allowed me to write in or about the doc (was a README.md for my first try at committing)
And then to get back to the usual CLI, I had to press ESC and then
(I found that on google on a forum after searching above extension. )
But I am still not entirely sure what happened or why.
This comment has been minimized.
Copy link Quote reply
antont commented Mar 27, 2017
This comment has been minimized.
Copy link Quote reply
AlisterH commented May 30, 2017
This comment has been minimized.
Copy link Quote reply
xyzzy529 commented Jul 11, 2017
This comment has been minimized.
Copy link Quote reply
coderhh commented Nov 15, 2017
I clone a repo from account 1 using account 2, after making some changes, i want to push the changes.
But account 2 was denied by remote account 1. So i config the account 1 as the local setting under working directory and ran the reset-author command. After all this, when i commit. It still use account 2 and was denied.
This comment has been minimized.
Copy link Quote reply
nafg commented Jul 17, 2020
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.