Error pathspec initial commit did not match any file s known to git

Попробуйте git fetch, чтобы ваш локальный репозиторий получал всю новую информацию от github. Он... Вопрос по теме: git.

Я не уверен, почему я не смог проверить ветку, с которой я работал раньше. См. Приведенные ниже команды (примечание: co является псевдонимом для checkout):

[email protected]:~/source/unstilted$ git branch -a
* develop
  feature/datts_right
  feature/user_controlled_menu
  feature/user_controlled_site_layouts
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/develop
  remotes/origin/feature/datts_right
  remotes/origin/master
[email protected]:~/source/unstilted$ git co feature/user_controlled_site_layouts 
error: pathspec 'feature/user_controlled_site_layouts' did not match any file(s) known to git.

Я не уверен, что это значит, и я не могу найти ничего, что я могу понять в Google.

Как проверить эту ветку и что я могу сделать, чтобы сломать это?

UPDATE

Я нашел этот пост, и запуск git show-ref дает мне:

97e2cb33914e763ff92bbe38531d3fd02408da46 refs/heads/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/heads/feature/datts_right
11a90dae8897ceed318700b9af3019f4b4dceb1e refs/heads/feature/user_controlled_menu
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/heads/master
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/HEAD
e7c17eb40610505eea4e6687e4572191216ad4c6 refs/remotes/origin/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/remotes/origin/feature/datts_right
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/master
23768aa5425cbf29d10ff24274adad42d90d15cc refs/stash
e572cf91e95da03f04a5e51820f58a7306ce01de refs/tags/menu_shows_published_only
429ebaa895d9d41d835a34da72676caa75902e3d refs/tags/slow_dev

UPDATE в каталоге .git (user_controlled_site_layouts находится в refs/heads/feature folder):

$ ls .git/refs/heads/feature/
datts_right  user_controlled_menu  user_controlled_site_layouts
$ cat .git/refs/heads/feature/user_controlled_site_layouts
3af84fcf1508c44013844dcd0998a14e61455034

ОБНОВЛЕНИЕ на git show 3af84fcf1508c44013844dcd0998a14e61455034

$ git show 3af84fcf1508c44013844dcd0998a14e61455034
commit 3af84fcf1508c44013844dcd0998a14e61455034
Author: Ramon Tayag <[email protected]>
Date:   Thu May 12 19:00:03 2011 +0800

    Removed site layouts migration

diff --git a/db/schema.rb b/db/schema.rb
index 1218fc8..2040b9f 100755
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
 #
 # It strongly recommended to check this file into your version control system.

-ActiveRecord::Schema.define(:version => 20110511012647) do
+ActiveRecord::Schema.define(:version => 20110503040056) do

   create_table "attachments", :force => true do |t|
     t.string   "name"
@@ -205,15 +205,6 @@ ActiveRecord::Schema.define(:version => 20110511012647) do
     t.integer  "old_id"
   end

-  create_table "site_layouts", :force => true do |t|
-    t.string   "name"
-    t.text     "description"
-    t.text     "content"
-    t.integer  "site_id"
-    t.datetime "created_at"
-    t.datetime "updated_at"
-  end
-
   create_table "site_styles", :force => true do |t|
     t.text     "published"
     t.datetime "created_at"

13 май 2011, в 08:44

Поделиться

Источник

40 ответов

Попробуйте git fetch, чтобы ваш локальный репозиторий получал всю новую информацию от github. Он просто берет информацию о новых ветких и фактическом коде. После этого git checkout должен работать нормально.

MarkoHiel
07 сен. 2011, в 14:24

Поделиться

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

ошибка: pathspec ‘BRANCH-NAME’ не соответствует ни одному из файлов, известных git.

Когда я попробовал git checkout origin/<BRANCH-NAME>, я получил отдельную ГОЛОВУ:

(отстранен от происхождения /)

Наконец, я сделал следующее, чтобы решить проблему:

git remote update
git fetch 
git checkout --track origin/<BRANCH-NAME>

Mayank
15 сен. 2015, в 06:42

Поделиться

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

git checkout feature/foo

в прошлом, чтобы обойти эту ошибку, я должен был

git checkout -t -b feature/foo origin/feature/foo

Я не знаю, что я сделал, чтобы попасть в эту ситуацию.

Gregory McIntyre
31 май 2011, в 01:07

Поделиться

Если вы удалили ветку с помощью git branch -D yourbranchname и снова вытащили/клонировали свое репо, вам может понадобиться снова создать локальную ветку.

Попробуйте:

git checkout -b yourbranchname

Francisco Alvarez
04 фев. 2014, в 00:14

Поделиться

