Error bad index file sha1 signature fatal index file corrupt

After git init, I added and committed a few files, made some changes, added and committed. Set up the git daemon (running under Cygwin on WinXP) and cloned the repository once. Now, I get this error

After git init, I added and committed a few files, made some changes, added and committed. Set up the git daemon (running under Cygwin on WinXP) and cloned the repository once.
Now, I get this error with the cloned repository:

$ git status
error: bad index file sha1 signature
fatal: index file corrupt

Is there any way to fix this, other than getting a new copy of the repository?

Simon East's user avatar

Simon East

54k17 gold badges138 silver badges132 bronze badges

asked Jul 12, 2009 at 11:23

Number8's user avatar

1

If the problem is with the index as the staging area for commits (i.e. .git/index), you can simply remove the index (make a backup copy if you want), and then restore index to version in the last commit:

On OSX/Linux/Windows(With Git bash):

rm -f .git/index
git reset

On Windows (with CMD and not git bash):

del .gitindex
git reset

(The reset command above is the same as git reset --mixed HEAD)

You can alternatively use lower level plumbing git read-tree instead of git reset.


If the problem is with index for packfile, you can recover it using git index-pack.

Community's user avatar

answered Jul 12, 2009 at 12:28

Jakub Narębski's user avatar

Jakub NarębskiJakub Narębski

301k65 gold badges219 silver badges230 bronze badges

21

You may have accidentally corrupted the .git/index file with a sed on your project root (refactoring perhaps?) with something like:

sed -ri -e "s/$SEACHPATTERN/$REPLACEMENTTEXT/g" $(grep -Elr "$SEARCHPATERN" "$PROJECTROOT")

to avoid this in the future, just ignore binary files with your grep/sed:

sed -ri -e "s/$SEACHPATTERN/$REPLACEMENTTEXT/g" $(grep -Elr --binary-files=without-match "$SEARCHPATERN" "$PROJECTROOT")

answered Mar 19, 2011 at 7:57

hobs's user avatar

hobshobs

17.8k10 gold badges78 silver badges100 bronze badges

5

I had that problem, and I try ti fix with this:

rm -f .git/index
git reset

BUT it did not work. The solution?
For some reason I had others .git folders in sub directories. I delete those .git folders (not the principal) and git reset again. Once they were deleted, everything worked again.

answered Jul 24, 2015 at 13:23

Cleiton Almeida's user avatar

3

This sounds like a bad clone. You could try the following to get (possibly?) more information:

git fsck --full

answered Jul 12, 2009 at 11:36

Gav's user avatar

GavGav

10.8k7 gold badges32 silver badges35 bronze badges

Since the above solutions left me with continued problems, I used this dull solution:

  1. clone a new copy of the repo elsewhere
  2. copy the fresh .git directory into the (broken) repo that contained the changes I wanted to commit

Did the trick. Btw, I did a sed on the project root as @hobs guessed. Learned my lesson.

answered Feb 10, 2017 at 22:18

eskimwier's user avatar

eskimwiereskimwier

99712 silver badges16 bronze badges

2

This worked for me. Although i’m curious of the reason I started getting the errors in the first place. When I logged out yesterday, it was fine. Log in this morning, it wasn’t.

rm .git/index

git reset

DimaSan's user avatar

DimaSan

12k11 gold badges66 silver badges75 bronze badges

answered Aug 5, 2016 at 12:32

Eighty's user avatar

EightyEighty

1091 silver badge3 bronze badges

2

Note for git submodule users — the solutions here will not work for you as-is.

Let’s say you have a parent repository called dev, for example, and your submodule repository is called api.

if you are inside of api and you get the error mentioned in this question:

error: bad index file sha1 signature
fatal: index file corrupt

The index file will NOT be inside of a .git folder. In fact, the .git won’t even be a folder — it will will be a text document with the location of the real .git data for this repository. Likely something like this:

~/dev/api $ cat .git
gitdir: ../.git/modules/api

So, instead of rm -f .git/index, you will need to do this:

rm -f ../.git/modules/api/index
git reset

or, more generally,

rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index
git reset

answered Feb 12, 2018 at 20:19

jenming's user avatar

jenmingjenming

8097 silver badges8 bronze badges

This issue can occur when there is a .git directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.

Eric Leschinski's user avatar

answered May 31, 2016 at 19:48

Nick Kuijpers's user avatar

1

None of the existing answers worked for me.

I was using worktrees, so there is no .git folder.

You’ll need to go back to your main repo. Inside that, delete .git/worktrees/<name_of_tree>/index

Then run git reset as per other answers.

answered Sep 29, 2020 at 8:06

Ash's user avatar

AshAsh

1,9161 gold badge14 silver badges15 bronze badges

Cloning remote repo and replacing the .git folder from it to problematic local directory solved the issue.

answered Feb 17, 2022 at 13:14

Moein Qureshi's user avatar

A repo may seem corrupted if you mix different git versions.

Local repositories touched by new git versions aren’t backwards-compatible with old git versions. New git repos look corrupted to old git versions (in my case git 2.28 broke repo for git 2.11).

Updating old git version may solve the problem.

answered Oct 16, 2020 at 16:41

Kornel's user avatar

