Не получается сделать commit (Unversioned files) Pycharm GitHub
Как вернуть статус этим файлам чтобы модно было их commit на gitHub? Выдает, что я не могу сделать коммит этих файлов

Отслеживать
26.2k 7 7 золотых знаков 31 31 серебряный знак 48 48 бронзовых знаков
задан 4 ноя 2021 в 22:22
27 5 5 бронзовых знаков
А случаем у вас нету в проекте .gitignore файла, в котором прописано, что файлы такого типо не передаются ?
5 ноя 2021 в 14:28
@WilteRatenau Этот файл присутсвует но он пустой
6 ноя 2021 в 19:59
Тогда Вам стоит так же посмотреть обучающие материалы как с этими файлами работать в рамках django проекта. Так как миграции и файлы бд Вам не нужны будут при деплое и есть static файлы которые тоже не нужны.
8 ноя 2021 в 9:03
2 ответа 2
Сортировка: Сброс на вариант по умолчанию
Если у вас PyCharm показывает 5к+ unrevisioned files — просто добавлять их все в git будет очень плохой идеей.
В проектах (особенно новых) обычно не бывает такого количества файлов, скорее всего это файлы виртуального окружения, кэша, файлы IDE и т.д. В первую очередь нужно, чтобы это все игнорировалось, для этого все не нужное надо добавить в файл .gitignore .
Естественно, его нужно переименовать, так, чтобы осталось только .gitignore . В самом файле я обычно раскомментирую последнюю строку .idea/ (игнорирование файлов проекта PyCharm или IntellijIDEA).
После добавления этого файла количество Unrevisioned files должно стать сильно меньше, при коммите через PyCharm ставьте галку на Unrevisioned files (пустой квадрат слева от этой надписи — это чекбокс), и коммитите.
Либо через консоль делаете git add . , потом коммитите. Без разницы как именно вы добавите эти файлы (поставив галку на них или через git add . ), суть одна и та же.
Как сменить исполнителя коммита в pycharm?

Алексей Тен, при выполнении коммита первый раз указываешь свои данные — имя и почту для связи, и под этими данными есть галочка, мол «set properties global», и он подставляет потом эти данные всюду.
vfl.ru/fotos/374beccb26375382.html

https://help.github.com/en/articles/changing-autho.
ну и перенастроить pycharm
Михаил Кузнецов @pika-pika Автор вопроса
Алексей Тен, интересует именно перенастроить pycharm, что бы при создании нового коммита можно было сменить, указать данные исполнителя. Копался сам по настройкам, в том числе и через поиск — не нашёл.
Про изменение данных в уже выполненном коммите не думал, но сейчас, после прочтения, понимаю когда и где может понадобиться, но сам до такого ещё не дошёл.
Решения вопроса 1

Сергей Кузнецов @sergey-kuznetsov Куратор тега Git
Автоматизатор
В самом PyCharm вы такой настройки не найдёте. Имя и мыло хранятся в конфигах гита, которые находятся как минимум в трёх местах на диске компьютера. PyCharm достаточно умён, чтобы увидеть, что вы ещё не настроили свой системный Git и выводит красивый диалог для ввода недостающих данных.
Но для редактирования извольте уже открыть терминал и ввести команды
git config --global user.name "John Smith" git config --global user.email john@smith.com
Подправить подписи старых коммитов позволит команда
git filter-repo —mailmap my-mailmap
Ответ написан более года назад
Комментировать
Нравится Комментировать
Ответы на вопрос 1
Михаил Кузнецов @pika-pika Автор вопроса
Нашёл какое никакое решение своего вопроса.
В папке пользователя находится файл .gitconfig, в котором и указаны имя и почта (открывается обычным блокнотом). После удаления файла он снова спрашивает имя и почту исполнителя.
И ещё, если этот файл как то переименовать, добавить что то до точки, то виндовс не позволит потом сохранить файл с названием, начинающимся с точки.
Может есть какой то вариант добиться этого через сам pycharm?
Ответ написан более трёх лет назад

Сергей Кузнецов @sergey-kuznetsov Куратор тега Git
Вы не должны редактировать этот файл вручную. Доверьте это самому гиту.
И прочитайте наконец руководство пользователя.
Использование Git в IDE PyCharm без CLI