Git Пользователи Windows остерегаются — без параметров --icase-pathspecs или GIT_ICASE_PATHSPECS = 1 env var, что git pathspecs будут чувствительны к регистру, в которых case

git checkout origin/FooBranch "Some/Path/To/File.txt"

не совпадает с

git checkout origin/FooBranch "Some/Path/To/File.txt"

StuartLC
21 фев. 2014, в 09:36

Поделиться

У меня есть те же вопросы, и я получил некоторую информацию по этой ссылке: git fetch не извлекает все ветки

Итак, теперь я не уверен, как эта ситуация произошла, по крайней мере, мы можем ее решить:

Шаг 1. Проверьте настройку «remote.origin.fetch», должно быть как

$git config —get remote.origin.fetch

+ ссылки/головки/private_dev_branch: ссылки/пультов ДУ/происхождение/private_dev_branch

Шаг 2. Измените «remote.origin.fetch», чтобы получить все

$git config remote.origin.fetch «+ refs/heads/*: refs/remotes/origin/*»

$git config —get remote.origin.fetch

+ ссылки/главы/*: ссылки/пультов ДУ/происхождение/*

Затем вы можете попробовать «git pull» (возможно, «git fetch origin» также работает, но я не пробовал), чтобы получить всю ветвь.

bearzyj
08 авг. 2017, в 05:45

Поделиться

Если имя ветки отсутствует, и у вас нет никакого файла с ограниченным доступом, попробуйте это

git fetch && git checkout <branch name>

Sajin M Aboobakkar
18 май 2017, в 12:20

Поделиться

git pull

Это просто исправило это для меня :)

OpMt
29 авг. 2018, в 00:29

Поделиться

Я получил это, когда сделал следующее:

  • Используемая IntelliJ IDE, подключенная к git
  • Создан новый файл и добавлен в git
  • Переименован новый файл

Когда я попытался проверить каталог, я получил эту ошибку.

Чтобы исправить:

Я открыл репо в расширениях git. Я увидел, что файл (со старым именем) был поставлен. Но поскольку он больше не существует, он не может быть зафиксирован.

Я просто отключил этот файл.

Затем я снова добавил файл (на этот раз правильно названный) в git и зафиксировал без ошибок.

Somaiah Kumbera
26 нояб. 2014, в 16:16

Поделиться

У меня была эта проблема сегодня, я пытался git checkout foo и получил error: pathspec 'foo' did not match any file(s) known to git.

Оказывается, я ошибался в репо. Итак, извлеченный урок: проверьте, на каком репо вы смотрите, прежде чем волноваться.

James Harrington
16 дек. 2014, в 18:34

Поделиться

У меня такая же проблема, потому что я использовал git clone --depth=1, что подразумевает --single-branch.

Выполняет завершенный git clone.

Huachao Huang
25 авг. 2016, в 12:08

Поделиться

Во-первых, проверьте родительскую ветвь. Затем введите

git fetch --all --prune 
git checkout <your branch>

Надеюсь, поможет!.

Shradhey Tripathi
09 авг. 2018, в 15:51

Поделиться

В ОС Windows по умолчанию git устанавливается

core.ignorecase = true

Это означает, что файлы git repo будут нечувствительны к регистру, чтобы изменить это, которое вам нужно выполнить:

yourLocalRepo> git config core.ignorecase false

эту конфигурацию можно найти в файле .gitconfig

Vasile Bors
11 окт. 2015, в 16:21

Поделиться

В моем случае у меня есть TWO branch 1) master (для живого сервера) 2) dev (тестовый сервер). Я установил несколько удаленных программ для ввода кода на соответствующем сервере. Когда я попытался переключить ветвь, я получил ошибку, например error: pathspec 'master' did not match any file(s) known to git.

Вы можете увидеть их на git remote -v.
Я удалил другой удаленный, кроме origin remote, с помощью git remote remove <remote-name>

Тогда git fetch

Теперь я могу проверить ветвь на git checkout <branch-name>.

ProCylon
10 дек. 2016, в 11:57

Поделиться

Если это происходит в Windows, это, вероятно, проблема с именем файла.

У меня была эта ошибка сегодня — я создал новый файл, добавленный в GIT, затем я сменил одну букву в имени файла с нижнего на верхний, а затем я ничего не мог — зафиксировать, вернуть, удалить файл из репо,

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

Marcin Nabiałek
03 март 2015, в 18:27

Поделиться

Произошло со мной после переименования незафиксированного файла в Android Studio.

У Git, похоже, была старая версия в своем хранилище, даже если ее больше не существовало.

fetch, pull, checkout, add all and so on did not help in my case!

Поэтому я открыл графический интерфейс Git TortoiseGit, который показал мне точный файл, вызвавший проблемы.

После этого я удалил файл из хранилища с помощью

git rm -r --cached /path/to/affected/file

и проблема исчезла

Marian Klühspies
25 март 2015, в 13:01

Поделиться

У меня была такая же проблема. Я думал, что у меня есть ветвь с именем foo, когда я пытаюсь:

git checkout foo

Я получал:

error: pathspec 'foo' did not match any file(s) known to git.

Затем я попробовал имя полной ветки:

git checkout feature/foo

тогда работал у меня.

tokhi
10 июнь 2013, в 09:54

Поделиться

Я сделал глупую ошибку, не указав флаг -m во время совершения (lol)

git commit -m "commit message in here"

Ajain Vivek
23 март 2017, в 14:25

Поделиться

в моем случае я вхожу в каталог подмодулей, не делая

  • git submodule init
  • git submodule update

Итак, git был связан с родительской папкой, которая действительно пропустила эту ветвь.

Ilya Gazman
26 авг. 2015, в 13:12

Поделиться

Ни один из этих ответов не решил мою проблему:

[email protected] ~/Documents/NetBeansProjects/Version (master)
$ git log --format=oneline
b9cc6a9078312865280fb5432a43e17eff03a5c6 Formatted README
288772f36befe6bd60dd41b8185f1e24e0119668 Updated README documentation
d2bdbe18f4169358d46fad50eacfb89786df3bf8 Version object v3.0.0-SNAPSHOT
a46b1910a3f548b4fa254a6055d25f68d3f217dd VersionFactory is now Platform agnostic
24179ae569ec7bd28311389c0a7a85ea7b4f9594 Added internal.Platform abstraction
252b684417cf4edd71aed43a15da2c8a59c629a7 Added IPlugin implementation for Sponge
e3f8d21d6cf61ee4fc806791689c984c149b45e3 Added IPlugin implementation for Bukkit
aeb403914310b4b10dee9e980cf64472e2bfda79 Refactored Version.java
ef50efcff700c6438d57f70fac30846de2747a7e Refactored TesterFactory
a20808065878d4d28657ae362235c837cfa8e625 Added IPlugin abstraction
9712a3575a70060d7ecea8b62bb5e888fdc32d07 Heavily refactored Tester
02d025788ae740dbfe3ef76a132cea8ca4e47467 Added generic Predicate<T> interface
9c565777abea9be6767dfdab4ab94ed1173750dd Minor refactoring of testCompareTo()
2ff2a28c221681e256dcff28770782736d3a796a Version object v2.0.1
d4b2e2bd830f77cdbc2297112c2e46b6555d4393 Fix compareTo()
05fe7e012b07d1a5b8de29804f96d9a6b24229a1 Make compareTo() fail
6e85371414357a41c1fc0cec0e75adba92f96832 Fix VersionFactory passing null
c1fd1f032f87d860d5ed9d6f6679c9fa522cff8d Version object v2.0
62c3a92c008a2ed11f0a4d016080afc3541d0700 Version object v1.2
c42e9e617128085e872c51b4d977a04e48d69e8f Deprecated, doc'd, future-proofed getNm


[email protected] ~/Documents/NetBeansProjects/Version (master)
$ git checkout 3a796a
error: pathspec '3a796a' did not match any file(s) known to git.

Я пытался вернуться и построить фиксацию для Version object v2.0.1. К счастью, у меня возникла идея попробовать весь хеш-код, и это сработало! Это означает, что я использовал неправильный конец хэш-кода.

[email protected] ~/Documents/NetBeansProjects/Version (master)
$ git checkout 2ff2a
Note: checking out '2ff2a'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 2ff2a28... Version object v2.0.1

[email protected] ~/Documents/NetBeansProjects/Version ((2ff2a28...))
$

Как показано выше, для частичных хеш-кодов вы должны предоставить интерфейс, а не внешний.

Nikolaii99
05 авг. 2015, в 23:30

Поделиться

В моем случае я переименовал файл, изменяющий случай файла, т.е. SomeFile.js → someFile.js

Я думаю, что это было связано с проблемой. Выполнение git fetch не помогло решить проблему.

Я вытащил файлы из своего проекта, сделал выборку и без толчка. Затем я сделал выборку, добавил их обратно и сделал толчок, и это сработало. Я не знаю, нужны ли все эти шаги, но это в конечном итоге сработало.

Kip
31 март 2015, в 23:51

Поделиться

Я скопировал url удаленного источника из другого файла .git/config, поэтому в моем новом файле .git/config отсутствовала следующая строка в разделе [remote "origin"]

fetch = +refs/heads/*:refs/remotes/origin/*

Добавление вышеуказанной строки исправило error: pathspec 'master' did not match any file(s) known to git.

AamirR
09 дек. 2018, в 16:55

Поделиться

Для меня это была проблема с моими полномочиями


Попробовав некоторые ответы, один из них помог мне решить проблему:

Запустив git fetch выдал следующую ошибку:

Не удалось разрешить хост: bitbucket.org

Все, что мне нужно было сделать, это заставить мою IDE (VS Code в моем случае) запомнить мои учетные данные:

git config --global credential.helper wincred

Git немедленно синхронизировал все изменения, и git checkout <branche> теперь работает нормально!

Jeffrey Roosendaal
30 авг. 2018, в 19:13

Поделиться

Я столкнулся с этой же проблемой, когда я впервые играл с git. При попытке моего первого совершения…

git commit -m 'first commit!'

Я получил ошибку, упомянутую OP…

error: pathspec 'commit!'' did not match any file(s) known to git.

Я думал, что, возможно, запутался git, используя ключевое слово в сообщении commit, поэтому я попробовал несколько других слов и получил ту же ошибку.

Наконец, я использовал двойные кавычки в сообщении…

git commit -m "first commit!"

Это оказалось успешным…

[master (root commit) 0000000] first commit!
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 dummyDoc.txt

TheLastGIS
28 дек. 2016, в 00:44

Поделиться

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

Поэтому я предлагаю вам дважды проверить, не используется ли ваш репозиторий другим приложением.

Mohammad Faisal
12 сен. 2018, в 16:46

Поделиться

Одна возможная причина. Если вы работаете с машиной Windows с MINGW *

ISSUE

Проверьте имя ветки, которую вы хотите проверить. Windows опускает символ ' из имени ветки во время разбора команды.

например: если у вас есть имя ветки, например bugfix/some-'branch'-name

Когда вы выдаете команду: > git checkout bugfix/some-'branch'-name, она будет анализировать ее как bugfix/some-branch-name, заметьте, что она пропускает символ '.

REMEDY

Чтобы проверить это имя ветки, добавить escape-символ при выдаче команды.

Тип: > git checkout bugfix/some-'branch'-name

Затем он работает!!

Piyush Sagar
19 окт. 2016, в 12:51

Поделиться

В моем случае я запускаю «git fetch» до «git branch…:, но получил ту же ошибку.
Затем я проанализировал его и нашел ошибку в имени моей ветки. Исправлено и успешно переключилось на ветвь.

Viktor Chmel
19 июль 2016, в 10:34

Поделиться

Я столкнулся с этой проблемой в прошлый раз, и то, что я сделал, это удалить папку (или исходный код), связанную с этой веткой.

Ex: начало ветки /foo создает папку foo на вашем локальном, поэтому я просто удаляю ее и использую git fetch $ checkout, чтобы получить код с удаленного.

Или вы можете сделать это, создав папку на том же месте, что и ветка, которую вы планировали проверить.

Ex: создайте папку foo на локальном компьютере, после этого используйте команду Git: git branch --set-upstream-to=origin/foo foo, что все. Используйте git pull для получения кода.

blackberry
25 янв. 2016, в 05:17

Поделиться

У меня была эта проблема при работе с Git в Windows. В моем случае это была проблема.
Я уже добавил и перенял файл в мой репозиторий, а потом изменил только его случай.
Чтобы решить проблему, я переименовал файл в соответствии с исходным случаем и снова переименовал его с помощью команды git mv. По-видимому, это позволяет Git отслеживать переименование.

Примечание. Я использовал Cygwin.

Thomas Eizinger
16 сен. 2015, в 15:42

Поделиться

Я столкнулся с подобной проблемой. Что привело меня в эту беду:
У меня было несколько удаленных веток, и я удалил папку с кодом.
Я потянулся.:

git pull [email protected]

Затем я добавил удаленный репозиторий:

git remote add upstream [email protected]

Затем я попытался изменить ветвь на другую ветку, скажем, AAAA, и я получил ошибку

error: pathspec 'AAAA' did not match any file(s) known to git.

Проведя час, я нашел решение.
Я снова удалил исходную папку.
Затем я сделал git pull:

git pull [email protected]

Затем я изменил ветвь, прежде чем связывать ее с удаленным репозиторием:

git checkout AAA

то я добавил его в удаленный репозиторий

git remote add upstream [email protected]

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

Amit Kumar
29 окт. 2014, в 11:21

Поделиться

Это может быть вызвано тем, что восходящий поток перезаписывает историю.

Когда это произойдет, я бросаю все затронутые репозитории, клонирую их свежими из восходящего потока и использую ‘git format-patch’/’git am’, чтобы переправлять любые выполняемые работы из старого мира в новый.

Dan Kegel
14 март 2014, в 00:27

Поделиться

Я получил тот же pathspec error на git — bash. Я использовал Tortoise git в окнах для переключения/проверки ветки.

nouveau
17 апр. 2013, в 09:08

Поделиться

У меня была та же проблема (с версией git-latest) и я обнаружил, что это связано с кодами escape-цветов, используемыми git. Интересно, может ли это объяснить, почему эта проблема возникает так часто.

Это демонстрирует, что может происходить, хотя цвет обычно задается в конфигурации git, а не в командной строке (в противном случае это будет очевидно):

~/dev/trunk (master)$ git checkout 'git branch -l  --color=always  | grep django-1.11'
error: pathspec 'django-1.11' did not match any file(s) known to git.
~/dev/trunk (master)$ git branch -l  --color=always  | grep django-1.11
  django-1.11
~/dev/trunk (master)$ git checkout 'git branch -l  | grep django-1.11'
Switched to branch 'django-1.11'
Your branch is up-to-date with 'gerrit/django-1.11'.
~/dev/trunk (django-1.11)$ 

Я полагаю, что git-конфигурация, которая не играет с настройками цвета, должна работать color = auto должна делать правильные вещи. Моя конкретная проблема заключалась в том, что git recent я использовал, был определен как псевдоним с жестко закодированными цветами, и я пытался создавать команды поверх этого.

Danimal
27 июль 2018, в 14:03

Поделиться

Я получил это на столе Github после нажатия «Обновить из…», когда было выбрано неправильное репо. Затем я изменил репо на правильный, но когда я попытался удалить изменения, я получил эту ошибку. Это потому, что это были новые файлы в репо, которые я ошибочно выбрал, но не тот, который я хотел обновить.

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

Затем я сменил селектор репо на тот, который я хотел.

user2568374
24 авг. 2015, в 14:37

Поделиться

$ cat .git/refs/heads/feature/user_controlled_site_layouts
3af84fcf1508c44013844dcd0998a14e61455034

Можете ли вы подтвердить, что следующие работы:

$ git show 3af84fcf1508c44013844dcd0998a14e61455034

Возможно, кто-то переписал историю и что это обязательство больше не существует (по какой-либо причине).

ralphtheninja
13 май 2011, в 12:28

Поделиться

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

bugfix_ # 303_multiline_opmerkingen_not_displaying_correctly_in_viewer

и

bugfix_339_hidden_fields_still_validated

вы можете увидеть на скриншоте из Git bash ниже.

Изображение 7704

Когда я попытался использовать графический интерфейс Git, я даже не мог видеть ветки вообще. Однако, когда я использовал инструмент Pycharms Git, я увидел это:

Изображение 7705

Итак, почему-то окна решили добавить некоторую неразличимую персонаж к моим именам ветвей, и именно по этой причине это не сработало. Переименование ветвей в Pycharm сделал трюк, поэтому угадайте, что это будет работать и на других IDE.

tarikki
01 июнь 2016, в 07:08

Поделиться

Вот как я решил свою ошибку!

Сначала я удалил свое репо локально, а также из моего Github. Затем я раздвоил и клонировал в свой локальный репозиторий.

После этого я сделал свое изменение и наконец

Создана Моя ветка с помощью

$git checkout -b moh_branch

изменить рабочую ветвь

$git checkout moh_branch

нажмите ветку на GitHub

$git push origin moh_branch

После этого я могу выполнить свои изменения следующим образом: —

$git add .

$git commit -m "updated readme.md"

$git push origin moh_branch

Премию 100% для меня!!

Moh K
30 авг. 2017, в 17:19

Поделиться

Поскольку ваша ветвь функции существует в удаленном режиме, это повреждает локальное репо. Итак, удалите локальное репо и повторите клонирование. Теперь ‘git checkout <branch_name>‘ должен работать для вас.

Ninos
18 апр. 2017, в 19:07

Поделиться

Это сработало для меня. Он отбрасывает все локальные изменения и сбрасывает их до последнего фиксации.

git reset --hard

timbo7io
21 янв. 2017, в 02:28

Поделиться

Если вы находитесь в Windows, вы, вероятно, можете изменить имя файла на нижний/верхний регистр, например File.txt — file.txt

Итак, проверьте, какой файл у вас есть в git и переименуйте его в нужное вам:

git status

Затем мне нужен файл file.txt → but git, который дает мне файл File.txt, поэтому просто переименуйте его

git mv File.txt file.txt

И проблема решена.

Manic Depression
07 июль 2017, в 19:04

Поделиться

Ещё вопросы

  • 0Метеор на сервере на стороне клиента с реактивным кофе
  • 0Как запускать функции в представлении Backbone
  • 1Discord — BOT отправляет личное сообщение
  • 1WELD-001318 Не удается разрешить неоднозначную зависимость между. , , в GlassFish 4
  • 0Я хочу изменить цвет определенного текста, только если он напечатан в
  • 1Ява маршаллер. Использовать значение тега в качестве значения атрибута
  • 0Ul LI Меню не отображается как блок в IE
  • 0Нужна помощь в исправлении моего кода jquery
  • 0MySQL — лучший способ получить рейтинг и сводку отзывов из базовой таблицы отзывов, например, Google
  • 1Темы и производительность с играми для Android
  • 0c # HTML встроенные проблемы с цитатами
  • 1MediaPlayer на Android играет только часть моей песни :(
  • 0Мой первый столбец кода в простой консольной программе (c ++) заканчивается как мой последний столбец
  • 0C ++ / CX WinRT File Copy
  • 0Добавление php в код php
  • 0загрузить функцию после загрузки другой
  • 0вектор <Mat>, передающий в функцию логическую ошибку
  • 1используя FFT в обработке
  • 0Как я могу получить КНОПКИ для переключения между массивами, используя next () и prev ()?
  • 0Qt: QVector <bool> to QByteArray
  • 1установка границ или экстентов составленных графиков в HoloViews
  • 0Угловая форма ввода часов не работает
  • 0Как извлечь hrefs из HTML с помощью PHP
  • 0заменить все ссылки, содержащие текст «редактировать» с изображением, за исключением определенного класса
  • 1SqlDependency выберите сегодня записи
  • 1Какова цель метода org.eclipse.jst.ws.util.JspUtils.markup (String text)
  • 0JQuery отправляет HTML-сущность / эмодзи на сервер PHP
  • 1Какие методы вызываются, только если я нажимаю кнопку «Домой»?
  • 1Поиск элемента во вложенном списке и распечатка его
  • 0Переменная, переданная = в область видимости, не обязательна
  • 0Конвертировать сумму в долларах в строку
  • 0Mysql update auto count по количеству обновлений строк
  • 0HTML-фильтрация точек событий неинтерактивных элементов?
  • 0Вставка переменных PHP MySQL [дубликаты]
  • 1Получить уникальный идентификатор мобильного телефона из JavaScript
  • 1Проблемы со скрапом — не ползли
  • 0Поворот изображения в Symfony2
  • 1«Базовое имя администратора очередей» в Websphere MQ Explorer /
  • 1просмотрите папку и получите пользовательский ввод для создания нового файла
  • 0Facebook PHP SDK v4 — пост-фид не отображается правильно
  • 1Как реализовать основанную на соотношении передискретизацию SMOTE при наборе CV-данных
  • 0«Сложение» двух классов
  • 1эффективно превращать ctypes LP_c_ubyte в питона ‘str’
  • 0Раскрывающийся в Angularjs каскад с массивом объектов json
  • 0Как разместить элемент прямо под «абсолютным» div?
  • 0Запрос DOMXPath для возврата элемента с тегом img
  • 1Добавить новый элемент в ItemsSource таблицы данных, не обновляя коллекцию
  • 0Php MySQL зацикливается на цикле? Я «перегружен»
  • 1Можно ли найти все (Java) циклы «foreach» в IntelliJ IDEA?
  • 0Как обрабатывать переменные строки столбцов в фиксированной таблице столбцов

Сообщество Overcoder

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

isimmons opened this issue

Feb 12, 2014

· 15 comments

Comments

@isimmons

Not sure if I am doing something wrong here. Just testing the commit task at this point.

In a new project I do git init and git add . in the cli. git status shows files ready to be commited.

So I run gulp commit and get the following errors

λ gulp commit
[gulp] Using file C:Userslotusprojectsgulpjscsgulpfile.js
[gulp] Working directory changed to C:Userslotusprojectsgulpjscs
[gulp] Running 'commit'...
[gulp] Finished 'commit' in 4.79 ms
[gulp] { [Error: Command failed: error: pathspec 'commit'' did not match any file(s) known to git.
] killed: false, code: 1, signal: null }
[gulp]  error: pathspec 'commit'' did not match any file(s) known to git.

[gulp] { [Error: Command failed: error: pathspec 'commit'' did not match any file(s) known to git.
] killed: false, code: 1, signal: null }
[gulp]  error: pathspec 'commit'' did not match any file(s) known to git.

[gulp] { [Error: Command failed: error: pathspec 'commit'' did not match any file(s) known to git.
error: pathspec 'node_modules' did not match any file(s) known to git.
] killed: false, code: 1, signal: null }
[gulp]  error: pathspec 'commit'' did not match any file(s) known to git.
error: pathspec 'node_modules' did not match any file(s) known to git.

[gulp] { [Error: Command failed: error: pathspec 'commit'' did not match any file(s) known to git.
] killed: false, code: 1, signal: null }
[gulp]  error: pathspec 'commit'' did not match any file(s) known to git.

Here is the task

// Run git commit
gulp.task('commit', function(){
    gulp.src('./*')
        .pipe(git.commit('initial commit'));
});

This is on Windows in case that has anything to do with it.

@stevelacy

Can you enter the node_modules/gulp-git/lib and edit commit.js with the following?

Right directly under line 12:

 var cmd = "git commit -m " + escape([message, file.path]) + " " + opt.args;

Add this:

And post the results from the gulp log here?
It may be the UNIX vs win characters escaped in shell-escape

@isimmons

Was just doing that :-)

The result is

git commit -m 'initial commit' C:Userslotusprojectsgulpjscsgulpfile.js

Copy/pasting that in the cli gives me the same message but it works if I use double quotes around the message

git commit -m "initial commit" C:Userslotusprojectsgulpjscsgulpfile.js

@stevelacy

Ah yes!
I now remember that the time (only time ;) ) I was using git on windows I Needed to use the double quotes.
I will need to manually add that in instead of using shell-escape, I hope to get it done shortly.
Thanks for noticing it.

@isimmons

Thanks. And thanks for your work already building this.

@stevelacy

Can you check to see if my latest publish fixed it?

@stevelacy

@isimmons

So sorry I got off doing other things and didn’t realize you had replied back. Yes I will definitely check it in the morning.

@isimmons

Not working for me. Something with the file.cwd now. I added a console.log( cmd, file.cwd); at line 13 in commit.js . Here is what I get.

λ gulp commit
[gulp] Using file C:Userslotusprojectsgulpgittestgulpfile.js
[gulp] Working directory changed to C:Userslotusprojectsgulpgittest
[gulp] Running 'commit'...
[gulp] Finished 'commit' in 4.7 ms
git commit -m "initial commit" $'C:\Users\lotus\projects\repo\anothertest.txt'  C:Userslotusprojectsgulpgittest
git commit -m "initial commit" $'C:\Users\lotus\projects\repo\testfile.txt'  C:Userslotusprojectsgulpgittest
[gulp] { [Error: Command failed: fatal: Not a git repository (or any of the parent directories): .git
] killed: false, code: 128, signal: null }
[gulp]  fatal: Not a git repository (or any of the parent directories): .git

[gulp] { [Error: Command failed: fatal: Not a git repository (or any of the parent directories): .git
] killed: false, code: 128, signal: null }
[gulp]  fatal: Not a git repository (or any of the parent directories): .git

Here’s the task

gulp.task('commit', function() {
    gulp.src('../repo/*')
        .pipe(git.commit('initial commit', {}));
});

@stevelacy

Did you run git init in the other dir, or this one?

Windows may only allow in path git. Such as the git folder in local ./

@isimmons

I made a directory ‘repo’ next to ‘gulpgittest’

Then in repo

git init
touch testfile.txt
git add .
git commit -m "manually running git commands'

git repo is initialized and testfile.txt added and commited correctly

Then

touch anothertestfile.txt
git add .
git status //shows file added and ready for commit
cd ../gulpgittest
gulp commit

Am I misunderstanding? I’m thinking file.cwd should be

C:Userslotusprojectsrepo

But instead it is the same directory the gulpfile is running from (same as cwd)

C:Userslotusprojectsgulpgittest

@isimmons

If I initialize a git repo inside gulpgittest it tells me the file is outside the repo so it is trying to run git commit in the local ./

I may be misunderstanding the purpose of this plugin. Is it intended to be inside the actual repo? I was thinking I could use it to run git commands on another directory. That way I could copy files from this directory to a separate repo and then run the git commands on that repo without leaving this directory. That way it can be used as part of a deploy process where the actual repo is outside the project.

@stevelacy

I will look into the issue, it is designed to allow any folder and look for git from that files cwd, not just the local.
Unless I need to monkey patch it for windows…

@isimmons

Ok, I’ll keep messing around with it and let you know if I figure out anything. Thanks

@stevelacy

Can you confirm that #7 works for you?

@stevelacy

2 participants

@isimmons

@stevelacy

John Horner

John Horner

Posted on Mar 9, 2019

• Updated on Mar 24, 2019

I recently had to get back an earlier version of a specific file from a git repo.

This is simple as far as git is concerned:

git checkout <commit id> <filename>

so if you want to get back the version of file.txt that you had back in commit f6b01b3 you would do

git checkout f6b01b3 file.txt

and that’s what you’d get.

But when I did it, I got this:

error: pathspec 'file.txt' did not match any file(s) known to git

and it took quite a while to figure out what was wrong.

What had happened is, a folder in the structure above file.txt had been renamed.

Here’s how to reproduce what happened. Let’s create a git repo and a file, inside a folder:

john$ git init
Initialized empty Git repository in /Users/john/Library/Scripts/gitexample/.git/
john$ mkdir originalfolder
john$ cd originalfolder/

We make a file, add and commit it. All good.

john$ echo "this is the initial file" > file.txt
john$ git add file.txt 
john$ git commit file.txt -m "initial"
[master (root-commit) f6b01b3] initial
 1 file changed, 1 insertion(+)
 create mode 100644 originalfolder/file.txt

so now, we changed our mind about the name of the folder, we’ll rename it (and please note, this is git mv not just mv):

john$ cd ../
john$ git mv originalfolder/ changedfolder
john$ cd changedfolder/
john$ echo "now I've added a line" >> file.txt

we’ll commit this new version of the file:

john$ git commit file.txt -m "second"
[master ab9595b] second
 1 file changed, 2 insertions(+)
 create mode 100644 changedfolder/file.txt

no problems there.

Now we want to get back the version of file.txt from the original commit.

john$ git checkout f6b01b3 file.txt 
error: pathspec 'file.txt' did not match any file(s) known to git

git now says it’s got a pathspec error and it can’t find file.txt, which is right there

Obviously, what’s wrong is that when commit f6b01b3 was made, it was in a folder, and that folder no longer exists.

If you want that file back, you’ll need to get it back at the original path:

john$ mkdir ../originalfolder
john$ mkdir cd ../originalfolder/
john$ git checkout f6b01b3 file.txt 

this goes through with no problem.

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.

14 Answers

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".

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.

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"

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.

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.

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.

Please take note that in windows, it is very important that the git commit -m "initial commit" has the initial commit texts in double quotes. Single quotes will throw a path spec error.

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

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

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.

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

The order line contentions are isolated by space. On the off chance that you need furnish a contention with a space in it, you should cite it. So use git commit - m "Initial commit".
must follow this syntax.

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!

Please try adding the double quotes *

git commit -m «initial commit»

*This will solve your problem.

Scenarios that emerge

In the local init, a repository is created, and then a develop ment branch is created, on which file operations are performed, followed by changes made by commit.

$ git init
Initialized empty Git repository in D:/practice/testBranch/.git/
$ git checkout -b develop
Switched to a new branch 'develop'
$ vim a.txt
$ git add a.txt
$ git commit -m "add a new file"
[develop (root-commit) f9ac3b8] add a new file
 1 file changed, 1 insertion(+)
 create mode 100644 a.txt

Then you cut to the master branch and do the file operation. Then the following mistakes will occur:

$ git checkout master
error: pathspec 'master' did not match any file(s) known to git.

Reasons for the problem

Command parsing

The git init command creates a master branch by default and points the HEAD (which is a special pointer to the current local branch) to that branch. Nevertheless, you can’t see any branches when you view local and remote branches through the GIT branch-a command.
The git checkout master command actually does two things: one is to make HEAD refer back to the master branch; the other is to restore the working directory to the snapshot content that the master branch refers to.

problem analysis

After HEAD refers back to the master branch, it is necessary to restore the working directory to the content that the master branch refers to. But since you’ve been working on the develop ment branch since the beginning, the working directory corresponding to the master branch is equivalent to nothing, so that no files can be matched.

How to solve

You just need to initialize a repository, first do some commit operations on the master branch, such as adding a README.md file, so that you really create a master branch. For example:

$ git init
Reinitialized existing Git repository in D:/practice/testBranch/.git/
$ vim README.md
$ git add README.md
warning: LF will be replaced by CRLF in README.md.
The file will have its original line endings in your working directory.
$ git commit -m "add a new file"
[master (root-commit) 0e8c7c3] add a new file
 1 file changed, 1 insertion(+)
 create mode 100644 README.md
$ git push
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'master' on GitHub by visiting:
remote:      https://github.com/benben/testBranch/pull/new/master
remote:
To github.com:benben/testBranch.git
 * [new branch]      master -> master

When push ing, you can see the prompt to create a master branch in the remote warehouse, and the local master branch points to the remote master branch.
Then you can see all local and remote branches through git branch-a. Then you can create other branches and switch between master branches at will.

$ git branch -a
* master
  remotes/origin/master

When switching branches, be aware that the files in your working directory will be changed. If you switch to an older branch, your working directory will be restored to what it looked like when it was last submitted. If Git can’t do this cleanly, it will prohibit branch switching.

Понравилась статья? Поделить с друзьями:
  • Error pathspec homework did not match any file s known to git
  • Error pathspec did not match any file s known to git что делать
  • Error pathspec develop did not match any file s known to git
  • Error pathspec dev did not match any file s known to git
  • Error pathspec changed did not match any file s known to git