Visual studio добавить решение в репозиторий
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Узнайте о возможностях Git для более эффективного управления версиями исходного кода в Visual Studio.
Упрощение управления версиями в Visual Studio с помощью Git
Вам когда-нибудь хотелось, чтобы можно было вернуться к ранее работающей версии кода? Вы вручную храните резервные копии кода в разных местах? Здесь вам поможет управление версиями.
Git — это самая широко используемая система управления версиями в современном мире. С помощью Git вы можете отслеживать изменения, вносимые в код с течением времени, и выполнять откат к определенным версиям. Возможности Git в Visual Studio могут принести большую пользу и новичкам, и профессиональным разработчикам.
[!Tip] Чтобы узнать об использовании Git и GitHub в Visual Studio, зарегистрируйтесь для прохождения серии курсов Git Learning Series.
Начало работы с Git и GitHub в Visual Studio
С помощью Git можно легко управлять версиями в Visual Studio. Работайте так, как вам удобно: удаленно через выбранного поставщика Git, такого как GitHub или Azure DevOps, или локально без каких-либо поставщиков.
Чтобы начать работу с Git в Visual Studio, сделайте следующее:
Если у вас есть Git-репозиторий, размещенный у поставщика, например в GitHub, клонируйте репозиторий на свой локальный компьютер.
Либо вы можете легко создать репозиторий Git и добавить свой код. Если у вас еще нет поставщика Git, рекомендуем начать с GitHub, так как именно под этого поставщика оптимизирован интерфейс Git в Visual Studio. GitHub предоставляет бесплатное и защищенное облачное хранилище кода, в котором вы можете хранить код и обращаться к нему с любого устройства и в любом месте.
Вы можете добавить учетные записи GitHub и GitHub Enterprise в свою цепочку ключей и использовать их так же, как учетные записи Майкрософт. Если у вас нет учетной записи GitHub, воспользуйтесь инструкциями, чтобы создать учетную запись GitHub для использования с Visual Studio прямо сейчас.
. image type="content" source="media/git-source-control-create-repository.jpg" alt-text="Диалоговое окно "Создание репозитория Git" в Visual Studio.".
Просмотр файлов в обозревателе решений
При клонировании репозитория или открытии локального репозитория Visual Studio переключается на контекст Git. Обозреватель решений загружает папку в корне репозитория Git и проверяет дерево каталогов на наличие просматриваемых файлов, например CMakeLists.txt или файлов с расширением .sln . Дополнительные сведения см. в разделе Просмотр файлов в Обозревателе решений.
Интуитивный повседневный рабочий процесс
Для повседневного рабочего процесса Git Visual Studio предоставляет простой способ взаимодействия с Git при написании кода без необходимости покидать свой код.
Вы можете выполнять несколько задач и экспериментировать с кодом с помощью ветвей. Если вы или ваша команда работаете с несколькими компонентами одновременно или хотите опробовать какие-то идеи, не затрагивая рабочий код, ветвление оказывается очень полезным. Рекомендуемый рабочий процесс Git использует новую ветвь для каждого компонента или исправления, над которым вы работаете. Узнайте, как создать ветвь из Visual Studio.
После создания новой ветви и переключения на нее вы можете начать с изменения имеющихся файлов или добавления новых, а затем зафиксировать работу в репозитории. Чтобы узнать больше о фиксации в Visual Studio и состоянии файлов в Git см. страницу Фиксация кода.
Если вы работаете в команде или используете разные компьютеры, вам также потребуется постоянно получать новые изменения из удаленного репозитория. Дополнительные сведения об управлении сетевыми операциями Git в Visual Studio см. на странице Получение, вытягивание, отправка и синхронизация.
. image type="content" source="media/git-source-control-inner-loop.jpg" alt-text="Интегрированная среда разработки Visual Studio с меню Git и вкладка "Изменения Git" в обозревателе решений.".
Управление репозиториями и совместная работа
Однако бывают случаи, когда лучше сосредоточиться на репозитории Git. Например, вы хотите понять, над чем работает команда, скопировать фиксацию из другой ветви или просто очистить исходящие фиксации. Visual Studio включает мощные функции для просмотра репозиториев и совместной работы, благодаря которым использовать другие средства не требуется.
Чтобы вы могли сосредоточиться на репозитории Git, в Visual Studio есть окно Репозиторий Git, в котором представлены все сведения о репозитории, включая локальные и удаленные ветви и журналы фиксации. Открыть это окно можно из меню GIT или Вид либо непосредственно из строки состояния.
. image type="content" source="media/git-source-control-repository-management.jpg" alt-text="Интегрированная среда разработки Visual Studio, в которой выделено меню Git и вкладка "Изменения Git" в обозревателе решений.".
Просмотр репозиториев Git и управление ими
Дополнительные сведения об использовании окна репозитория Git в Visual Studio для просмотра репозитория Git и управления им см. на следующих страницах:
Разрешение конфликтов слияния
Во время слияния могут возникать конфликты, если два разработчика изменяют одни и те же строки в файле и Git неизвестно, какой вариант правильный. В этом случае GIT прерывает слияние и сообщает о конфликтном состоянии. Дополнительные сведения см. в статье о разрешении конфликтов слияния.
Настройка параметров GIT
Чтобы настроить параметры Git на уровне репозитория, а также на глобальном уровне, выполните приведенные ниже действия.
- В строке меню выберите Git >Параметры.
- Затем выберите нужные параметры.
. image type="content" source="media/git-options-settings.jpg" alt-text="Диалоговое окно "Параметры" Visual Studio IDE, в котором можно выбрать параметры персонализации и настройки.".
Улучшение возможностей и отзывы
Мы продолжаем добавлять новые функции для расширения возможностей Git. Дополнительные сведения о недавно появившихся функциях, а также опрос, в котором можно поделиться отзывом, доступны в записи блога Multi-repo support in Visual Studio (Поддержка множества репозиториев в Visual Studio). Если у вас есть предложение, отправьте его нам. Мы будем рады вашему участию в работе над решением на портале Сообщества разработчиков.
Чтобы попробовать более новые обновления функций Git и обновления из выпуска предварительной версии, скачайте и установите его со страницы Visual Studio 2022 Preview. Сведения о каждом выпуске см. в Заметках о выпуске Visual Studio 2022.
Теперь Git является интерфейсом системы управления версиями по умолчанию в Visual Studio 2019. Начиная с версии 16.6 мы работаем над созданием набора функций на основе ваших отзывов. В версии 16.8 Git стал интерфейсом управления версиями по умолчанию для всех.
[!NOTE] Мы продолжаем расширять набор возможностей Git в Visual Studio 2022. Дополнительные сведения о последнем обновлении компонентов см. в записи блога Поддержка нескольких репозиториев в Visual Studio.
Дополнительные сведения о Git
Начало работы с Git в Visual Studio 2019
Мы подробно расскажем вам о том, как использовать новый интерфейс Git в Visual Studio. Однако если вы хотите сначала ознакомиться с кратким обзором, посмотрите следующее видео:
Длительность видео: 05:27 мин.
Существует три способа начать использование Git в Visual Studio для повышения производительности:
-
. Если у вас уже есть код и он не связан с Git, можно начать с создания нового репозитория Git. . Если код, с которым вы хотите работать, не находится на вашем компьютере, можно клонировать любые существующие удаленные репозитории. . Если у вас уже есть код на компьютере, его можно открыть с помощью пункта меню Файл >Открыть >Решение/проект (или Папка). Visual Studio автоматически определяет, имеется ли инициализированный репозиторий GIT.
[!NOTE] Начиная с версии 16.8 Visual Studio 2019 включает полностью интегрированный интерфейс для работы с учетными записями GitHub. Теперь вы можете добавить в цепочку ключей учетные записи GitHub и GitHub Enterprise. Вы сможете добавлять и использовать их так же, как и учетные записи Майкрософт. Это позволит упростить доступ к ресурсам GitHub в Visual Studio. Дополнительные сведения см. на странице Работа с учетными записями GitHub в Visual Studio.
[!TIP] Если у вас нет учетной записи GitHub, можно начать с выполнения действий, описанных в разделе Создание учетной записи GitHub для использования с Visual Studio.
Создание нового репозитория Git в Visual Studio 2019
Если ваш код не связан с GIT, можно начать с создания нового репозитория GIT. Для этого в строке меню выберите GIT > Создать репозиторий GIT. Затем в диалоговом окне Создание репозитория GIT введите свои данные.
. image type="content" source="media/git-create-repository.jpg" alt-text="Диалоговое окно "Создание репозитория Git" в Visual Studio.".
[!TIP] Независимо от того, является ли репозиторий общедоступным или частным, лучше создать удаленную резервную копию кода, которая будет безопасно храниться в GitHub, даже если вы работаете сами по себе. Это также позволит вам получать доступ к коду с любого компьютера.
Вы можете создать исключительно локальный репозиторий GIT, выбрав параметр Только локальный. Вы также можете связать локальный проект с любым существующим пустым удаленным репозиторием, размещенным в Azure DevOps или у любого другого поставщика Git, с помощью параметра Существующий удаленный репозиторий.
Клонирование существующего репозитория Git в Visual Studio 2019
В Visual Studio процесс клонирования прост. Если вы знаете URL-адрес репозитория, который нужно клонировать, можно вставить его в разделе Расположение репозитория, а затем выбрать место на диске, в которое будет клонирован репозиторий.
. image type="content" source="media/git-clone-repository.jpg" alt-text="Диалоговое окно "Клонирование репозитория Git" в Visual Studio.".
Если вы не знаете URL-адрес репозитория, в Visual Studio можно легко перейти к существующему репозиторию GitHub или Azure DevOps и выбрать его.
Открытие существующего локального репозитория в Visual Studio 2019
После клонирования или создания репозитория GIT Visual Studio обнаружит его и добавит в список Локальные репозитории в меню GIT.
В нем можно быстро открывать репозитории GIT и переключаться между ними.
. image type="content" source="media/git-local-repositories.jpg" alt-text="Вариант "Локальные репозитории" в меню Git в Visual Studio.".
Просмотр файлов в Обозревателе решений в Visual Studio 2019
При клонировании репозитория или открытии локального репозитория Visual Studio переключается в этот контекст GIT, сохраняя и закрывая все ранее открытые решения и проекты. Обозреватель решений загружает папку в корне репозитория Git и проверяет дерево каталогов на наличие просматриваемых файлов. К ним относятся такие файлы, как CMakeLists.txt или файлы с расширением SLN.
Visual Studio настраивает представление в зависимости от файла, загруженного в обозреватель решений:
- При клонировании репозитория, содержащего один SLN-файл, обозреватель решений напрямую загружает это решение.
- Если обозреватель решений не обнаруживает файлов SLN в репозитории, по умолчанию он загружает представление папки.
- Если репозиторий содержит несколько файлов SLN, то обозреватель решений выводит список доступных представлений для выбора.
Переключаться между текущим представлением и списком представлений можно с помощью кнопки Переключить представления на панели инструментов обозревателя решений.
. image type="content" source="media/git-solution-explorer-views.jpg" alt-text="Обозреватель решений с нажатой кнопкой "Переключить представления" в Visual Studio.".
Окно "Изменения Git" в Visual Studio 2019
GIT отслеживает изменения файлов в репозитории в процессе работы и разделяет файлы на три категории. Это те же изменения, которые отображаются при вводе команды git status в командной строке.
- Файлы без изменений: эти файлы не были изменены с момента последней фиксации.
- Измененные файлы: эти файлы изменились с момента последней фиксации, но еще не были подготовлены для следующей фиксации.
- Промежуточные файлы: эти файлы содержат изменения, которые будут добавлены в следующую фиксацию.
В процессе работы Visual Studio отслеживает изменения в файлах проекта в разделе Изменения окна Изменения GIT.
. image type="content" source="media/git-changes-window.jpg" alt-text="Окно "Изменения Git" в Visual Studio.".
Когда вы будете готовы подготовить изменения, нажмите кнопку + (плюс) для каждого из файлов, которые необходимо подготовить, или щелкните файл правой кнопкой мыши и выберите пункт Промежуточно сохранить. Можно также подготовить все измененные файлы одним щелчком мыши, используя кнопку "Промежуточно сохранить все" ( + ) в верхней части раздела Изменения.
При подготовке изменения Visual Studio создает раздел Подготовленные изменения. Только изменения из раздела Подготовленные изменения добавляются к следующей фиксации, которую можно выполнить, выбрав команду Зафиксировать промежуточные. Эквивалентная команда для этого действия — git commit -m "Your commit message" . Можно также отменить подготовку изменений, нажав кнопку – (минус). Эквивалентная команда для этого действия — git reset для отмены размещения одного файла или git reset для отмены размещения всех файлов в каталоге.
. image type="content" source="media/git-file-version-compare.jpg" alt-text="Построчное сравнение версий файла в Visual Studio.".
Выбор существующей ветви в Visual Studio 2019
В Visual Studio текущая ветвь отображается в селекторе в верхней части окна Изменения GIT.
. image type="content" source="media/git-changes-current-branch-selector.jpg" alt-text="Текущие ветви, которые можно просмотреть с помощью селектора в верхней части окна "Изменения Git" в Visual Studio.".
Текущая ветвь также доступна в строке состояния в правом нижнем углу интегрированной среды разработки Visual Studio.
. image type="content" source="media/git-changes-current-branch-status-bar.jpg" alt-text="Текущие ветви, которые можно просмотреть с помощью строки состояния в правом нижнем углу интегрированной среды разработки Visual Studio.".
В обоих местах можно переключаться между имеющимися ветвями.
Создание новой ветви в Visual Studio 2019
Можно также создать новую ветвь. Эквивалентная команда для этого действия — git checkout -b .
Чтобы создать ветвь, достаточно ввести ее имя и указать существующую ветвь, на основе которой будет создана данная.
. image type="content" source="media/git-changes-create-new-branch.jpg" alt-text="Диалоговое окно "Создание новой ветви" в Visual Studio.".
В качестве базовой можно выбрать существующую локальную или удаленную ветвь. Если флажок Извлечь ветвь установлен, вы автоматически переключитесь на новую ветвь после ее создания. Эквивалентная команда для этого действия — git checkout -b .
Окно репозитория Git в Visual Studio 2019
В Visual Studio имеется новое окно Репозиторий GIT, в котором представлены все сведения о репозитории, включая все ветви, удаленные репозитории и журналы фиксации. Открыть это окно можно из меню GIT или Вид либо непосредственно из строки состояния.
Управления ветвями в Visual Studio 2019
При выборе в меню GIT пункта Управление ветвями отображается древовидное представление ветвей в окне Репозиторий GIT. В левой области можно использовать контекстное меню для извлечения, создания, объединения ветвей, перемещения изменений из одной ветви в другую, отбора изменений и других действий. Щелкнув ветвь, можно просмотреть ее журнал фиксаций в правой области.
При принесении ветви в окне Изменения GIT под раскрывающемся списком ветвей отображается индикатор, который показывает количество фиксаций, которые не были вытянуты из удаленной ветви. Он также показывает число локальных фиксаций, которые не были отправлены.
. image type="content" source="media/git-repo-drop-down-indicator.jpg" alt-text="Окно "Изменения Git" с индикатором под раскрывающимся списком в Visual Studio.".
. image type="content" source="media/git-branch-commit-history.jpg" alt-text="Окно "Репозиторий Git" с журналом фиксаций для ветви в Visual Studio.".
Сведения о фиксации в Visual Studio 2019
. image type="content" source="media/git-branch-commit-details.jpg" alt-text="Диалоговое окно "Сведения о фиксации" в Visual Studio.".
Обработка конфликтов слияния в Visual Studio 2019
Во время слияния могут возникать конфликты, если два разработчика изменяют одни и те же строки в файле и GIT неизвестно, какой вариант правильный. В этом случае GIT прерывает слияние и сообщает о конфликтном состоянии.
В Visual Studio можно легко выявлять и устранять конфликты слияния. Во-первых, в верхней части окна Репозиторий GIT имеется золотистая информационная панель.
Но если ни одно из этих окон не открыто и вы переходите к файлу с конфликтами слияния, вам не придется искать следующий текст:
Редактор слияния в Visual Studio 2019
Редактор слияния в Visual Studio позволяет выполнять трехстороннее сравнение: в нем приводятся входящие изменения, текущие изменения и результат слияния. С помощью панели инструментов вверху редактора слияния можно переходить между конфликтами и просматривать результаты автоматического слияния в файле.
. image type="content" source="media/git-merge-editor.jpg" alt-text="Редактор слияния в Visual Studio. ".
Персонализация параметров Git в Visual Studio 2019
Чтобы настроить параметры GIT на уровне репозитория, а также на глобальном уровне, выберите в строке меню пункты GIT > Параметры или Сервис > Параметры > Управление исходным кодом. Затем выберите нужные параметры.
. image type="content" source="media/git-options-settings.jpg" alt-text="Диалоговое окно "Параметры" Visual Studio IDE, в котором можно выбрать параметры персонализации и настройки.".
Использование всех возможностей Team Explorer в Visual Studio 2019
Новый интерфейс GIT — это система контроля версий по умолчанию в Visual Studio 2019 начиная с версии 16.8. Однако при желании этот интерфейс можно отключить. Чтобы вернуться в Team Explorer для Git, выберите Средства > Параметры > Среда > Функции предварительной версии и снимите флажок Новый пользовательский интерфейс Git.
. image type="content" source="media/git-opt-new-user-experience.jpg" alt-text="Раздел "Функции предварительной версии" диалогового окна "Параметры" в Visual Studio.".
Теперь, когда вы создали приложение, вы можете добавить его в репозиторий Git. Visual Studio упрощает этот процесс с помощью инструментов Git, которые вы можете использовать непосредственно из IDE.
Чтобы связать свой код с Git, начните с создания нового репозитория Git, в котором находится ваш код:
В строке состояния в правом нижнем углу Visual Studio нажмите Добавить в систему управления версиями и выберите Git.
В диалоговом окне Создать репозиторий Git войдите в GitHub.
Имя репозитория заполняется автоматически в зависимости от расположения вашей папки. Ваш новый репозиторий является частным по умолчанию. Это означает, что только вы можете получить к нему доступ.
Независимо от того, является ли ваш репозиторий общедоступным или частным, лучше всего иметь удаленную резервную копию кода, надежно хранящуюся на GitHub. Даже если вы не работаете с командой, удаленный репозиторий позволит получать доступ к коду с любого компьютера.
После того как вы создали свой репозиторий, вы увидите информацию о статусе в строке состояния.
Первый значок со стрелками показывает, сколько исходящих и входящих фиксаций в вашей текущей ветке. Вы можете использовать этот значок, чтобы получать любые входящие или исходящие фиксации. Вы также можете выбрать отображение этих фиксаций в первую очередь. Для этого щелкните значок и выберите Просмотреть исходящие/входящие.
Второй значок с карандашом показывает количество незафиксированных изменений в вашем коде. Щелкните этот значок, чтобы просмотреть эти изменения в окне Git Changes.
Чтобы узнать больше о том, как использовать Git с вашим приложением, см. документацию по управлению версиями Visual Studio.
Visual Studio обеспечивает непосредственную интеграцию с локальными репозиториями Git и удаленными репозиториями. Это помогает в работе с такими службами, как GitHub и Azure Repos. Эта интеграция включает в себя клонирование репозитория, фиксацию изменений и управление ветвями.
В этой статье представлены общие сведения о создании локального репозитория Git для существующего проекта и некоторых возможностях Visual Studio, связанных с Git.
Открыв проект в Visual Studio, например проект из предыдущего шага, щелкните решение правой кнопкой мыши и выберите Добавить решение в систему управления версиями. В Visual Studio создается локальный репозиторий Git, содержащий код вашего проекта.
Когда Visual Studio обнаруживает, что проект управляется в репозитории Git, появляются относящиеся к Git элементы управления. Относящиеся к Git элементы управления появляются в правом нижнем углу окна Visual Studio. Эти элементы управления показывают ожидающие фиксации, изменения, имя репозитория и ветвь. Наведите указатель на эти элементы управления для просмотра дополнительных сведений.
Выберите Изменения (или элемент управления Git со значком карандаша), чтобы просмотреть незафиксированные изменения и при необходимости зафиксировать их.
Дважды щелкните файл в списке Изменения, чтобы открыть представление различий для этого файла:
Выберите Ветви (или элемент управления Git с именем ветви), чтобы изучить ветви и выполнять операции объединения и перемещения изменений из одной ветви в другую:
Чтобы перейти в другой репозиторий, выберите элемент управления Git с именем репозитория (CosineWave на предыдущем рисунке), а затем в Team Explorer используйте интерфейс подключения.
При использовании локального репозитория зафиксированные изменения помещаются сразу в него. Если установлено подключение к удаленному репозиторию, щелкните заголовок с раскрывающимся меню в Team Explorer, выберите Синхронизировать, чтобы перейти к разделу Синхронизация, и используйте представленные там команды вытягивания и принесения.
Дополнительные подробности
Общие инструкции по созданию проекта из удаленного репозитория Git см. в статье Краткое руководство. Клонирование репозитория с кодом Python в Visual Studio.
Подробное руководство и инструкции по обработке конфликтов слияния, проверке кода с запросами на вытягивание, перемещении изменений из одной ветви в другую и отборе изменений см. в руководстве по началу работы с Git и Azure Repos.
Обзор руководства
На этом руководство по Python в Visual Studio завершено. В этом руководстве вы узнали, как:
- создавать проекты и просматривать их содержимое;
- использовать редактор кода и запустить проект;
- использовать интерактивное окно для разработки нового кода и быстрого копирования этого кода в редактор;
- запускать готовую программу в отладчике Visual Studio;
- устанавливать пакеты и управлять средами Python;
- работать с кодом в репозитории Git.
Далее вы можете заняться изучением основных понятий и практических руководств, включая следующие статьи:
I'm trying to put an existing project under Git source control, but I'm unclear on several things.
I have set up a 'Team Foundation Service' Git account online.
How do I get my existing files into the online repository?
I believe this has now been embedded in the 2015 version under Team Explorer. I ran into this, where i couldnt 'Publish' (vs's initial push after init), so i will add an answer with instructions on adding the URI
17 Answers 17
I went searching around for a similar question - the way I've managed to initialize a Git repository for an existing project file is this (disclaimer: this is done in Visual Studio 2013 Express, without a Team Foundation Server setup):
- Open the project in Visual Studio.
- Go to menu File → Add to Source Control.
That did it for me - assuming Git is set up for you, you can go to menu View → Team Explorer, then double click the repository for your project file, and make your initial commit (making sure to add whatever files you'd like).
This will also save you the hassle to "supply a reasonable .gitignore file", as Visual Studio will take care of this detail for you. Between a manual git init and this, this is my preferred method from now on.
If you would like to chose the Project this new solution goes into, you can click the Sync button - then click publish to git repo, then click advanced solution and pick the Project you would like to add this new solution to.. once you have done that, you can then sync and boom
Note: that this didn't work for me because I had already added a shared library that was included in another repository. I had to remove the shared project before the 'Add to Source Control' option became available.
- First of all you need to install Git software on your local development machine, e.g. Git Extensions.
- Then do git init in the solution folder. That is the proper way to create a repository folder.
- Set up a reasonable .gitignore file, so you don't commit unnecessary stuff.
- git add
- git commit
- Add the proper remote, as described in your Team Foundation Server account git remote add origin
- git push your code
Alternatively, there are detailed guides here using the Visual Studio integration.
After slogging around Visual Studio I finally figured out the answer that took far longer than it should have.
In order to take an existing project without source control and put it to an existing EMPTY (this is important) GitHub repository, the process is simple, but tricky, because your first inclination is to use the Team Explorer, which is wrong and is why you're having problems.
First, add it to source control. There are some explanations of that above, and everybody gets this far.
Now, this opens an empty LOCAL repository and the trick which nobody ever tells you about is to ignore the Team Explorer completely and go to the Solution Explorer, right click the solution and click Commit.
This then commits all differences between your existing solution and the local repository, essentially updating it with all these new files. Give it a default commit name 'initial files' or whatever floats your boat and commit.
Then simply click Sync on the next screen and drop in the EMPTY GitHub repository URL. Make sure it's empty or you'll have master branch conflicts and it won't let you. So either use a new repository or delete the old one that you had previously screwed up. Bear in mind this is Visual Studio 2013, so your mileage may vary.
Just right click on your solution and select Add to source control. Then select Git.
Now your projects has been added to a local source control. Right click on one of your files and select Commit.
Then enter a commit message and select Commit. Then select Sync to synchronise your project with GitHub. It requires having a Git repository. Go to GitHub, create a new repository, copy the repository link, and add it to your remote source control server. Select Publish.
This answer is correct and works in VS 2015. However I had a major question with this being a new git user. VS 2015 did not seem to create a gitignore file or offer any way to ignore dlls/files that are created by VS that should NOT be checked in. Like the obj folder for instance and it is trying to commit everything into the local repos. Anyone else have this issue? I dont want all this stuff committed locally.
I'll amend my comment above as I learn more. When i check the directory it did in fact build the gitignore file which is great because it is very large and I would hate to try to build this manually. However, when i tried to do my initial commit into the local repo, VS did not use this gitignore file because all files were available for committing into git and it was a big mess. So i closed the solution, deleted the .git folder and 2 git files in my solution (which detaches from git), reopened and went to file->add to source control and selected git again. This time it worked great.
It is now Dec 2019 and it is even easier. After I did the steps above and hit Sync, I was prompted with the GitHub account and whether I wanted to make this a private repository. Once selected, the new repository was created for me (without me having to go to GitHub) and created successfully.
The easiest way is obviously as described in the MSDN article Share your code with Visual Studio 2017 and VSTS Git.
Create a new local Git repository for your project by selecting Add to Source Control in the status bar in the lower right hand corner of Visual Studio. This will create a new repository in the folder the solution is in and commit your code into that repository.
In the Push view in Team Explorer, select the Publish Git Repository button under Push to Visual Studio Team Services.
Connect Remote Source Control and enter your repository name and select Publish Repository.
Right click the solution name in Solution Explorer. Select "Add to Source Control".
Then head over to SourceTree, and select Clone/New. Select Add Working Folder and point to the new Git place you just made inside your solution.
Go and grab the clone address for an empty Git, (Bitbucket or GitHub) and go back to SourceTree, right click Remotes and add New Remote. (Note in modern versions, go to Repositories → Add Remote. . Paste your URL in that box and hit OK .
This is how you can make your initial commit and push.
On Visual Studio 2015 the only way I finally got it to work was to run git init from the root of my directory using the command line. Then I went into Team Explorer and added a local git repository. Then I selected that local git repository, went to Settings->Repository Settings, and added my Remote Repo. That's how I was finally able to integrate Visual Studio to use my existing project with git.
I read all of the answers but none of them worked for me. I went to File->Add To Source Control, which was suppose to basically do the same as git init , but it didn't seem to initialize my project because when I would then go to Team Explorer all of the options were grayed out. Also nothing would show up in the Changes dialog either. Another answer stated that I just had to create a local repo in Team Explorer and then my changes would show up, but that didn't work either. All the Git options on Team Explorer only worked after I initialized my project through the command line.
I'm new to Visual Studio so I don't know if I just missed something obvious, but it seems like my project wasn't initializing from Visual Studio.
After you select "File -> Add to Source Control", is there anything in the Output window for "Source Control - Git" pane? I wouldn't expect anything in the Changes page, but if you viewed history of the Git repository, I would expect it to show a commit "Add project files" where the files were committed to the repository.
Is this the same as the Source Control Explorer? If so, it doesn't show anything. It just displays a link to add a source control plugin. When I click it, and select Git, nothing happens. As for the other panels inside Team Explorer, nothing happens either. It's only after I initialize the project from the command line and then create a local repo from the Connections pane that I start to see VS Git tools interacting with my project.
First create a 'Solution Folder' with the desired relative path. Note that Visual Studio 2012 does not create a system folder with the same relative path.
Now inside that 'Solution Folder' add a new project, but you must be careful when defining it that the relative path in the system matches the relative path of your new 'Solution Folder'. If the system folder you want does not exist, Visual Studio 2012 will now create it for the new project. (As noted above, it does not do this when you add a new 'Solution Folder'.)
If you want to add an existing file with the matching relative path, you must first create the file in the matching system relative path, from outside of Visual Studio. Then you can Add existing file in Visual Studio.
The process is greatly simplified for VS2017 / VS2019 (maybe even earlier, but I have not tested) in conjunction with GitHub:
@user1034912 yes and I am currently using Gitlab @ work. I expect a similar approach with Gitlab extension for Visual Studio.
If the desired repository already exists (perhaps on GitHub) then you can clone it to your local system, and then copy the solution directory into it. Then add the files, commit the files, and push the local. This put the solution in a repository.
Git in Visual Studio - add existing project; how to publish your local repository to a project on GitHub, GitLab, or the like.
So, you have created a solution and you want it uploaded and versioncontroller via your Git account somewhere. Visual Studio 2015 has tools in Team Explorer for this.
As Meuep mentions, load your solution and then navigate File >> Add to Source Control . This is the equivalent of git init . Then you will have this:
Now, select Settings >> Repository Settings and scroll to Remotes.
Set up origin (make sure you put this reserved name there) and set URIs.
Then you may use Add , Sync and Publish .
I always forget this so this is more for myself but maybe might help someone else using VS.
Visual Studio has the concept of Solutions. In git however, it has the concept of a git repository tracked by local and remote branches. All the files and folders that get added to git are local.
Now going back to Visual Studio Solutions when you create a standard template project it creates all projects locally to that solution.
So the problem happens when you add a project that is not local to the solution or to git for that matter. What happens is that the solution file .sln is updated with the project location but the actual contents of the project, project files and folders can not be added to git because they are on a separate directory or a separate network drive or one some ftp server etc. This might be preferable if you only want a reference to a project file that gets compiled in the .sln file only or you want to source them to separate git or github repositories. But you don't want the actual files to be tracked by git locally.
To remedy this (i.e. you want to add them to your git repository) you just move the remote files of interest within the purview of the solution and its projects files so that they are local.
To get started with the GitHub in VS Code, you'll need to create a GitHub account and install the GitHub Pull Requests and Issues extension. In this topic, we'll demonstrate how you can use some of your favorite parts of GitHub without leaving VS Code.
If you're new to source control or want to learn more about VS Code's basic Git support, you can start with the Version Control topic.
Getting started with GitHub Pull Requests and Issues
Once you've installed the GitHub Pull Requests and Issues extension, you'll need to sign in. Follow the prompts to authenticate with GitHub in the browser and return to VS Code.
Setting up a repository
Cloning a repository
You can search for and clone a repository from GitHub using the Git: Clone command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by using the Clone Repository button in the Source Control view (available when you have no folder open).
From the GitHub repository dropdown you can filter and pick the repository you want to clone locally.
Authenticating with an existing repository
Enabling authentication through GitHub happens when you run any Git action in VS Code that requires GitHub authentication, such as pushing to a repository that you're a member of or cloning a private repository. You don't need to have any special extensions installed for authentication; it is built into VS Code so that you can efficiently manage your repository.
When you do something that requires GitHub authentication, you'll see a prompt to sign in:
Follow the steps to sign into GitHub and return to VS Code. If authenticating with an existing repository doesn't work automatically, you may need to manually provide a personal access token. See Personal Access Token authentication for more information.
Note that there are several ways to authenticate to GitHub, including using your username and password with two-factor authentication (2FA), a personal access token, or an SSH key. See About authentication to GitHub for more information and details about each option.
Note: If you'd like to work on a repository without cloning the contents to your local machine, you can install the GitHub Repositories extension to browse and edit directly on GitHub. You can learn more below in the GitHub Repositories extension section.
Editor integration
Hovers
When you have a repository open and a user is @-mentioned, you can hover over that username and see a GitHub-style hover.
Suggestions
The issues that appear in the suggestion can be configured with the GitHub Issues: Queries ( githubIssues.queries ) setting. The queries use the GitHub search syntax.
You can also configure which files show these suggestions using the settings GitHub Issues: Ignore Completion Trigger ( githubIssues.ignoreCompletionTrigger ) and GitHub Issues: Ignore User Completion Trigger ( githubIssues.ignoreUserCompletionTrigger ). These settings take an array of language identifiers to specify the file types.
Pull requests
From the Pull Requests view you can view, manage, and create pull requests.
The queries used to display pull requests can be configured with the GitHub Pull Requests: Queries ( githubPullRequests.queries ) setting and use the GitHub search syntax.
Creating Pull Requests
Once you have committed changes to your fork or branch, you can use the GitHub Pull Requests: Create Pull Request command or the Create Pull Request button in the Pull Requests view to create a pull request.
A new Create Pull Request view will be displayed where you can select the repository and branch you'd like your pull request to target as well as fill in details such as the title, description, and whether it is a draft PR. If your repository has a pull request template, this will automatically be used for the description.
Once you select Create, if you have not already pushed your branch to a GitHub remote, the extension will ask if you'd like to publish the branch and provides a dropdown to select the specific remote.
The Create Pull Request view now enters Review Mode, where you can review the details of the PR, add comments, reviewers, and labels, and merge the PR once it's ready.
After the PR is merged, you'll have the option to delete both the remote and local branch.
Reviewing
Pull requests can be reviewed from the Pull Requests view. You can assign reviewers and labels, add comments, approve, close, and merge all from the pull request Description.
From the Description page, you can also easily checkout the pull request locally using the Checkout button. This will switch VS Code to open the fork and branch of the pull request (visible in the Status bar) in Review Mode and add a new Changes in Pull Request view from which you can view diffs of the current changes as well as all commits and the changes within these commits. Files that have been commented on are decorated with a diamond icon. To view the file on disk, you can use the Open File inline action.
The diff editors from this view use the local file, so file navigation, IntelliSense, and editing work as normal. You can add comments within the editor on these diffs. Both adding single comments and creating a whole review is supported.
When you are done reviewing the pull request changes you can merge the PR or select Exit Review Mode to go back to the previous branch you were working on.
Issues
Creating issues
Issues can be created from the + button in the Issues view and by using the GitHub Issues: Create Issue from Selection and GitHub Issues: Create Issue from Clipboard commands. They can also be created using a Code Action for "TODO" comments. When creating issues, you can take the default description or select the Edit Description pencil icon in the upper right to bring up an editor for the issue body.
You can configure the trigger for the Code Action using the GitHub Issues: Create Issue Triggers ( githubIssues.createIssueTriggers ) setting.
Working on issues
From the Issues view, you can see your issues and work on them.
By default, when you start working on an issue (Start Working on Issue context menu item), a branch will be created for you, as shown in the Status bar in the image below.
The Status bar also shows the active issue and if you select that item, a list of issue actions are available such as opening the issue on the GitHub website or creating a pull request.
Once you are done working on the issue and want to commit a change, the commit message input box in the Source Control view will be populated with a message, which can be configured with GitHub Issues: Working Issue Format SCM ( githubIssues.workingIssueFormatScm ).
GitHub Repositories extension
The GitHub Repositories extension lets you quickly browse, search, edit, and commit to any remote GitHub repository directly from within Visual Studio Code, without needing to clone the repository locally. This can be fast and convenient for many scenarios, where you just need to review source code or make a small change to a file or asset.
Opening a repository
Once you have installed the GitHub Repositories extension, you can open a repository with the GitHub Repositories: Open Repository. command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by clicking the Remote indicator in the lower left of the Status bar.
When you run the Open Repository command, you then choose whether to open a repository from GitHub, open a Pull Request from GitHub, or reopen a repository that you had previously connected to.
If you haven't logged into GitHub from VS Code before, you'll be prompted to authenticate with your GitHub account.
You can provide the repository URL directly or search GitHub for the repository you want by typing in the text box.
Once you have selected a repository or Pull Request, the VS Code window will reload and you will see the repository contents in the File Explorer. You can then open files (with full syntax highlighting and bracket matching), make edits, and commit changes, just like you would working on a local clone of a repository.
One difference from working with a local repository is that when you commit a change with the GitHub Repository extension, the changes are pushed directly to the remote repository, similar to if you were working in the GitHub web interface.
Another feature of the GitHub Repositories extension is that every time you open a repository or branch, you get the up-to-date sources available from GitHub. You don't need to remember to pull to refresh as you would with a local repository.
Switching branches
You can easily switch between branches by clicking on the branch indicator in the Status bar. One great feature of the GitHub Repositories extension is that you can switch branches without needing to stash uncommitted changes. The extension remembers your changes and reapplies them when you switch branches.
Remote Explorer
You can quickly reopen remote repositories with the Remote Explorer available on the Activity bar. This view shows you the previously opened repositories and branches.
Create Pull Requests
If your workflow uses Pull Requests, rather than direct commits to a repository, you can create a new PR from the Source Control view. You'll be prompted to provide a title and create a new branch.
Once you have created a Pull Request, you can use the GitHub Pull Request and Issues extension to review, edit, and merge your PR as described earlier in this topic.
Virtual file system
Without a repository's files on your local machine, the GitHub Repositories extension creates a virtual file system in memory so you can view file contents and make edits. Using a virtual file system means that some operations and extensions which assume local files are not enabled or have limited functionality. Features such as tasks, debugging, and integrated terminals are not enabled and you can learn about the level of support for the virtual file system via the features are not available link in the Remote indicator hover.
Extension authors can learn more about running in a virtual file system and workspace in the Virtual Workspaces extension author's guide.
Continue Working on.
Sometimes you'll want to switch to working on a repository in a development environment with support for a local file system and full language and development tooling. The GitHub Repositories extension makes it easy for you to clone the repository locally or into a Docker container (if you have Docker and the Microsoft Docker extension installed) with the GitHub Repositories: Continue Working on. command available from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by clicking on the Remote indicator in the Status bar.
If you are using the browser-based editor, the "Continue Working On. " command has the options to open the repository locally or within a cloud-hosted environment in GitHub Codespaces.
Visual Studio Code has integrated source control management (SCM) and includes Git support out-of-the-box. Many other source control providers are available through extensions on the VS Code Marketplace.
Tip: Click on an extension tile to read the description and reviews in the Marketplace.
SCM Providers
VS Code has support for handling multiple Source Control providers simultaneously. For example, you can open multiple Git repositories alongside your Azure DevOps Server local workspace and seamlessly work across your projects. To turn on the Source Control Providers view, select the overflow menu in the Source Control view ( ⌃⇧G (Windows, Linux Ctrl+Shift+G ) ), hover over Views, and make sure that Source Control Repositories is marked with a check. The Source Control Providers view shows the detected providers and repositories, and you can scope the display of your changes by selecting a specific provider.
SCM Provider extensions
If you would like to install another SCM provider, you can search on the scm providers extension category in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ). Start typing '@ca' and you will see suggestions for extension categories like debuggers and linters. Select @category:"scm providers" to see available SCM providers.
Git support
VS Code ships with a Git source control manager (SCM) extension. Most of the source control UI and work flows are common across other SCM extensions, so reading about the general Git support in VS Code will help you understand how to use another provider.
Note: If you are new to Git, the git-scm website is a good place to start, with a popular online book, Getting Started videos and cheat sheets. The VS Code documentation assumes you are already familiar with Git.
Note: VS Code will leverage your machine's Git installation, so you need to install Git first before you get these features. Make sure you install at least version 2.0.0 .
👉 When you commit, be aware that if your username and/or email is not set in your Git configuration, Git will fall back to using information from your local machine. You can find the details in Git commit information.
The Source Control icon in the Activity Bar on the left will always indicate an overview of how many changes you currently have in your repository. Selecting the icon will show you the details of your current repository changes: CHANGES, STAGED CHANGES and MERGE CHANGES.
Clicking each item will show you in detail the textual changes within each file. Note that for unstaged changes, the editor on the right still lets you edit the file: feel free to use it!
You can also find indicators of the status of your repository in the bottom-left corner of VS Code: the current branch, dirty indicators, and the number of incoming and outgoing commits of the current branch. You can checkout any branch in your repository by clicking that status indicator and selecting the Git reference from the list.
Tip: You can open VS Code in a sub-directory of a Git repository. VS Code's Git services will still work as usual, showing all changes within the repository, but file changes outside of the scoped directory are shaded with a tool tip indicating they are located outside the current workspace.
Commit
Staging (git add) and unstaging (git reset) can be done via contextual actions in the files or by drag-and-drop.
You can type a commit message above the changes and press Ctrl+Enter (macOS: ⌘+Enter ) to commit them. If there are any staged changes, only those changes will be committed. Otherwise, you'll get a prompt asking you to select what changes you'd like to commit and get the option to change your commit settings.
We've found this to be a great workflow. For example, in the earlier screenshot, only the staged changes to overview.jpg will be included in the commit. Later staging and commit actions could include the changes to versioncontrol.md and the two other .jpg images as a separate commit.
More specific Commit actions can be found in the Views and More Actions . menu on the top of the Source Control view.
Tip: If you commit your change to the wrong branch, undo your commit using the Git: Undo Last Commit command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
Cloning a repository
If you haven't opened a folder yet, the Source Control view will give you the options to Open Folder from your local machine or Clone Repository.
If you select Clone Repository, you will be asked for the URL of the remote repository (for example on GitHub) and the parent directory under which to put the local repository.
For a GitHub repository, you would find the URL from the GitHub Code dialog.
You would then paste that URL into the Git: Clone prompt.
You'll also see the option to Clone from GitHub. Once you authenticate with your GitHub account in VS Code, you'll be able to search through repositories by name, and select any repo to clone it. You can also start the flow to clone a Git repository with the Git: Clone command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). To see a step-by-step walkthrough, check out our Clone repos from VS Code video.
Note: If you'd like to work on a repository without cloning the contents to your local machine, you can install the GitHub Repositories extension to browse and edit directly on GitHub. You can learn more in the GitHub Repositories extension section.
Branches and Tags
You can create and checkout branches directly within VS code through the Git: Create Branch and Git: Checkout to commands in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
If you run Git: Checkout to, you will see a dropdown list containing all of the branches or tags in the current repository. It will also give you the option to create a new branch if you decide that's a better option, or checkout a branch in detached mode.
The Git: Create Branch command lets you quickly create a new branch. Just provide the name of your new branch and VS Code will create the branch and switch to it. If you choose to Create new branch from. , you'll get an extra prompt that allows you to specify which commit the new branch should be pointing to.
Remotes
Given that your repository is connected to some remote and that your checked out branch has an upstream link to a branch in that remote, VS Code offers you useful actions to push, pull, and sync that branch (the latter will run a pull command followed by a push command). You can find these actions in the Views and More Actions . menu, along with the option to add or remove a remote.
VS Code is able to periodically fetch changes from your remotes. This enables VS Code to show how many changes your local repository is ahead or behind the remote. Starting with VS Code 1.19, this feature is disabled by default and you can use the git.autofetch setting to enable it.
Tip: You should set up a credential helper to avoid getting asked for credentials every time VS Code talks to your Git remotes. If you don't do this, you may want to consider disabling automatic fetching via the git.autofetch setting to reduce the number of prompts you get.
Git Status Bar actions
There is a Synchronize Changes action in the Status Bar, next to the branch indicator, when the current checked out branch has an upstream branch configured. Synchronize Changes will pull remote changes down to your local repository and then push local commits to the upstream branch.
If there is no upstream branch configured and the Git repository has remotes set up, the Publish action is enabled. This will let you publish the current branch to a remote.
Gutter indicators
If you open a folder that is a Git repository and begin making changes, VS Code will add useful annotations to the gutter and to the overview ruler.
- A red triangle indicates where lines have been deleted
- A green bar indicates new added lines
- A blue bar indicates modified lines
Merge conflicts
Merge conflicts are recognized by VS Code. Differences are highlighted and there are inline actions to accept either one or both changes. Once the conflicts are resolved, stage the conflicting file so you can commit those changes.
Viewing diffs
Our Git tooling supports viewing of diffs within VS Code.
Tip: You can diff any two files by first right clicking on a file in the Explorer or OPEN EDITORS list and selecting Select for Compare and then right-click on the second file to compare with and select Compare with 'file_name_you_chose'. Alternatively from the keyboard hit ⇧⌘P (Windows, Linux Ctrl+Shift+P ) and select File: Compare Active File With and you will be presented with a list of recent files.
Diff editor review pane
There is a review pane in the Diff editor that presents changes in a unified patch format. You can navigate between changes with Go to Next Difference ( F7 ) and Go to Previous Difference ( ⇧F7 (Windows, Linux Shift+F7 ) ). Lines can be navigated with arrow keys and pressing Enter will jump back in the Diff editor and the selected line.
Note: This experience is especially helpful for screen reader users.
Timeline view
The Timeline view, accessible at the bottom of the File Explorer by default, is a unified view for visualizing time-series events (for example, Git commits) for a file.
VS Code's built-in Git support provides the Git commit history of the specified file. Selecting a commit will open a diff view of the changes introduced by that commit. When you right-click on a commit, you'll get options to Copy Commit ID and Copy Commit Message.
Visual Studio Code supports more Git history workflows through extensions available on the VS Code Marketplace.
Tip: Click on an extension tile to read the description and reviews in the Marketplace.
Git output window
You can always peek under the hood to see the Git commands we are using. This is helpful if something strange is happening or if you are just curious. :)
To open the Git output window, run View > Output and select Git from the dropdown list.
Initialize a repository
If your workspace is on your local machine, you can enable Git source control by creating a Git repository with the Initialize Repository command. When VS Code doesn't detect an existing Git repository, the Source Control view will give you the options to Initialize Repository or Publish to GitHub.
You can also run the Git: Initialize Repository and Publish to GitHub commands from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Running Initialize Repository will create the necessary Git repository metadata files and show your workspace files as untracked changes ready to be staged. Publish to GitHub will directly publish your workspace folder to a GitHub repository, allowing you to choose between a private and public repositories. Check out our publishing repos video for more information about publishing to GitHub.
VS Code as Git editor
When you launch VS Code from the command line, you can pass the --wait argument to make the launch command wait until you have closed the new VS Code instance. This can be useful when you configure VS Code as your Git external editor so Git will wait until you close the launched VS Code instance.
Here are the steps to do so:
- Make sure you can run code --help from the command line and you get help.
- if you do not see help, please follow these steps:
- macOS: Select Shell Command: Install 'Code' command in path from the Command Palette.
- Windows: Make sure you selected Add to PATH during the installation.
- Linux: Make sure you installed Code via our new .deb or .rpm packages.
- if you do not see help, please follow these steps:
- From the command line, run git config --global core.editor "code --wait"
Now you can run git config --global -e and use VS Code as editor for configuring Git.
VS Code as Git diff tool
Add the following to your Git configurations to use VS Code as the diff tool:
This leverages the --diff option you can pass to VS Code to compare two files side by side.
To summarize, here are some examples of where you can use VS Code as the editor:
- git rebase HEAD~3 -i do interactive rebase using VS Code
- git commit use VS Code for the commit message
- git add -p followed by e for interactive add
- git difftool ^ use VS Code as the diff editor for changes
Working with pull requests
Visual Studio Code also supports pull request workflows through the GitHub Pull Requests and Issues extension available on the VS Code Marketplace. Pull request extensions let you review, comment, and verify source code contributions directly within VS Code.
Next steps
-
- An introductory video providing an overview of VS Code Git support. - Learn about the powerful VS Code editor. - Move quickly through your source code. - This is where VS Code really shines - Running tasks with Gulp, Grunt, and Jake. Showing Errors and Warnings - If you want to integrate another Source Control provider into VS Code, see our Source Control API.
Common questions
I initialized my repo but the actions in the . menu are all grayed out
To push, pull, and sync you need to have a Git origin set up. You can get the required URL from the repository host. Once you have that URL, you need to add it to the Git settings by running a couple of command-line actions. For example:
My team is using Team Foundation Version Control (TFVC) instead of Git. What should I do?
Use the Azure Repos extension and this will light up TFVC support.
Why do the Pull, Push and Sync actions never finish?
This usually means there is no credential management configured in Git and you're not getting credential prompts for some reason.
You can always set up a credential helper in order to pull and push from a remote server without having VS Code prompt for your credentials each time.
How can I sign in to Git with my Azure DevOps organization that requires multi-factor authentication?
Git Credential Manager (GCM) is the recommended Git credential helper for Windows, macOS, and Linux. If you're running Git for Windows, GCM has already been installed and configured for you. If you're running on macOS or Linux, the GCM README has setup instructions.
I have GitHub Desktop installed on my computer but VS Code ignores it
VS Code only supports the official Git distribution for its Git integration.
I keep getting Git authentication dialogs whenever VS Code is running
VS Code automatically fetches changes from the server in order to present you with a summary of incoming changes. The Git authentication dialog is independent from VS Code itself and is a part of your current Git credential helper.
One way to avoid these prompts is to set up a credential helper that remembers your credentials.
Another option is to disable the auto fetch feature by changing the following setting: "git.autofetch": false .
Can I use SSH Git authentication with VS Code?
Yes, though VS Code works most easily with SSH keys without a passphrase. If you have an SSH key with a passphrase, you'll need to launch VS Code from a Git Bash prompt to inherit its SSH environment.
Читайте также: