Git add ошибка

Пытаюсь добавить проект в git, создала .gitignore
произвела следующие действия:
git init
git status
git add .
и вот git add . у меня не прошел
пишет
error: ‘site_tests/’ does not have a commit checked out
fatal: adding files failed

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

буду очень благодарна за помощь в моей проблеме

Эникейщик's user avatar

Эникейщик

25.6k7 золотых знаков31 серебряный знак47 бронзовых знаков

задан 26 авг 2019 в 20:08

NOtAgoodProgger's user avatar

NOtAgoodProggerNOtAgoodProgger

431 золотой знак1 серебряный знак8 бронзовых знаков

14

У меня была подобная ситуация.

У меня папка в которой лежат куча файлов. И я хочу эту папку проиндексировать. Но вылетела ошибка:
error: ‘JS/’ does not have a commit checked out
fatal: adding files failed

Что я сделал:

  1. В папке JS/ у меня была скрытая папка .git/ ( которая отвечает за структуру Git-репозитория ) . Она была лишней и я ее удалил. Отмечу, что у меня была папка .git на уровне проекта (в папке my_project), а папка .git в папке JS была лишней.
  2. Затем согласно данной книги: Pro Git: Основы Git — Запись изменений в репозиторий .
    Сказано: «Команда git add принимает параметром путь к файлу или каталогу, если это каталог, команда рекурсивно добавляет все файлы из указанного каталога в индекс.».

То есть нужно для каталогов указывать путь:
Для меня команда выглядела так: git add C:\Users\User\my_project\JS , и все корректно проиндексировалось.

ответ дан 8 мая 2020 в 21:07

Тимур Оразалинов's user avatar

1

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

После её удаления все заработало.

0xdb's user avatar

0xdb

51.5k198 золотых знаков59 серебряных знаков237 бронзовых знаков

ответ дан 5 окт 2021 в 20:21

Qwerty's user avatar

QwertyQwerty

696 бронзовых знаков

  • Dpy3b

Столкнулся с этим впервые, другой проект нормально залился в репозиторий.
Вот порядок действий:

Захожу в локальную папку проекта
cd ~/project

Инициализирую гит
git init

Фоловлю файлы
git add .

И тут он пишет мне:

warning: LF will be replaced by CRLF in *file_name*
The file will have its original line endings in your working directory.

После чего выполняю коммит и он пишет:

On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:

В гите новичок. Гуглил, способы решения не подошли.


  • Вопрос задан

  • 36362 просмотра

Пригласить эксперта

Инициализируем новый репозиторий
git init

Добавляем файлы (все)
git add .

Если файлы не добавляются, то добавляем каждый вручную
git add README.md

Делаем коммит
git commit -m "First commit"

Пушим
git push -u origin master

warning: LF will be replaced by CRLF in *file_name*
The file will have its original line endings in your working directory.

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

Связанно это с тем что переносы строк были в Unix-формате, так как дело происходило под Windows.
Простые решения:

Очень просто конвертировать переносы строк в Windows-формат помогает текстовый редактор Notepad++: Правка→EOL конверсия→Преобразовать в WIN-формат.
Подробнее.
Вручную преобразовать символы перевода строки из виндовых в линуксовые, открыть файл, еще раз визуально все проконтролировать и сохранить.
Быстро заменить CRLF на LF можно утилитой dos2unix, входящей в MINGW, с которым поставляется git для win32:

dos2unix.exe -f -D *file*


  • Показать ещё
    Загружается…

21 сент. 2023, в 14:16

100000 руб./за проект

21 сент. 2023, в 13:38

2500 руб./за проект

21 сент. 2023, в 13:29

5000 руб./за проект

Минуточку внимания

Sometimes, when using the git add command nothing happens. But why is the git add command not working?

Here are some of the reasons why this behavior can happen:

  • You are not in the root folder.
  • You have an invalid entry inside your .gitignore file.
  • You are using the wrong flag.

This article explores the git add command not working and shows multiple solutions for solving this issue.

Let’s get to it 😎.

git add not working