Как организовать процесс написания кода, чтобы в любой момент можно было вернуться к последней рабочей версии? Как не хранить 100500 архивов, но иметь достаточную глубину отката? Как взаимодействовать нескольким участником команды в рамках работы над одной задачей и не затереть чужой код? Разобраться в этих вопросах, не вникая во все тонкости работы с командной строкой, попытаемся в посте.
Все мы знаем о преимуществах использования систем контроля версий как при самостоятельной разработке, так и при работе в команде. Сегодня я хотел бы рассказать о поддержке в PyCharm самой популярной системы контроля версий Git и ее GUI.
Для начала предлагаю убедиться, что на машине установлен сам Git. В MS Windows это можно сделать открыв командную строку и набрав в ней git —version.

Если вдруг cmd не понимает такой команды, значит Git не установлен. Так как он является свободно распространяемым ПО, его можно бесплатно скачать и установить. Версия для MS Windows доступна по ссылке https://gitforwindows.org.
Теперь запускаем PyCharm и открываем какой-либо свой проект. С помощью команд главного меню VCS -> Enable Version Control Integration… -> [в выпадающем списке] Git подключаем контроль версий.

Сразу же не забываем создать .gitignore, чтобы не таскать конфигурационные, сборочные файлы и т.п.
Также нужно добавить конкретные файлы/директории, для которых Git будет отслеживать изменения. Изначально, после подключения контроля версий к проекту, все файлы выделятся красным цветом. Выделив необходимые из них и вызвав контекстное меню, кликаем Git -> Add. Файлы выделятся зеленым цветом – значит будут отслеживаться системой контроля версий.

Затем нужно будет сделать первый commit (Git -> Commit Files…), чтобы сохранить текущее состояние, к которому можно будет впоследствии откатиться с помощью rollback, если что-то пойдет не так.
В ходе дальнейшей работы, после редактирования, файлы будут выделяться синим цветом, сигнализируя о наличии незафиксированных commit-ом изменений. После commit-а цветовое выделение будет сниматься, давая понять, что несохраненные изменения отсутствуют.

Использование в разработке системы контроля версий, дает ряд неоспоримых преимуществ.
В любой момент времени есть возможность посмотреть всю хронологию произведенных над файлом изменений с помощью (Git -> Show History). Удобно видеть кто, когда и что именно добавил в проект.

При необходимости всегда можно посмотреть изменения более детально (Git -> Show Diff).

Конечно же, есть возможность работы с ветками: создавать, реализовывать в них новую функциональность, производить слияние.
Все вышеописанные манипуляции возможны не только с локальным репозиторием, но и с удаленным, что особенно полезно при командной работе.
Давайте рассмотрим, как запушить свой проект, например, на github (Git -> GitHub -> Share Project on GitHub). При использовании этой функции впервые, IDE попросит авторизоваться на GitHub.

В правом нижнем углу мы можем видеть и управлять локальным и удаленным репозиториями и всеми их ветками.

Пушить commit-ы в удаленный репозиторий можно с помощью Git -> Push, либо при создании commit-а выбрать не commit, как раньше, а commit and push…, тогда создастся локальный commit и запушится в удаленный репозиторий.
Обновлять проект с учетом изменений в удаленном репозитории можно с помощью Git -> Update Project.
Я рассмотрел основные операции, связанные с контролем версий, которыми пользуются разработчики, Data Scientist-ы, аналитики, инженеры и все, кто работает над проектами несколько более сложными чем “Hello World!”. Хотелось бы обратить внимание на то, что мне ни разу не пришлось прибегать к CLI и терминалу. Все базовые задачи удалось решить с помощью графического интерфейса IDE. В данном посте я попытался показать преимущества использования GUI, но, несомненно, работа через терминал имеет также свои плюсы и каждый волен выбирать то, что ближе ему.
Commit and push changes to Git repository
After you’ve added new files to the Git repository, or modified files that are already under Git version control, and you are happy with their current state, you can share the results of your work. This involves committing them locally to record the snapshot of your repository to the project history, and then pushing them to the remote repository so that they become available to others.
Set your Git username
Git needs to know your username to associate commits with an identity. If you have not set your username, PyCharm will prompt you to specify it when you first attempt to commit changes.
- Open the Terminal and execute one of the following commands:
- To set a name for every Git repository on your machine, use $ git config —global user.name «John Smith»
- To set a name for a single repository, use $ git config user.name «John Smith»
Commit changes locally
- Open the vertical Commit tool window Alt+0 located on the left:

- As your changes are ready to be committed, select the corresponding files or an entire changelist. If you press Control+K , the entire active changelist will be selected. You can also select files under the Unversioned Files node — PyCharm will stage and commit these files in one step.
- If you want to append local changes to the latest commit instead of creating a separate commit, select the Amend option.
- Enter the commit message. You can click to choose from the list of recent commit messages. You can also edit the commit message later before you’ve pushed the commit. You can customize commit message rules on the Version Control | Commit page of the IDE settings Control+Alt+S . There is also a quick-fix and the Reformat action that wrap a long line or reformat the message. You can also define a commit template that will be used as the default commit message. Specify the boilerplate text you want to use in a .txt file and execute the following command in the terminal to add it to your Git config: git config —local commit.template
- If you need to perform commit checks, upload files to a server after the commit, or commit with advanced options, click in the bottom-right corner:
The following options are available:
- Author : if you are committing changes made by another person, you can specify the author of these changes.
- Sign-off commit : select if you want to sign off your commit to certify that the changes you are about to check in have been made by you, or that you take the responsibility for the code you’re committing. When this option is enabled, the following line is automatically added at the end of the commit message: Signed off by:
- In the Commit Checks area, select the actions you want PyCharm to perform while committing the selected files to the local repository. The following options are available:
- Reformat code : perform code formatting according to the Project Code Style settings.
- Rearrange code : rearrange your code according to the arrangement rules preferences.
- Optimize imports : remove redundant import statements.
- Analyze code : analyze modified files while committing them. Click Choose profile to select an inspection profile from which the IDE will run inspections.
- Check TODO () : Review the TODO items matching the specified filter. Click Configure to choose an existing TODO filter, or open the TODO settings page and define a new filter to be applied.
- Cleanup : batch-apply quick-fixes from code cleanup inspections. Click Choose profile to select a profile from which the IDE will run inspections.
- Run Tests : run tests as commit checks. Click Choose configuration near Run Tests and select which configuration you want to run.
- Update copyright : add or update a copyright notice according to the selected copyright profile — scope combination.
- In the After Commit area, you can select the server access configuration or a server group to use for uploading the committed files to a local or remote host, a mounted disk, or a directory. For more information, refer to Deploy. The following options are available:
- Run tool : select the external tool that you want PyCharm to launch after the selected changes have been committed. You can select a tool from the list, or click the Browse button and configure an external tool in the External Tools dialog that opens.
- Upload files to : select the server access configuration or a server group to use for uploading the committed files to a local or remote host, a mounted disk, or a directory.
- To suppress uploading, choose None .
- To add a server configuration to the list, click and fill in the required fields in the Add Server dialog that opens.
The list is only available if the FTP/SFTP/WebDAV Connectivity plugin is enabled.
Commit part of a file
Sometimes when you make changes that are related to a specific task, you also apply other unrelated code modifications that affect the same file. Including all such changes into one commit may not be a good option, since it would be more difficult to review, revert, cherry-pick them, and so on.
PyCharm lets you commit such changes separately in one of the following ways:
- select modified code chunks and lines that you want to include in a commit right in the Commit Changes dialog and leave other changes pending so that you can commit them later.
- put different code chunks into different changelists on the fly, when you edit code, and then commit these changelists separately. You can also create a new changelist and make it active, then all changes that you make after that will fall into that changelist, while any modifications you made before that will stay where they are.
Select chunks and specific lines you want to commit
- Open the Commit tool window Alt+0 .
- To display the differences between the repository version and the local version of the selected file, in the Commit tool window Alt+0 , select Show Diff from the context menu or press Control+D .
- Select the checkbox next to each chunk of modified or newly added code that you want to commit, and leave other changes unselected:
You can also select Move to Another Changelist from the context menu of a modified chunk to split changes between different changelists that you can commit separately. To assign a custom shortcut for this action, look for the Move Lines to Another Changelist action under Version Control Systems on the Keymap page of the IDE settings Control+Alt+S . - If you want to commit only a specific line from a chunk, right-click the line you want to include and select Split Chunks and Include Selected Lines into Commit .
Alternatively, hover over the gutter and select or clear the checkbox next to the line you want to include in the commit or exclude from it. - Click Commit . Unselected changes will stay in the current changelist, so that you can commit them separately.
Put changes into different changelists