KornelKornel

96.5k34 gold badges218 silver badges303 bronze badges

On Windows PowerShell, it should be

rm -Force .git/index
git reset

answered Sep 4, 2022 at 2:21

ishandutta2007's user avatar

ishandutta2007ishandutta2007

16k16 gold badges89 silver badges123 bronze badges

I committed my changes and suddenly my laptop went off due to battery issue and then I got this fatal index corrupt error and Desktop github couldn’t locate this git repo. So I ran below mentioned commands using git-bash and everything went back fine.

rm -f .git/index
git reset

answered Oct 29, 2022 at 18:03

Ahsan Khan's user avatar

Ahsan KhanAhsan Khan

5717 silver badges12 bronze badges

I had the same error and attempted to fix it as described in the accepted answer. However, immediately after resetting my index in .git/index it became corrupted again.

The problem was, that I was using git bisect yesterday to find a bug, but forgot to run git bisect reset to clean up afterwards at the end of the day. Today as I started making changes git got confused, as it was still in bisect mode and I was attempting to apply changes. I also couldn’t just run git bisect reset, because there were already changes.

To fix this problem run the following in the git bash in your root directory:

git stash -m <message>
git bisect reset        # You are now most likely in detached head mode
git checkout <branch>
git stash apply         # If you have multiple stashes, make sure 
                          to apply the correct one

Note that there is no need to remove .git/index and reset the index in this case!

answered Nov 1, 2022 at 11:10

Liqs's user avatar

LiqsLiqs

979 bronze badges

I did a simple trick. I clone the repo to a new folder. Copied the .git folder from the new folder to repo’s old folder, replacing .git there.

answered Mar 1, 2020 at 5:32

Astra Uvarova - Saturn's star's user avatar

4

FelixSFD's user avatar

FelixSFD

5,94210 gold badges46 silver badges115 bronze badges

answered Nov 18, 2017 at 16:18

Christopher Shaw's user avatar

1

You can also try for restore to previous version of the file (if you are using windows os)

answered May 2, 2014 at 12:07

Shyamsundar's user avatar

1

Содержание

  1. [Solved-5 Solutions] How to resolve “Error: bad index Fatal: index file corrupt” when using Git
  2. Error Description :
  3. Solution 1:
  4. Solution 2:
  5. Solution 3:
  6. Solution 4:
  7. Solution 5:
  8. Related Searches to How to resolve “Error: bad index – Fatal: index file corrupt” when using Git
  9. Как решить проблему «Ошибка: неверный индекс — Неустранимый: файл индекса поврежден» при использовании Git
  10. 14 ответы
  11. Laravel: error on «composer update» command #5629
  12. Comments
  13. Footer
  14. Laravel: error on «composer update» command #5629
  15. Comments
  16. Footer
  17. git bad signature index file corrupt #648
  18. Comments

[Solved-5 Solutions] How to resolve “Error: bad index Fatal: index file corrupt” when using Git

Error Description :

  • After git init, if we add and commit a few files, make some changes, add and committed. Set up the git daemon (running under Cygwin on WinXP) and clone the repository once, We get this error with the cloned repository:
click below button to copy the code. By Git tutorial team
  • Is there any way to fix this, other than getting a new copy of the repository?

Solution 1:

  • If the problem is with the index as the staging area for commits (i.e. .git/index ), we can simply remove the index (make a backup copy if we want), and then restore index to version in the last commit:
  • On OSX/Linux:
click below button to copy the code. By Git tutorial team
click below button to copy the code. By Git tutorial team
  • (The reset command above is the same as git reset —mixed HEAD )
  • We can alternatively use lower level plumbing git read-tree instead of git reset.
  • If the problem is with index for packfile you can recover it using git index-pack .

Solution 2:

  • We could try the following to get (possibly?) more information:
click below button to copy the code. By Git tutorial team

Solution 3:

  • This issue can occur when there is a .git directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.

Solution 4:

  • Clone a new copy of the repo elsewhere
  • Copy the fresh .git directory into the (broken) repo that contained the changes I wanted to commit

Solution 5:

click below button to copy the code. By Git tutorial team

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

Как решить проблему «Ошибка: неверный индекс — Неустранимый: файл индекса поврежден» при использовании Git

После git init , Я добавил и зафиксировал несколько файлов, внес некоторые изменения, добавил и зафиксировал. Настройте демон git (работающий под Cygwin на WinXP) и один раз клонируйте репозиторий. Теперь я получаю эту ошибку с клонированным репозиторием:

Есть ли способ исправить это, кроме получения новой копии репозитория?

задан 12 июля ’09, 08:07

Это в клонированном репозитории или в исходном репозитории? Выдала ли команда clone какие-либо ошибки? — CB Bailey

14 ответы

Если проблема связана с индексом как область подготовки коммитов (т.е. .git/index ), вы можете просто удалить индекс (сделать резервную копию, если хотите), а затем восстановить индекс до версии в последней фиксации:

( reset команда выше такая же, как git reset —mixed HEAD )

Вы также можете использовать более низкий уровень водопровод git read-tree вместо git reset .

Если проблема в индекс для пакетный файл, вы можете восстановить его, используя git index-pack .