Page content

  1. Fix #1 — NOT from the root folder
  2. Fix #2 — Check the .gitignore file
  3. Fix #3 — Use the —all flag
  4. Fix #4 — Use a wildcard
  5. Fix #5 — Try to force your way
  6. Final thoughts

The git add command may not work for many reasons.

Go down this list of potential fixes to find the one that fixes your issue.

Fix #1 — NOT from the root folder

First, you need to double-check that you are trying to run this git command from the root directory of your Git repository.

If you run the command outside the root folder of the git repository, the command will not work.

If you run the command from a subdirectory the command may not work as expected.

To navigate to the top-level Git directory from within a subdirectory, run this command:

bashcd $(git rev-parse --show-toplevel)

Fix #2 — Check the .gitignore file

If a .gitignore file exists within the Git repository, open it and verify each line.

Remove any listing that may cause your files to be ignored and stage the .gitignore file.

⚠️ This is one of the most common reasons the git add command doesn’t work.

Fix #3 — Use the —all flag

Try using the git add command with the —all flag, like so:

bashgit add --all

Next, run the git status command to see the changes.

P.S. The —all flag works on subdirectories and from within subdirectories on parent folders.

Fix #4 — Use a wildcard

Try using the git add command with a wildcard, like so:

bashgit add *

Next, run the git status command to see your changes.

Fix #5 — Try to force your way

Try using the git add command with the —force flag, like so:

bashgit add --force

Final thoughts

If none of the fixes above worked, you may need to reinitialize your repository as something is broken.

To fix this error, you need to delete the .git directory inside your repository. Be aware that you WILL lose your history.

bashrm -rf .git

After running this command, initialize Git again, and everything should work.

git add not working

Here are some other Git tutorials for you to enjoy:

  • How to undo the git add command?
  • How to add an empty folder in Git?
  • How to fix the «unable to update local ref» error in Git?

Tim Mouskhelichvili

written by:

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada.

I specialize in React, Node.js & TypeScript application development.

If you need help on a project, please reach out, and let’s work together.

Moving repositories with submodules is problematic

I am thinking that originally I may have setup the Git in the App_V3 folder on the old OS

This is the source of the problem.

What matters is the version of git when the repository (or more specifically, the referenced submodule) was originally created.

Consider a repository with one submodule in vendor/awesome, how git behaved when creating the submodule is quite different.

git version < 1.7.8

The contents of vendor/awesome/.git is a folder — just like any git checkout so for example the folder structure of a checkout would be:

.gitmodules
.git
    ...
vendor/
    awesome
        .git
            config
            HEAD
            index
            packed-refs
            ...

There’s no problem moving this kind of repository around, as there are no paths stored anywhere.

git version 1.7.8 or 1.7.9

1.7.8 moved the location of a submodule’s .git folder

When populating a new submodule directory with «git submodule init»,
the $GIT_DIR metainformation directory for submodules is created inside
$GIT_DIR/modules// directory of the superproject and referenced
via the gitfile mechanism. This is to make it possible to switch
between commits in the superproject that has and does not have the
submodule in the tree without re-cloning.

Therefore vendor/awesome/.git is not a folder, it is a file with the following contents:

gitdir: /absolute/path/to/main/repo/.git/modules/vendor/awesome

And the overal folder structure is:

.gitmodules
.git
    ...
    modules
        vendor
            awesome
                config
                HEAD
                index
                packed-refs
                ...

vendor/
    awesome
        .git <- a file

The contents of .git/modules/vendor/awesome/config specifies where the working tree is:

[core]
   ...
   worktree = /absolute/path/to/main/repo/vendor/awesome

This was a pretty awesome change — however it introduced a problem, as absolute paths were used to reference locations.

git version >= 1.7.10

In version 1.7.10 the use of absolute paths in submodules was modified

The whole directory that houses a top-level superproject managed by
«git submodule» can be moved to another place.

Now vendor/awesome/.git if generated with this or a later version of git would contain:

gitdir: ../../.git/modules/vendor/awesome

The contents of .git/modules/vendor/awesome/config specifies where the working tree is:

[core]
   ...
   worktree = ../../../../vendor/awesome

