Ошибка git commit

I am trying to upload a Ruby app to Heroku. I start with git init and then I type git add . and then I use git commit -m initial commit.

Whenever I use git commit -m, I receive an error message saying:

git commit error:pathspect ‘commit’ did not match any file(s) known to git.

I have been told that this is happening because the arguments are in the wrong order.

The thing I noticed is that when I use git add . it will not list the files that are being added because it will just go to the next line.

I suspect that I am having this problem because my files are not really being added.

I would appreciate any advice about how to correct this problem.

Kenny Evitt's user avatar

Kenny Evitt

9,2816 gold badges66 silver badges93 bronze badges

asked Jun 5, 2013 at 22:55

user2457644's user avatar

The command line arguments are separated by space. If you want provide an argument with a space in it, you should quote it. So use git commit -m "initial commit".

answered Jun 5, 2013 at 22:58

kan's user avatar

kankan

28.3k7 gold badges72 silver badges101 bronze badges

4

I would just like to add—

In windows the commit message should be in double quotes (git commit -m "initial commit" instead of git commit -m 'initial commit'), as I spent about an hour, just to figure out that single quote is not working in windows.

toto_tico's user avatar

toto_tico

18k9 gold badges97 silver badges116 bronze badges

answered Sep 8, 2014 at 0:32

Nicks's user avatar

NicksNicks

16k8 gold badges58 silver badges65 bronze badges

6

In my case, this error was due to special characters what I was considering double quotes as I copied the command from a web page.

answered Nov 9, 2014 at 16:11

zeeawan's user avatar

zeeawanzeeawan

6,6872 gold badges50 silver badges56 bronze badges

I figured out mistake here use double quotations instead of single quotations.

change this

git commit -m 'initial commit'

to

git commit -m "initial commit"

agarcian's user avatar

agarcian

3,9093 gold badges33 silver badges55 bronze badges

answered Sep 22, 2018 at 4:33

saigopi.me's user avatar

saigopi.mesaigopi.me

14.1k3 gold badges84 silver badges54 bronze badges

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

answered Sep 11, 2016 at 13:11

Linux_Google's user avatar

I have encounter the same problem. my syntax has no problem.
What I found is that I copied and pasted git commit -m «comments» from my note. I retype it, the command execute without issue. It turns out the and » « are the problem when I copy paste to terminal.

answered Jul 3, 2019 at 13:26

Haibin Chen's user avatar

1

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

answered Feb 5, 2015 at 0:04

Jerry Krinock's user avatar

Type the command git commit -m "Initial Commit" yourself in the terminal/command prompt instead of copy and paste from web page. I believe this will help.

answered Jun 25, 2022 at 11:59

Freeman's user avatar

In my case, the problem was I used wrong alias for git commit -m. I used gcalias which dit not meant git commit -m

answered Dec 4, 2019 at 11:09

T G's user avatar