Я случайно сделал :w! в :Gstatus (из fugitive.vim). Этот ответ избавил меня от необходимости тянуть за волосы. — Лоуренс Гонсалвес

Я знаю, что нам не нравятся сообщения «мне тоже» — но «мне тоже». Эквивалент в Windows erase /s .gitindex , Мне нужен был erase .gitindex.lock тоже. — Джереми МакГи

Привет, у меня была такая же проблема с поиском и заменой, но git reset сообщает мне, что в .git / objects / pack / есть два файла пакета, к которым нет доступа. У тебя есть идея? — эпсилоны

не было бы безопаснее использовать git reset —keep вместо? в Шпаргалка по Tower Git это объясняется как: Сбросьте указатель HEAD на предыдущую фиксацию и сохраните незафиксированные локальные изменения — Петр

Когда я писал этот ответ, его не существовало . Во всяком случае git reset —keep более безопасная форма git reset —hard ; git reset —mixed вообще не трогает рабочий каталог. — Якуб Наребски

Возможно, вы случайно повредили файл .git / index с помощью sed в корне вашего проекта (возможно, рефакторинг?), Например:

чтобы избежать этого в будущем, просто игнорируйте двоичные файлы с помощью grep / sed:

ответ дан 19 мар ’11, в 07:03

Если вы не против потерять изменения в .git/index , вы всегда можете удалить его и создать заново с помощью git reset (без —hard !). — Якуб Наребски

Я сломал его с помощью # find ./ -type f -exec sed -i ‘s / Politician / Legislator / g’ <> ; Выполнение того, что рекомендует этот ответ, в первую очередь не сломало бы его, но принятый ответ устранил ущерб, который я нанес. Но это отличная профилактика. — Райан Мортенсен

@RyanMortensen Вы можете попробовать инвертировать sed с чем-то вроде find .git/ -type f -exec sed -i ‘s/Legislator/Politician/g’ <> ; Это может помочь, если ваш .git/ настолько испорчен, что git reset не сработает. Или, может быть, вы хотите восстановить существующие .git/index не удаляя его. Конечно, это не удастся, если в вашем исходном коде или указателе уже есть некоторые «законодатели». — варочные панели

Спасибо @hobs, вы избавили меня от многих проблем — я решил это инвертированием sed заменив мой new_string с моим old_string ! — цвети_ико

Я реорганизовал весь свой проект вместо папки src в IntelliJ и столкнулся с этой проблемой. Это объясняет, почему у меня были такие странные ошибки! — Майкл

У меня была эта проблема, и я пытаюсь ее исправить:

НО это не сработало. решение? По какой-то причине у меня были другие папки .git в подкаталогах. Я удаляю эти папки .git (не основные) и git reset очередной раз. Как только они были удалены, все снова заработало.

Создан 24 июля ’15, 14:07

Этот ответ действительно решает проблему, если у вас есть папки .git в vendor / (ex) — АльСан

Звучит как плохой клон. Вы можете попробовать следующее, чтобы получить (возможно?) Больше информации:

Создан 12 июля ’09, 12:07

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

  1. клонировать новую копию репо в другом месте
  2. скопируйте свежий каталог .git в (сломанный) репо, содержащий изменения, которые я хотел зафиксировать

Сделал свое дело. Кстати, я сделал sed в корне проекта, как догадался @hobs. Усвоил урок.

Это не очень хорошо, если вы были в середине слияния, создали ветки или выполнили какие-либо коммиты с момента клонирования, или любой из ряда других сценариев . Клонирование новой копии репо вряд ли является решением, и я осмелюсь предположить это попахивает нетерпением (лучше оставить в крайнем случае). Гораздо лучше действительно диагностировать, что происходит, и восстановить индекс существующего репо — обычно это относительно легко сделать. Иногда вы можете просто переименовать индексный файл (или удалить его, если вы уверены, что он вам больше не понадобится) и позволить Git создать новый (используя git-reset или git-checkout) .. — Джазимов

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

ответ дан 27 окт ’16, 09:10

Это сработало для меня, хотя он удалил все добавленные файлы из git. Мне пришлось запустить git add для этих файлов — Шамсул Арефин Саджиб

Примечание для пользователей подмодуля git — решения здесь не будут работать для вас как есть.

Допустим, у вас есть родительский репозиторий с именем dev , например, и ваш репозиторий подмодулей называется api .

если ты внутри api и вы получите ошибку, упомянутую в этом вопросе:

error: bad index file sha1 signature fatal: index file corrupt

Компания index файл НЕ будет внутри .git папка. Фактически, .git даже не будет папкой — это будет текстовый документ с местонахождением реальных данных .git для этого репозитория. Скорее всего что-то вроде этого:

/dev/api $ cat .git gitdir: ../.git/modules/api

Итак, вместо rm -f .git/index , вам нужно будет сделать это:

rm -f ../.git/modules/api/index git reset

или, в более общем плане,

rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index git reset

Источник

Laravel: error on «composer update» command #5629

Hi,
I am not able to do a «composer update» command on Laravel 5, cause I get this error:

I guess it does not depends on package, cause I already got the same error message on another package before this error.

Anyone knows why its happening?

The text was updated successfully, but these errors were encountered:

Sounds like the vendor/guzzlehttp/promises/.git/index file is corrupt. I would just delete and re-install all the packages:

(If it’s happening on multiple packages, corrupted files could be a symptom of another problem — I’ve had that happen on a hard drive that was failing, for example.)

@davejamesmiller composer update is overkill — composer install will also work fine from the lock and be 100 times faster to just restore a working situation.

As for the underlying cause — I’ve seen this happen a few times when shutting down my Ubuntu dev VM aggressively. Git is quite error sensitive, although you can also just repair it by cloning the repo elsewhere and copying the .git folder back in.

@curry684 I only said composer update because that’s the command that @giacomok was attempting to run in the first place. Though it would be possible to do first an install then an update I suppose, I don’t know if that would make the update any faster.

Thanks both for your reply, I find out what was the problem.
Indeed the index file of some packages was corrupted, so I deleted the «.git» folder of all packages and «composer update» worked fine.

P.S. I tried (before this solution) to remove the «vendor» folder, but I got an error cause in the «vendor» folder there is «autoload.php» that needs to «composer update» command.

© 2023 GitHub, Inc.

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.

Источник

Laravel: error on «composer update» command #5629

Hi,
I am not able to do a «composer update» command on Laravel 5, cause I get this error:

I guess it does not depends on package, cause I already got the same error message on another package before this error.

Anyone knows why its happening?

The text was updated successfully, but these errors were encountered:

Sounds like the vendor/guzzlehttp/promises/.git/index file is corrupt. I would just delete and re-install all the packages:

(If it’s happening on multiple packages, corrupted files could be a symptom of another problem — I’ve had that happen on a hard drive that was failing, for example.)

@davejamesmiller composer update is overkill — composer install will also work fine from the lock and be 100 times faster to just restore a working situation.

As for the underlying cause — I’ve seen this happen a few times when shutting down my Ubuntu dev VM aggressively. Git is quite error sensitive, although you can also just repair it by cloning the repo elsewhere and copying the .git folder back in.

@curry684 I only said composer update because that’s the command that @giacomok was attempting to run in the first place. Though it would be possible to do first an install then an update I suppose, I don’t know if that would make the update any faster.

Thanks both for your reply, I find out what was the problem.
Indeed the index file of some packages was corrupted, so I deleted the «.git» folder of all packages and «composer update» worked fine.

P.S. I tried (before this solution) to remove the «vendor» folder, but I got an error cause in the «vendor» folder there is «autoload.php» that needs to «composer update» command.

© 2023 GitHub, Inc.

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.

Источник

git bad signature index file corrupt #648

Often vim-fugitive corrupts my git index. This happens when I call Gstatus and then I add the same file more the one with — . Any one else has this problem?

The text was updated successfully, but these errors were encountered:

Next time it happens take a look inside the index file and see if the contents of the :Gstatus window have overwritten it.

@giuse88 @tpope not sure if this is related, but on the latest version of vim-fugative after I wq to save a commit I get this error: and then this shows up .

If I use vim to check .git/index I see:
using nano I see:

Sounds like an issue with whatever this «BufSurf» plugin is.

On Thu, Jun 25, 2015 at 10:54 AM cj notifications@github.com wrote:


Reply to this email directly or view it on GitHub
#648 (comment).

this is the plugin https://github.com/ton/vim-bufsurf. It only just started happening after I updated fugitive. I guess something changed that bufsurf doesn’t like.

If you can figure out the exact commit that triggered it I can further advise.

i’m having the same issue when doing Gcommit then I added a file to stage. After that, I did another Gcommit, this time with a the message and I got this error.

@tpope so I’m still having this issue. I no longer have that plugin, but after I commit I’m still getting this:

After I do a :Gwrite then :Gcommit type in my message and then :wq this buffer just pops up.

So the commit message buffer closes and then this opens in a split? That’s odd. It looks like a failed attempt to open :Gstatus , which is what happens when you call :Gcommit with no changes.

Can you check the value of :echo b:fugitive_commit_arguments before you :wq ?

Yes. Strange, there definitely was a commit with changes before I did :wq ‘d.

here’s the value: —cleanup=strip -F /home/cj/apps/acd/autolink/.git/COMMIT_EDITMSG —no-edit —no-interactive —no-signoff

While the commit message is still open, try running the following in another window:

Check for errors, and the exit status ( echo $? ).

I’ve run into this (pretty consistently). I’ve tried the troubleshooting
steps without seeing much different than reported above. That said I
think I might have found a workaround (and thus a pointer) My (less then
full perusal) of the code shows that the commit window is normally set
with bufhidden=bdelete but on commit it’s set to bwipeout . It
looks like some path allows that to get skipped. After a commit I can
still see the hidden .git/index file with ls! If I switch to the file at
that point (either directly or by invoking Gstatus) I see the garbled
binary index.

To clarify a bit:

  1. I use Gtatus. Everything is good
  2. I commit a change with Gcommit
  3. At that point I can still see the .git/index file with ls!
  4. If switch to the window, it’s garbled
  5. If I close that window and re-invoke Gstatus, it’s back to expected.

If I bwipeout the buffer directly ( :[BNUMBER]bwipeout ) then
Gstatus and cousins work fine.