Once again, there’s no problem moving this kind of repository around, as paths a relative to the main repository.

Moving repositories

With an old, or a new version of git — you’re good.

If you’re unfortunate enough to work on a repository created in 1.7.8 or 1.7.9 (which from the evidence in the question seems to be the case) and move the repository — there are 2 solutions:

  1. Clone again
  2. Correct paths in submodule .git files, and the corresponding worktree config setting

Introduction

Staging is definitely one of the best things about Git that makes it stand out from most other version control systems out there. The fact that you can group up a set of changes and commit them on depend gives a deeper level of control on your repo. Whether or not it is something you admire, you’ll probably have to get the hang of it if you wish to use git, along with the few indefinite problems it brings in the process.

In git, you should already know that we use the git add command in order to stage the target files we have in our current buffer. However, if you try out the following command in your terminal:

$ git add .

in order to add all the files present in the directory you’re currently in (under a repo), it doesn’t seem to work as intended.

Which is why in this article, I’ll try my best to provide you with the solutions and or alternatives to the “git add .” command which should get your job done in a similar manner or so,


Check if it’s your root directory

This one’s a tricky catch. Let’s say you’re inside a repository, and would like to add all the files in your entire repository to the staging area. This is what you’ve probably been willing to use the ‘git add .’ command for. However, you need to be careful about the directory from which you’re executing the command.

The dot command after git add scans for all the files and directories (as well as the files inside those sub-directories) and adds them all together in the staging area. If, however, you’re inside a sub-directory which doesn’t contain any other file (not the root directory itself) and are trying to run the command, then git status would return you with everything being up to date and nothing left to be committed. This is because the dot command does not scan for its parent directories. So if you’d like the command to run as intended, you might first need to navigate to your root directory and try running the command from there.

If it does not seem to work, then consider some other methods mentioned in the following sections.


Try using the –all flag

The –all flag acts similar to the dot command, but there’s one big difference. That is, the –all flag will scan for any folder under your entire repository, and not just the ones under the currently selected directory. Even if you’re inside a sub-folder, the –all flag is smart enough to go through each parent folder (if any) and adds them all. The full command is:

$ git add --all

Try using *

This command supposedly works like an exact clone to the dot command. In case the dot command does not work, you can give the * (also known as a wildcard) a try. The command should look like this:

$ git add *

But you do need to be aware of the fact that unlike the –all flag, using * also requires you to be at the root directory, in case you want to add all the files under your repository. If you feel like this is a disadvantage, don’t just yet. As there might be situations where you choose to add only the files under one given sub-directory, and not the entire repository. 


Check the .gitignore file

If you’re working on a remote repository that includes other people’s development, and are facing this issue in such situations, it might be a good idea to check the .gitignore file (if it exists) from the root directory in case you’re unable to add anything at all to the staging area. What you should do is check out the .gitignore file by opening it with a text editor, and examining where there’s a line that contains * all by itself. If it does, then you’d not be unable to add anything to the staging area. In fact, this is a common reason why many people have faced the exact same problem. 

Be noted that no command (not even the –all flag) will be able to add anything to the staging in this case. So in order to fix it, you can either remove the file entirely if you wish, or you can simply remove the line which contains * and save the file. You should no longer be facing the issue by now.


Explicitly add each file

If nothing of the above mentioned fixes have worked for you, the only remaining way for you to deal with the issue is by adding each of the files one by one. Yes, it’s not the best solution given that a project can potentially contain 10s or even 100s of files. But it could at least get your job done in an emergency, As you should already know, the syntax is:

$ git add <file_name>

For the most part, I guess, fixing the .gitignore issue as well as ensuring that you’re at the root directory should eradicate your problem regarding the “git add .” command not working. If nothing has helped so far, it’s time to leave git and try some other version control system.

(Don’t expect it to be that good of an idea either…)


Понравилась статья? Поделить с друзьями:
  • Ginzzu посудомойка ошибки
  • Gilgen door systems ошибка e105
  • Gimp ошибка при извлечении временных файлов
  • Gimbal motor load too large ошибка mavic pro
  • Gilgen ошибка е2000