- When you make a change to a file in the editor, click the corresponding change marker in the gutter. If there are no change markers in the gutter, make sure the Highlight modified lines in the gutter option is enabled on the Editor | General page of the IDE settings Control+Alt+S .
- In the toolbar that appears, select the target changelist for the modified code chunk (or create a new changelist):
- Commit each changelist separately.
Use the Git staging area to commit changes
If you are more used to the concept of staging changes for commit instead of using changelists where modified files are staged automatically, press Control+Alt+S to open the IDE settings and select Version Control | Git , then select the Enable staging area checkbox.
The Commit tool window will now look as follows:

Using the staging area allows you to easily commit changes to the same file separately (including overlapping changes), and see which changes are already staged without switching focus from the editor.
When you switch from using changelists to Git staging area, all existing changelists are saved. You can switch between the two modes without losing your changes.
Stage changes for commit
- Do one of the following:
- To stage an entire file, in the Commit tool window Alt+0 , select this file and click on the right next to it or press Control+Alt+A .

- To stage a specific chunk inside a file, in the editor click the change marker in the gutter next to the modified chunk and click Stage .
Staged changes (including changes staged from outside PyCharm) are marked with a border-shaped change marker in the editor: 
- To stage granular changes like a single line instead of a code chunk, or even one of several changes to a single line, in the Commit tool window Alt+0 , select the file containing the change and choose Compare HEAD, Staged and Local Versions from the context menu. This will open a three-way diff viewer where the left pane shows the repository version, the right pane shows the local version, and the central pane is a fully-functional editor where you can make the changes you want to stage.

- To stage an entire file, in the Commit tool window Alt+0 , select this file and click on the right next to it or press Control+Alt+A .
- When ready, commit the changes as described in Commit changes locally.
Push changes to a remote repository
Before pushing your changes, sync with the remote and make sure your local copy of the repository is up to date to avoid conflicts.
PyCharm allows you to upload changes from any branch to its tracked branch or to any other remote branch.
- Do one of the following:
- To push changes from the current branch press Control+Shift+K or choose Git | Push from the main menu.
- To push changes from any local branch that has a remote, select this branch in the Branches popup and choose Push from the list of actions.
The Push Commits dialog opens showing all Git repositories (for multi-repository projects) and listing all commits made in the current branch in each repository since the last push.
If you have a project that uses multiple repositories that are not controlled synchronously, only the current repository is selected by default (for more information about enabling synchronous repositories control, refer to Version Control Settings: Git).
You can press Control+Q for the selected commit to display extra info, such as the commit author, time, hash and the commit message.
Update your working copy if push is rejected
If push is rejected because your working copy is outdated, PyCharm displays the Push Rejected dialog, provided that the Auto-update if push of the current branch was rejected option in the Git settings page of the Settings dialog is not selected. Do the following:
- If your project uses several Git repositories, specify which of them you want to update. If you want to update all repositories, no matter whether push was rejected for them or not, select the Update all repositories option. If this option is cleared, only the affected repositories will be updated.
- If you want PyCharm to apply the update procedure silently the next time push is rejected using the update method you choose in this dialog, select the Remember the update method choice and silently update in the future option. After you leave this dialog, the Auto-update if push of the current branch was rejected checkbox in the Git settings page of the Settings dialog will be selected, and the applied update method will become the default one. To change the update strategy, deselect this option to invoke the Push Rejected dialog the next time push of the current branch is rejected, apply a different update procedure, and select the Remember the update method choice option once again.
- Select the update method (rebase or merge) by clicking the Rebase or Merge button respectively.
When do I need to use force push?
When you run push , Git will refuse to complete the operation if the remote repository has changes that you are missing and that you are going to overwrite with your local copy of the repository. Normally, you need to perform pull to synchronize with the remote before you update it with your changes.
The —force push command disables this check and lets you overwrite the remote repository, thus erasing its history and causing data loss. Under the hood, when you choose to force push, PyCharm performs the push —force-with-lease operation which is a safer option that helps you ensure you do not overwrite someone else’s commits (refer to git push for more details on the push options).
A possible situation when you may still need to perform —force push is when you rebase a pushed branch and then want to push it to the remote server. In this case, when you try to push, Git will reject your changes because the remote ref is not an ancestor of the local ref. If you perform pull in this situation, you will end up with two copies of the branch which you then need to merge.