The workaround (and possible clue) is that I typically use ZZ as a wq
shortcut. In after/gitcommit.vim I’ve now set a function + mapping that
calls bwipeout and the problem goes away (aka I remap ZZ)

Hoping this is useful 🙂

@cj I have the same issue with garbled text after GCommit command. Have you managed to fix it somehow?

Is anyone here who is having this issue, using vim-airline by any chance?

@yevhen-m I noticed that the issue with fugitive goes away when I uninstall vim-airline, so perhaps that plugin could be the cause of the issue but I’m not entirely sure.

I’m having the same issue… Any fix available?

Hello, I can confirm that this is related to airline. I hit this after switching to Xenial (the exact same setup was working fine on 15.10).

Here is my .vimrc file

/.vim/bundle/Vundle.vim call vundle#begin() » alternatively, pass a path where Vundle should install plugins «call vundle#begin(‘

/some/path/here’) » let Vundle manage Vundle, required Plugin ‘gmarik/Vundle.vim’ » Add all your plugins here (note older versions of Vundle used Bundle instead » of Plugin)* » Auto-Complete Bundle ‘Valloric/YouCompleteMe’ » Folding Plugin ‘tmhedberg/SimpylFold’ «Folding » Python autodindent Plugin ‘vim-scripts/indentpython.vim’ » Indent python » Syntax Plugin ‘scrooloose/syntastic’ «Syntax checker » Plugin ‘nvie/vim-flake8’ » PEP8 » Colors Plugin ‘jnurmine/Zenburn’ » Zenburn theme (console) Plugin ‘altercation/vim-colors-solarized’ «Solarized theme (GUI) Plugin ‘scrooloose/nerdtree’ «Hierarchy tree Plugin ‘kien/ctrlp.vim’ » Search files Plugin ‘vim-airline/vim-airline’ «Status bar Plugin ‘vim-airline/vim-airline-themes’ Plugin ‘tpope/vim-fugitive’ » Show git branch in status bar Plugin ‘xolox/vim-misc’ » Needed by vim-session Plugin ‘xolox/vim-session’ » Make use of mksession easier Plugin ‘saltstack/salt-vim’ » For saltstack files Plugin ‘fatih/vim-go’ » Go Plugin Plugin ‘pearofducks/ansible-vim’ » Ansible plugin Bundle ‘Rykka/riv.vim’ » All of your Plugins must be added before the following line call vundle#end() » required filetype plugin indent on » required set encoding=utf-8 » Set filetype based on name autocmd BufRead,BufNewFile *Dockerfile* setlocal filetype=dockerfile autocmd BufRead,BufNewFile *dockerfile* setlocal filetype=dockerfile autocmd BufRead,BufNewFile *.spec.in setlocal filetype=spec autocmd BufRead,BufNewFile *.functions setlocal filetype=sh autocmd BufRead,BufNewFile *.sls setlocal filetype=sls autocmd BufRead,BufNewFile *.jinja setlocal filetype=jinja «» General section set nowrap » don’t wrap lines set tabstop=4 » a tab is four spaces set backspace=indent,eol,start » allow backspacing over everything in insert mode set autoindent » always set autoindenting on set copyindent » copy the previous indentation on autoindenting set shiftwidth=4 » number of spaces to use for autoindenting set shiftround » use multiple of shiftwidth when indenting with ‘ ‘ set showmatch » set show matching parenthesis set ignorecase » ignore case when searching set smartcase » ignore case if search pattern is all lowercase, » case-sensitive otherwise set smarttab » insert tabs on the start of a line according to » shiftwidth, not tabstop set hlsearch » highlight search terms set incsearch » show search matches as you type set history=1000 » remember more commands and search history set undolevels=1000 » use many muchos levels of undo set wildignore=*.swp,*.bak,*.pyc,*.class set visualbell » don’t beep set noerrorbells » don’t beep » FX button mapping set pastetoggle= » Toggle PASTE mode » Remove trailing whitespaces :nnoremap :let _s=@/ :%s/s+$//e :let @/=_s :nohl :unlet _s set hidden » Allow leaving a buffer with unsaved changes set mouse=a » Use mouse in all mode set guioptions-=T «remove toolbar » Completion in menu bar set wildmode=longest,list,full set wildmenu «» Remap » sv sources .vimrc nnoremap sv :source $MYVIMRC :runtime! plugin/settings/* :redraw :echo $MYVIMRC ‘reloaded’ » Buffer navigation nnoremap :bp nnoremap :bn » Split navigations nnoremap l nnoremap h nnoremap k nnoremap j » Copy to system clipboard Visual selection » vnoremap y/ «* «» Folding » Enable folding set foldmethod=indent set foldlevel=99 » See the docstring when folding let g:SimpylFold_docstring_preview=1 » Autocompletion stuff let g:ycm_autoclose_preview_window_after_completion=1 map g :YcmCompleter GoToDefinitionElseDeclaration » Colors set if has(‘gui_running’) set background=dark colorscheme solarized set guifont=DejaVu Sans Mono for Powerline 9 else «colors theme configuration (console) if &term == «linux» || &term == «screen.linux» set t_Co=8 colorscheme zenburn else set t_Co=256 colorscheme zenburn endif endif «» NerdTree let NERDTreeIgnore=[‘.pyc$’, ‘