if there are anybodys using python os to invoke git,u can use os.system(‘git commit -m » ‘+str(comment)+'»‘)

answered Sep 12, 2017 at 2:29

sixsixsix's user avatar

sixsixsixsixsixsix

1,76821 silver badges19 bronze badges

In my case the problem was I had forgotten to add the switch -m before the quoted comment. It may be a common error too, and the error message received is exactly the same

answered Aug 30, 2019 at 19:01

Javier D.'s user avatar

Javier D.Javier D.

751 silver badge10 bronze badges

Solved! Here is how I solved this issue:

  1. Made an app on Heroku first and prepared all the codes in local_folder to push into it.
  2. Cloned the remote app using heroku git:clone -a app_name
  3. then cd app_name
  4. then copied all the codes into this folder from local_folder
  5. then git add .
  6. then git commit -am "initial commit"
  7. then git push heroku master
  8. Viola!

answered Jul 17, 2021 at 17:07

Deepak Mittal's user avatar

Had the same problem. " or ' doesn’t work for me.

In my case, i used git commit to add commit-msg. After this commit, git commit -m 'xxx' works as before.

answered Jan 31 at 13:11

SIMIN's user avatar

SIMINSIMIN

11 bronze badge

Время на прочтение
4 мин

Количество просмотров 44K

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

Автор материала, перевод которого мы публикуем сегодня, собирается обсудить распространённые ошибки, которые совершают программисты при работе с Git, и поговорить о том, как с этими ошибками бороться.

Ошибка в сообщении последнего коммита

После нескольких часов хорошей работы легко допустить ошибку в сообщении коммита. К счастью, это легко исправить с помощью следующей команды:

git commit --amend

Эта команда откроет редактор и позволит внести изменения в последнее сообщение коммита. Никому кроме вас не стоит знать, что вы написали «Initial commment» с тремя «m».

Ошибка в имени ветки

Предположим, что на часах почти 15:00, а вы ещё не обедали. В результате, терзаемые голодом, вы назвали новую ветку feature-brunch. Вкуснятина, ничего не скажешь.

Эту проблему тоже можно решить. Переименовать ветку можно так же, как переименовывают файлы с помощью команды mv. Речь идёт о перемещении её в новое место с правильным именем:

git branch -m feature-brunch feature-branch

Если вы уже отправили эту ветку в репозиторий, вам, для её переименования, потребуется сделать ещё пару дел. Старую ветку надо удалить, а новую — отправить в репозиторий:

git push origin --delete feature-brunch
git push origin feature-branch

Случайный коммит изменений в ветку master

Предположим, вы работаете над некоей новой возможностью, и, в спешке, забыли создать для неё новую ветку. Вы закоммитили уже кучу файлов и всё это лежит в ветке master. Переместить все эти изменения в новую ветку можно с помощью следующих трёх команд. Обратите внимание на то, что если вы не воспользовались, в применении к изменениям, командами commit или stash, они будут утеряны.

git branch feature-branch
git reset HEAD~ --hard
git checkout feature-branch

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

Работа с файлами, которые забыли добавить в последний коммит

Ещё одна распространённая оплошность при работе с Git заключается в том, что коммиты делают слишком рано и в них не попадают нужные файлы. Скажем, вы пропустили некий файл, забыли его сохранить, или вам нужно внести небольшое изменение в файл для того, чтобы последний коммит имел смысл. В подобной ситуации вам снова пригодится команда --amend. Добавьте пропущенный файл в индекс репозитория и запустите эту команду:

git add missed-file.txt
git commit --amend

После этого вы можете изменить сообщение коммита, либо оставить его таким же, каким оно было.

Добавление не того файла в репозиторий

Как быть, если ваша ошибка представляет собой полную противоположность предыдущей? Что если вы добавили в индекс файл, который не собираетесь коммитить? Это может быть какой-нибудь ENV-файл, директория сборки проекта, фото вашей собаки, которое вы случайно сохранили не в той папке. Всё это можно исправить.

Если ваши действия ограничиваются индексированием файла, но вы пока не закоммитили его, справиться с проблемой будет очень легко, воспользовавшись командой reset:

git reset /assets/img/misty-and-pepper.jpg

Если вы продвинулись достаточно далеко и успели изменение закоммитить, то знайте, что и это поправимо. Придётся лишь воспользоваться ещё несколькими командами:

git reset --soft HEAD~1
git reset /assets/img/misty-and-pepper.jpg
rm /assets/img/misty-and-pepper.jpg
git commit

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

Что делать, если всё пошло не так?

Методика, которую мы сейчас обсудим, помогает в ситуациях, когда всё идёт не так, как надо. Например, такое происходит, когда вы слишком увлекаетесь копированием готовых решений со StackOverflow, и, после работы, ваш репозиторий оказывается в худшем состоянии чем он был в самом начале. В такую ситуацию, пожалуй, попадали все мы.

Команда git reflog показывает список всего, что вы сделали. Затем она позволяет воспользоваться инструментами Git для отката изменений, для возврата к одному из прошлых состояний репозитория. Стоит отметить, что этот метод стоит рассматривать как последнее средство, и, прежде чем им воспользоваться, стоит как следует подумать. Итак, вывести список того, что было сделано, можно следующей командой:

git reflog

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

3ff8691 (HEAD -> feature-branch) HEAD@{0}: Branch: renamed refs/heads/feature-brunch to refs/heads/feature-branch
3ff8691 (HEAD -> feature-branch) HEAD@{2}: checkout: moving from master to feature-brunch
2b7e508 (master) HEAD@{3}: reset: moving to HEAD~
3ff8691 (HEAD -> feature-branch) HEAD@{4}: commit: Adds the client logo
2b7e508 (master) HEAD@{5}: reset: moving to HEAD~1
37a632d HEAD@{6}: commit: Adds the client logo to the project
2b7e508 (master) HEAD@{7}: reset: moving to HEAD
2b7e508 (master) HEAD@{8}: commit (amend): Added contributing info to the site
dfa27a2 HEAD@{9}: reset: moving to HEAD
dfa27a2 HEAD@{10}: commit (amend): Added contributing info to the site
700d0b5 HEAD@{11}: commit: Addded contributing info to the site
efba795 HEAD@{12}: commit (initial): Initial commit

Обратите внимание на самую левую колонку этого списка. Тут содержатся индексы. Если вам нужно вернуться назад, в некий момент прошлого, выполните следующую команду, заменив {index} соответствующей ссылкой, например — dfa27a2. Выглядит эта команда так:

git reset HEAD@{index}

Итоги

Мы рассмотрели некоторые способы борьбы с ошибками, возникающими при работе с Git. Надеемся, вы подобных ошибок не допустите и вам эти приёмы работы с Git не пригодятся. А если что-то пойдёт не так — вы будете знать, что делать.

Уважаемые читатели! Знаете о каких-нибудь интересных приёмах работы с Git? Если так — просим ими поделиться.

I am trying to upload a Ruby app to Heroku. I start with git init and then I type git add . and then I use git commit -m initial commit.

Whenever I use git commit -m, I receive an error message saying:

git commit error:pathspect ‘commit’ did not match any file(s) known to git.

I have been told that this is happening because the arguments are in the wrong order.

The thing I noticed is that when I use git add . it will not list the files that are being added because it will just go to the next line.

I suspect that I am having this problem because my files are not really being added.

I would appreciate any advice about how to correct this problem.

Kenny Evitt's user avatar

Kenny Evitt

9,2816 gold badges66 silver badges93 bronze badges

asked Jun 5, 2013 at 22:55

user2457644's user avatar

The command line arguments are separated by space. If you want provide an argument with a space in it, you should quote it. So use git commit -m "initial commit".

answered Jun 5, 2013 at 22:58

kan's user avatar

kankan

28.3k7 gold badges72 silver badges101 bronze badges

4

I would just like to add—

In windows the commit message should be in double quotes (git commit -m "initial commit" instead of git commit -m 'initial commit'), as I spent about an hour, just to figure out that single quote is not working in windows.

toto_tico's user avatar

toto_tico

18k9 gold badges97 silver badges116 bronze badges

answered Sep 8, 2014 at 0:32

Nicks's user avatar

NicksNicks

16k8 gold badges58 silver badges65 bronze badges

6

In my case, this error was due to special characters what I was considering double quotes as I copied the command from a web page.

answered Nov 9, 2014 at 16:11

zeeawan's user avatar

zeeawanzeeawan

6,6872 gold badges50 silver badges56 bronze badges

I figured out mistake here use double quotations instead of single quotations.

change this

git commit -m 'initial commit'

to

git commit -m "initial commit"

agarcian's user avatar

agarcian

3,9093 gold badges33 silver badges55 bronze badges

answered Sep 22, 2018 at 4:33

saigopi.me's user avatar

saigopi.mesaigopi.me

14.1k3 gold badges84 silver badges54 bronze badges

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

answered Sep 11, 2016 at 13:11

Linux_Google's user avatar

I have encounter the same problem. my syntax has no problem.
What I found is that I copied and pasted git commit -m «comments» from my note. I retype it, the command execute without issue. It turns out the and » « are the problem when I copy paste to terminal.

answered Jul 3, 2019 at 13:26

Haibin Chen's user avatar

1

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

answered Feb 5, 2015 at 0:04

Jerry Krinock's user avatar

Type the command git commit -m "Initial Commit" yourself in the terminal/command prompt instead of copy and paste from web page. I believe this will help.

answered Jun 25, 2022 at 11:59

Freeman's user avatar

In my case, the problem was I used wrong alias for git commit -m. I used gcalias which dit not meant git commit -m

answered Dec 4, 2019 at 11:09

T G's user avatar

if there are anybodys using python os to invoke git,u can use os.system(‘git commit -m » ‘+str(comment)+'»‘)

answered Sep 12, 2017 at 2:29

sixsixsix's user avatar

sixsixsixsixsixsix

1,76821 silver badges19 bronze badges

In my case the problem was I had forgotten to add the switch -m before the quoted comment. It may be a common error too, and the error message received is exactly the same

answered Aug 30, 2019 at 19:01

Javier D.'s user avatar

Javier D.Javier D.

751 silver badge10 bronze badges

Solved! Here is how I solved this issue:

  1. Made an app on Heroku first and prepared all the codes in local_folder to push into it.
  2. Cloned the remote app using heroku git:clone -a app_name
  3. then cd app_name
  4. then copied all the codes into this folder from local_folder
  5. then git add .
  6. then git commit -am "initial commit"
  7. then git push heroku master
  8. Viola!

answered Jul 17, 2021 at 17:07

Deepak Mittal's user avatar

Had the same problem. " or ' doesn’t work for me.

In my case, i used git commit to add commit-msg. After this commit, git commit -m 'xxx' works as before.

answered Jan 31 at 13:11

SIMIN's user avatar

SIMINSIMIN

11 bronze badge

1 Answer

Check you git config core.editor value.
It might refer to a path with spaces in it, without quotes.

Make sure to use simple quotes when registering that editor path:
(And double quotes around the all command expression registered.
And ‘/‘ instead of ‘\‘ for the path separator)

git config core.editor "'C:/path/with spaces/xxx.exe' -<someoptions>"

That what was done when using, for instance, Visual Studio Code as a git editor.

Community's user avatar

answered Sep 13, 2015 at 10:15

VonC's user avatar

VonCVonC

1.3m530 gold badges4426 silver badges5266 bronze badges

1

  • Suddenly started being a problem and this command fixed it, even though I’m using /usr/bin/vim

    Nov 6, 2017 at 21:48

Git is a popular version control system that allows developers to manage and keep track of their code changes. However, sometimes, issues can arise during the Git commit process that can cause it to stop working and display an error. One such error is «Error building trees». This error occurs when Git is unable to build a tree from the index file, due to conflicts in the index, incorrect file permissions, or other issues.

Method 1: Check for conflicts in the index

One possible solution to fix the «Git: how to fix git commit stopped working — Error building trees?» issue is to check for conflicts in the index. Here are the steps to do it:

  1. Open your terminal or Git Bash and navigate to your Git repository.
  2. Run the command git status to check if there are any conflicts in the index.
  3. If there are conflicts, you will see a message like this: «You have unmerged paths.»
  4. To resolve the conflicts, run the command git mergetool. This will open a graphical tool to help you resolve the conflicts.
  5. Follow the instructions in the tool to resolve the conflicts. You can use the tool to compare the conflicting files and choose which changes to keep.
  6. Once you have resolved the conflicts, save and close the tool.
  7. Run the command git add . to stage the changes.
  8. Run the command git commit to commit the changes.

Here is an example of how to use these commands:

$ cd my-git-repo
$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")
...
$ git mergetool
Merging:
file.txt

Normal merge conflict for 'file.txt':
  {local}: modified
  {remote}: modified
Hit return to start merge resolution tool (opendiff):
...
$ git add .
$ git commit

In this example, we have resolved a conflict in the file «file.txt». We used the git mergetool command to open a graphical tool to help us resolve the conflict. We then used git add . to stage the changes and git commit to commit the changes.

Note that these commands may vary depending on your Git version and operating system. It is recommended to consult the Git documentation or seek help from the community if you encounter any issues.

Method 2: Reset the index and reapply changes

To fix the «Git: how to fix git commit stopped working — Error building trees?» error, you can reset the index and reapply changes. Here are the steps:

  1. First, run the following command to reset the index:
  1. Then, run the following command to add the changes back to the index:
  1. Finally, run the following command to commit the changes:
git commit -m "Commit message"

Here is an example of how to fix the error:

$ git commit -m "Initial commit"
error: Error building trees
$ git reset
Unstaged changes after reset:
M       file1.txt
M       file2.txt
$ git add .
$ git commit -m "Initial commit"
[master (root-commit) 4b825dc] Initial commit
 2 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file1.txt
 create mode 100644 file2.txt

In the example above, the error occurred when trying to commit changes. The git reset command was used to reset the index, and then the changes were added back to the index using git add .. Finally, the changes were committed with git commit -m "Initial commit".

Overall, this method involves resetting the index and reapplying changes to fix the error.

Method 3: Check file permissions

To fix the «Git commit stopped working — Error building trees» issue using the «Check file permissions» method, follow these steps:

  1. Open your terminal and navigate to your Git repository.

  2. Run the following command to check the file permissions:

git ls-tree -r HEAD | awk '{print $3}' | xargs -I {} sh -c 'test -x "{}" || echo "{}"'

This command will list all the files in your repository and check if they have executable permissions. If a file doesn’t have executable permissions, it will be listed in the output.

  1. Once you have identified the files with incorrect permissions, you can use the following command to add executable permissions to them:

Replace «path/to/file» with the actual path to the file that needs executable permissions.

  1. After you have updated the file permissions, try committing your changes again:
git commit -m "Your commit message"

If the commit is successful, you have fixed the «Git commit stopped working — Error building trees» issue.

Note: If you are still experiencing the issue after checking file permissions, there may be other underlying issues with your Git repository. In that case, you may need to try other solutions or seek further assistance.

Method 4: Revert to an earlier commit

To fix the «Git: how to fix git commit stopped working — Error building trees?» issue by reverting to an earlier commit, follow these steps:

  1. Find the commit hash of the last working commit using git log.

    $ git log
    commit 1234567890abcdefg (HEAD -> master)
    Author: John Doe <johndoe@example.com>
    Date:   Mon Jun 1 12:00:00 2022 -0500
    
        Add new feature
  2. Revert to the last working commit using git revert.

    $ git revert 1234567890abcdefg
  3. Resolve any conflicts that arise during the revert process.

    $ git status
    On branch master
    Your branch is ahead of 'origin/master' by 1 commit.
      (use "git push" to publish your local commits)
    
    You have unmerged paths.
      (fix conflicts and run "git commit")
      (use "git merge --abort" to abort the merge)
    
    Unmerged paths:
      (use "git add <file>..." to mark resolution)
            both modified:   file.txt
    
    no changes added to commit (use "git add" and/or "git commit -a")
  4. Edit the conflicted files to resolve the conflicts.

  5. Add the resolved files to the staging area.

  6. Commit the changes.

    $ git commit -m "Revert to last working commit"
  7. Push the changes to the remote repository.

By following these steps, you should be able to fix the «Git: how to fix git commit stopped working — Error building trees?» issue using the «Revert to an earlier commit» method.

Понравилась статья? Поделить с друзьями:
  • Ошибка f04 на газовом котле балтгаз
  • Ошибка erp 23 voice
  • Ошибка isuzu c0252
  • Ошибка gff на частотном преобразователе delta
  • Ошибка ip1 на котле аристон