$’] «ignore files in NERDTree map :NERDTreeToggle » Close vim if only NerdTree is open autocmd bufenter * if (winnr(«$») == 1 && exists(«b:NERDTree») && b:NERDTree.isTabTree()) | q | endif » Always enable status bar set laststatus=2 » Use powerline font symbols let g:airline_powerline_fonts = 1 if !exists(‘g:airline_symbols’) let g:airline_symbols = <> endif let g:airline_symbols.space = «ua0″ » Enable the list of buffers let g:airline#extensions#tabline#enabled = 1 » Session let g:session_autosave = «prompt» let g:session_autosaveperiodic = 60 let g:session_persist_colors = 0 let g:session_persist_font = 0″>

As long as I keep the vim-airline plugin, if I edit a file, :Gwrite, :Gcommit, I end up with a window with the .git/index content like this
DIRC�������CX/�� yada yada

The title of the window being «/.git/index» [Preview]
I can just close it but it’s rather annoying

As long as I remove vim-airline plugin, this does not happen anymore

Using previous version of vim-airline has lead nowhere so far, but still checking

Источник

The following error keeps repeating even after I’ve tried the recommended:

rm .git/index
git reset

But I still get this error:

error: bad index file sha1 signature
fatal: index file corrupt
fatal: 'git status --porcelain' failed in submodule '[directory path omitted]'

What’s wrong? What should I do?

asked Nov 8, 2014 at 20:53

ina's user avatar

inaina

5174 gold badges12 silver badges21 bronze badges

4

I had that problem, and I tried to fix it with this:

rm -f .git/index
git reset

BUT it did not work. The solution?
For some reason I had other .git folders in sub directories. I delete those .git folders (not the principal) and git reset again. Once they were deleted, everything worked again.

ctzdev's user avatar

ctzdev

2,3407 gold badges29 silver badges48 bronze badges

answered Jul 24, 2015 at 13:28

Cleiton Almeida's user avatar

0

 Home > Git & Source management > How to resolve “Error: bad index – Fatal: index file corrupt” when using Git?

How to resolve “Error: bad index – Fatal: index file corrupt” when using Git?

5w33t45
January 8, 2018
Git, Source management
No Comments

From time to time you could receive error using Git like this:

$ git status
error: bad index file sha1 signature
fatal: index file corrupt

Solution

  1. Delete file “.git/index” from your project parent directory.
  2. Execute git reset command from terminal.


Post Views:
2,796

About Author

5w33t45

Leave a Reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

[Solved-5 Solutions] How to resolve “Error: bad index Fatal: index file corrupt” when using Git

Error Description :

  • After git init, if we add and commit a few files, make some changes, add and committed. Set up the git daemon (running under Cygwin on WinXP) and clone the repository once, We get this error with the cloned repository:
click below button to copy the code. By Git tutorial team
  • Is there any way to fix this, other than getting a new copy of the repository?

Solution 1:

  • If the problem is with the index as the staging area for commits (i.e. .git/index ), we can simply remove the index (make a backup copy if we want), and then restore index to version in the last commit:
  • On OSX/Linux:
click below button to copy the code. By Git tutorial team
click below button to copy the code. By Git tutorial team
  • (The reset command above is the same as git reset —mixed HEAD )
  • We can alternatively use lower level plumbing git read-tree instead of git reset.
  • If the problem is with index for packfile you can recover it using git index-pack .

Solution 2:

  • We could try the following to get (possibly?) more information:
click below button to copy the code. By Git tutorial team

Solution 3:

  • This issue can occur when there is a .git directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.

Solution 4:

  • Clone a new copy of the repo elsewhere
  • Copy the fresh .git directory into the (broken) repo that contained the changes I wanted to commit

Solution 5:

click below button to copy the code. By Git tutorial team

Related Searches to How to resolve “Error: bad index – Fatal: index file corrupt” when using Git

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

Как решить проблему «Ошибка: неверный индекс — Неустранимый: файл индекса поврежден» при использовании Git

После git init , Я добавил и зафиксировал несколько файлов, внес некоторые изменения, добавил и зафиксировал. Настройте демон git (работающий под Cygwin на WinXP) и один раз клонируйте репозиторий. Теперь я получаю эту ошибку с клонированным репозиторием:

Есть ли способ исправить это, кроме получения новой копии репозитория?

задан 12 июля ’09, 08:07

Это в клонированном репозитории или в исходном репозитории? Выдала ли команда clone какие-либо ошибки? — CB Bailey

14 ответы

Если проблема связана с индексом как область подготовки коммитов (т.е. .git/index ), вы можете просто удалить индекс (сделать резервную копию, если хотите), а затем восстановить индекс до версии в последней фиксации:

( reset команда выше такая же, как git reset —mixed HEAD )

Вы также можете использовать более низкий уровень водопровод git read-tree вместо git reset .

Если проблема в индекс для пакетный файл, вы можете восстановить его, используя git index-pack .

Я случайно сделал :w! в :Gstatus (из fugitive.vim). Этот ответ избавил меня от необходимости тянуть за волосы. — Лоуренс Гонсалвес

Я знаю, что нам не нравятся сообщения «мне тоже» — но «мне тоже». Эквивалент в Windows erase /s .gitindex , Мне нужен был erase .gitindex.lock тоже. — Джереми МакГи

Привет, у меня была такая же проблема с поиском и заменой, но git reset сообщает мне, что в .git / objects / pack / есть два файла пакета, к которым нет доступа. У тебя есть идея? — эпсилоны

не было бы безопаснее использовать git reset —keep вместо? в Шпаргалка по Tower Git это объясняется как: Сбросьте указатель HEAD на предыдущую фиксацию и сохраните незафиксированные локальные изменения — Петр

Когда я писал этот ответ, его не существовало . Во всяком случае git reset —keep более безопасная форма git reset —hard ; git reset —mixed вообще не трогает рабочий каталог. — Якуб Наребски

Возможно, вы случайно повредили файл .git / index с помощью sed в корне вашего проекта (возможно, рефакторинг?), Например:

чтобы избежать этого в будущем, просто игнорируйте двоичные файлы с помощью grep / sed:

ответ дан 19 мар ’11, в 07:03

Если вы не против потерять изменения в .git/index , вы всегда можете удалить его и создать заново с помощью git reset (без —hard !). — Якуб Наребски

Я сломал его с помощью # find ./ -type f -exec sed -i ‘s / Politician / Legislator / g’ <> ; Выполнение того, что рекомендует этот ответ, в первую очередь не сломало бы его, но принятый ответ устранил ущерб, который я нанес. Но это отличная профилактика. — Райан Мортенсен

@RyanMortensen Вы можете попробовать инвертировать sed с чем-то вроде find .git/ -type f -exec sed -i ‘s/Legislator/Politician/g’ <> ; Это может помочь, если ваш .git/ настолько испорчен, что git reset не сработает. Или, может быть, вы хотите восстановить существующие .git/index не удаляя его. Конечно, это не удастся, если в вашем исходном коде или указателе уже есть некоторые «законодатели». — варочные панели

Спасибо @hobs, вы избавили меня от многих проблем — я решил это инвертированием sed заменив мой new_string с моим old_string ! — цвети_ико

Я реорганизовал весь свой проект вместо папки src в IntelliJ и столкнулся с этой проблемой. Это объясняет, почему у меня были такие странные ошибки! — Майкл

У меня была эта проблема, и я пытаюсь ее исправить:

НО это не сработало. решение? По какой-то причине у меня были другие папки .git в подкаталогах. Я удаляю эти папки .git (не основные) и git reset очередной раз. Как только они были удалены, все снова заработало.

Создан 24 июля ’15, 14:07

Этот ответ действительно решает проблему, если у вас есть папки .git в vendor / (ex) — АльСан

Звучит как плохой клон. Вы можете попробовать следующее, чтобы получить (возможно?) Больше информации:

Создан 12 июля ’09, 12:07

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

  1. клонировать новую копию репо в другом месте
  2. скопируйте свежий каталог .git в (сломанный) репо, содержащий изменения, которые я хотел зафиксировать

Сделал свое дело. Кстати, я сделал sed в корне проекта, как догадался @hobs. Усвоил урок.

Это не очень хорошо, если вы были в середине слияния, создали ветки или выполнили какие-либо коммиты с момента клонирования, или любой из ряда других сценариев . Клонирование новой копии репо вряд ли является решением, и я осмелюсь предположить это попахивает нетерпением (лучше оставить в крайнем случае). Гораздо лучше действительно диагностировать, что происходит, и восстановить индекс существующего репо — обычно это относительно легко сделать. Иногда вы можете просто переименовать индексный файл (или удалить его, если вы уверены, что он вам больше не понадобится) и позволить Git создать новый (используя git-reset или git-checkout) .. — Джазимов

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

ответ дан 27 окт ’16, 09:10

Это сработало для меня, хотя он удалил все добавленные файлы из git. Мне пришлось запустить git add для этих файлов — Шамсул Арефин Саджиб

Примечание для пользователей подмодуля git — решения здесь не будут работать для вас как есть.

Допустим, у вас есть родительский репозиторий с именем dev , например, и ваш репозиторий подмодулей называется api .

если ты внутри api и вы получите ошибку, упомянутую в этом вопросе:

error: bad index file sha1 signature fatal: index file corrupt

Компания index файл НЕ будет внутри .git папка. Фактически, .git даже не будет папкой — это будет текстовый документ с местонахождением реальных данных .git для этого репозитория. Скорее всего что-то вроде этого:

/dev/api $ cat .git gitdir: ../.git/modules/api

Итак, вместо rm -f .git/index , вам нужно будет сделать это:

rm -f ../.git/modules/api/index git reset

или, в более общем плане,

rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index git reset

Источник

Git: Understanding the Index File

Git index file (.git/index) is a binary file having the following format: a 12-byte header, a number of sorted index entries, extensions, and a SHA-1 checksum. Now let’s create a new Git repository.

Today, I want to share with you what is Git Index. The index is a binary file (generally kept in .git/index ) containing a sorted list of path names, each with permissions and the SHA1 of a blob object; git ls-files can show you the contents of the index. Please note that words index, stage, and cache are the same thing in Git: they are used interchangeably. I’m using macOS for the examples in this post.

This blog post will go through the following steps:

0. Prerequisites

Create a project app and initialize as Git project. Then, create a readme file and add it to index.

1. Understand Index via git-ls-files

Now, see the indexed files using git-ls-files tool:

The flag —stage shows staged contents’ mode bits, object name and stage number in the output. So in our case, the output means:

  • The read-me file mode bits are 100644, a regular non-executable file.
  • The SHA-1 value of blob README.md
  • The stage number (slots), useful during merge conflict handling.
  • The object name.

Mode bits, the 6 digits, is the octal notation of the file permission. It can also be read in binary form. Mode bits 100644 ( 0b1000000110100100 ) means this file is a regular file, readable and writable by owner of the file, readable by other users in the owner group, and readable by others. Part (a) is a 4-bit object type, valid values in binary are 1000 (regular file), 1010 (symbolic link) and 1110 (gitlink); Part (b) is 3-bit unused; Part (c) is 9-bit unix permission. Only 0755 and 0644 are valid for regular files. Symbolic links and gitlinks have value 0 in this field. These notions are defined in Git index-format.txt.

The different stage numbers are not really used during git-add command. They are used for handling merge conflicts. In a nutshell:

  • Slot 0: “normal”, un-conflicted, all-is-well entry.
  • Slot 1: “base”, the common ancestor version.
  • Slot 2: “ours”, the target (HEAD) version.
  • Slot 3: “theirs”, the being-merged-in version.

2. Inside .git/index

Now, let’s make a bits (binary digits) dump for the Git index file .git/index :

or a hex dump version:

The index file contains several information:

  1. A 12-byte header.
  2. A number of sorted index entries.
  3. Extensions. They are identified by signature.
  4. 160-bit SHA-1 over the content of the index file before this checksum.

2.1. Header

As you can see, the index starts with a 12-byte header:

A 12-byte header consisting of a 4-byte signature “DIRC” ( 0x44495243 ) standing for DirCache; 4-byte version number “2” ( 0x00000002 ), which is the current version of Git index format; 32-bit number of index entries “1” ( 0x00000001 ).

2.2. Index Entry

Before going further, we also need the statistic data about README.md:

In this index entry for README.md, it consists:

64-bit ctime

32-bit ctime seconds, the last time a file’s metadata changed; and 32-bit ctime nanosecond fractions. Here it means “2018-04-28T10:04:48” ( 0x5AE42B20 ). According to the HFS+ volume format spec, it only stores timestamps to a granularity of one second. In other words, the nanosecond fractions is unused.

64-bit mtime

32-bit mtime seconds, the last time a file’s data changed; and 32-bit mtime nanosecond fractions. Here it means “2018-04-28T10:04:48” ( 0x5ae42b20 ). According to the HFS+ volume format spec, it only stores timestamps to a granularity of one second. In other words, the nanosecond fractions is unused.

32-bit dev

The device ( 16777221 ) upon which file README.md resides.

32-bit ino

The file inode number ( 8596164404 ). The overflowed part seems to be truncated.

32-bit mode

The hexadecimal representation of file permission 100644 (octal).

32-bit uid

The user identifier of the current user. The mine is 501 ( 0x1F5 ):

32-bit gid

The group identifier of the current user. The mine is 20 ( 0x14 ):

32-bit file size

The file size is 12 bytes ( 0xC ).

160-bit SHA-1 Object ID

A 20-byte (160-bit) SHA-1 over the content of the index file before this checksum. This is the blob id of the README.md file—we’ve seen it previously via git-ls-files command, do you remember?

A 16-bit ‘flags’ field split into (high to low bits)

1-bit assume-valid flag ( false ); 1-bit extended flag (must be zero in version 2); 2-bit stage (during merge); 12-bit name length if the length is less than 0xFFF , otherwise 0xFFF is stored in this field. The value is 9 in decimal, or 0x9 .

(Version 3 or later)… Ignore, we are in version 2.

File Path (length=9+1)

The index entry path name relative to top level directory (without leading slash). Here, it’s value is “README.md” (length=9), with one NUL byte. See below.

NUL byte(s) 1 NUL byte to pad the entry to a multiple of eight bytes while keeping the name NUL-terminated. In our case, the index entry starts with 64-bit ctime. In total, it has 72 bytes:

2.3 Extensions

2.4 SHA-1 Index Checksum

160-bit SHA-1 over the content of the index file before this checksum. If the index is corrupted, you might meet an error like “index file corrupt”:

3. Why Index?

Git index, or Git cache, has 3 important properties:

  1. The index contains all the information necessary to generate a single (uniquely determined) tree object.
  2. The index enables fast comparisons between the tree object it defines and the working tree.
  3. It can efficiently represent information about merge conflicts between different tree objects, allowing each pathname to be associated with sufficient information about the trees involved that you can create a three-way merge between them.

Источник

Понравилась статья? Поделить с друзьями:
  • Error bad duplicates
  • Error bad crc checksum
  • Error bad argument type numberp nil
  • Error backpropagation algorithm
  • Error azk 9038 ошибка удаленного вызова задания