Как связать visual studio code с github

Обновлено: 01.07.2022

Рано или поздно у разработчика наступает момент, когда разработка вида "хренак, хренак и в продакшен" уже не устраивает и требуются системы, которые бы работали как сохранения в игре, и в любой момент можно вернуться к определенному шагу разработки. Такие системы называют системами контроля версий, их очень много, но речь сегодня пойдет именно про GIT.

Что такое GIT

Git - система управления контроля версиями, репозитории Git содержат файлы, историю, конфигурации управляемые Git. Данные могут отправляться из локальной папки в Git репозиторий и обратно, локальное состояние подразумевает рабочую папку которая содержит измененные файлы готовые для помещения в .git каталог, при помещении в данный каталог - Commit, указываются комментарии к данному коммиту, что по факту является историей, удаленный репозиторий содержит ветки Branches, основная ветка называется Master, данные могут отправляться как в Master, так и другие ветки (ответвления) проекта.

GIT является одной из самых популярных систем. Её отличие от других программ — отсутствие графической версии. Поэтому работа с Git ведётся через командную строку. В разных операционных системах свои программы для взаимодействия с Git.

В Windows их две: PowerShell и cmd.exe. В Ubuntu это Terminal. Самая популярная программа на macOS тоже называется Terminal. Если вам не подходит встроенная в систему программа для работы с командной строкой, вы можете поставить свою. Например, написанную на JavaScript программу Hyper, которая работает на любой операционной системе. На Windows популярны программы Cmder и Git Bash, а на macOS — iTerm.

Установка GIT

Если вы ранее не работали с GIT, то для начала его нужно установить. В зависимости от системы нужно выбрать свой вариант

Установка GIT в Linux (Ubuntu)

В зависимости от вашего дистрибутива Linux требуется установить через консоль, например в убунту эта команда будет иметь следующий вид:

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

Установка на macOS

Установка в Windows

Скачайте exe-файл инсталлятора с сайта Git и запустите его. Это Git для Windows, он называется msysGit. Установщик спросит добавлять ли в меню проводника возможность запуска файлов с помощью Git Bash (консольная версия) и GUI (графическая версия). Подтвердите действие, чтобы далее вести работу через консоль в Git Bash. Остальные пункты можно оставить по умолчанию.

Проверим, что Git установлен.

После того, как все действия по установке завершены, убедимся, что Git появился в системе компьютера. Откройте терминал и введите git --version , должна появиться текущая версия программы на вашей машине. Эта проверка подходит для всех операционных систем.

Настройка Git

После установки производим настройку своего профиля вводя в терминал поочереди команды:

Заменив значения ВАШЕ_ИМЯ и АДРЕС вашими значениями.

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

Обратите внимание, что в командах, указанных выше, есть опция --global . Это значит, что такие данные будут сохранены для всех ваших действий в Git и вводить их больше не надо. Если вы хотите менять эту информацию для разных проектов, то в директории проекта вводите эти же команды, только без опции --global .

GITHUB

GitHub — веб-сервис, который основан на системе Git. Это такая социальная сеть для разработчиков, которая помогает удобно вести коллективную разработку IT-проектов. Здесь можно публиковать и редактировать свой код, комментировать чужие наработки, следить за новостями других пользователей. Именно в GitHub работаем мы, команда Академии, и студенты интенсивов.

Чтобы начать работу с GitHub, нужно зарегистрироваться на сайте, если вы ещё этого не сделали.

После того как у вас будет создан аккаунт в Github можно будет начать полноценно работать с ним.

Копирование репозитория Git в локальную папку

Для начала определим, что такое репозиторий. Это рабочая директория с вашим проектом. По сути, это та же папка с HTML, CSS, JavaScript и прочими файлами, что хранится у вас на компьютере, но находится на сервере GitHub. Поэтому вы можете работать с проектом удалённо на любой машине, не переживая, что какие-то из ваших файлов потеряются — все данные будут в репозитории при условии, что вы их туда отправите. Но об этом позже.

Сведения о клонировании общедоступного репозитория из GitHub на локальный компьютер с помощью Visual Studio Code.

Клонирование репозитория

Чтобы приступить к работе, скачайте пример проекта, как описано ниже.

Откройте палитру команд с сочетанием клавиш CTRLShiftP + + .

В строке палитры команд введите gitcl , выберите команду Git: клонировать и нажмите клавишу ВВОД.

gitcl command in the Visual Studio Code command palette prompt

Если появится запрос на ввод URL-адреса репозитория, выберите параметр клонирования из GitHub и нажмите клавишу ВВОД.

Если поступает запрос на вход в GitHub, завершите процедуру входа.

Введите azure-samples/js-e2e-express-server в поле URL-адрес репозитория.

Выберите (или создайте) локальный каталог, в который нужно клонировать проект.

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

Откройте интегрированный терминал из терминала —> новый терминал.

Клонируйте репозиторий с помощью следующей команды Git:

Измените терминал на новый подкаталог:

Затем откройте Visual Studio Code:

Инициализация нового репозитория

Если у вас еще нет репозитория GitHub, но вы хотите запустить проект локально, инициализируйте папку с помощью Git.

  • С панели действий
  • Из палитры команд
  1. Выберите систему управления версиями на панели действий или используйте сочетание клавиш CTRLShiftG + + .
  2. Выберите "Инициализировать репозиторий".
  1. Откройте палитру команд с сочетанием клавиш CTRLShiftP + + .
  2. Отфильтруйте с Git помощью, а затем выберите Initialize repository .

Создание ветви для изменений

Откройте палитру команд с сочетанием клавиш CTRLShiftP + + .

Найдите элемент git branch и выберите Git: Create Branch .

Search for `git branch` and select `Git: Create Branch`.

Введите имя для новой ветви. Имя ветви будет отображатся в строке состояния.

The branch name is visible in the status bar.

Выберите имя ветви в строке состояния. Откроется палитра команд.

Строка состояния обычно находится в нижней части Visual Studio code.

Выберите в палитре команд элемент Создание ветви.

Введите имя для новой ветви.

Введите имя для новой ветви. Имя ветви будет отображатся в строке состояния.

The branch name is visible in the status bar.

Откройте интегрированный терминал из терминала —> новый терминал.

Создайте новую ветвь с именем MY-BRANCH с помощью следующей команды Git:

Фиксация изменений в локальной среде

После внесения изменений в ветвь зафиксируйте изменения.

Откройте палитру команд с сочетанием клавиш CTRLShiftP + + .

В палитре команд отфильтруйте, а Git затем выберите Commit .

Adding the yarn.lock file to Git

Переключитесь на панель действий и выберите значок системы управления версиями или нажмите клавиши CTRL + SHIFT + G .

В палитре команд отфильтруйте, а Git затем выберите Commit .

Adding the yarn.lock file to Git

Отправка локальной ветви в GitHub

  • Из палитры команд
  • Из строки состояния
  • Из расширения системы управления версиями
  1. Откройте палитру команд с сочетанием клавиш CTRLShiftP + + .
  2. В палитре команд отфильтруйте, а Git затем выберите Push .
  3. Если у вас несколько вышестоящих удаленных, выберите удаленный, а затем нажмите клавишу ВВОД .

В строке состояния Visual Studio Code выберите значок отправки справа от имени ветви.

Visual Studio Code status bar, with the push icon highlighted.

Выберите имя удаленного расположения во всплывающем окне. Если вы имеете только одно удаленное расположение, вам не будет предложено выбрать имя такого расположения.

Щелкните значок "Система управления версиями" на панели действий.

Щелкните многоточие (. ) и выберите элемент Push или Push to .

Visual Studio Code source control, with the push icon highlighted.

Выберите имя удаленного расположения во всплывающем окне. Если вы имеете только одно удаленное расположение, вам не будет предложено выбрать имя такого расположения.

Просмотр выходных данных Git

Вы можете просмотреть команды Git, выполняемые при использовании расширения системы управления версиями. Это помогает выполнить отладку при сбое команды.

Щелкните значок "Система управления версиями" на панели действий.

Щелкните многоточие (. ) и выберите элемент Показать выходные данные Git.

Visual Studio Code source control, with the Show Git Output selection highlighted.

средства Visual Studio Code для работы с Git и GitHub

При работе в Visual Studio Code с репозиторием необходимо использовать отдельные средства.

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.

Extension Sign In

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.

GitHub repository dropdown filtered on microsoft/vscode

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:

Authentication Prompt

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.

User Hover

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

Pull Request View

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.

Create Pull Request view

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.

Pull Request Description editor

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.

Changes in Pull Request view

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.

Issue view with hover

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.

Work on Issue

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.

Issue Status bar actions

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.

GitHub Repositories extension

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.

Remote indicator in 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.

GitHub Repository extension open repository dropdown

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.

Branch indicator on the Status bar

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.

Remote Explorer view

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.

Create a Pull Request button in the Source Control view

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.

Remote indicator hover with features are not available link

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.

Continue Working on command in Remote dropdown

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.

Welcome to Visual Studio Code! VS Code is a free coding editor that helps you start coding quickly. Use it to code in any programming language, without switching editors. VS Code comes with built-in source control, so you can compare versions of your code side-by-side and save your work over time by backing it up on GitHub. We have resources specifically created for students and educators, including our Python and Java Coding Packs, programming lessons built in partnership with NASA and Netflix, and videos to quickly get up to speed.

To get started with VS Code and learn how to best use GitHub, check out the resources below:

Lessons

In this 20-minute tutorial, you'll learn how to search GitHub for repositories, clone them, and publish your own projects onto GitHub right from VS Code.

Introduction to GitHub Microsoft Learn module

In this module, learn the fundamentals of version control systems like Git.

Introduction to Git Microsoft Learn module

Tutorials

In this video, you'll see how GitHub is used when building a project. After completing this one hour tutorial and you'll end up creating a Node.js app, hosting it on GitHub, and deploying it to the cloud.

Helpful extensions

With this extension, you can quickly create pull requests and review other pull requests or issues, right from VS Code. To learn more about using this extension, check out the video below or read about the features.

The GitLens extension enhances the built-in Git features in VS Code, like showing you when lines of code were written, by whom, and in what commit. To learn more, check out this helpful video.

Connect with us

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.

Source Control Repositories view option in overflow menu

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.

SCM Provider category in the marketplace

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.

Overview of 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.

Stage all changes button

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.

views and more actions button

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.

First run Source Control experience

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.

clone repository dialog

You would then paste that URL into the Git: Clone prompt.

set repository URL

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.

Git checkout

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.

git status bar sync

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.

git status bar publish

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

Gutter indicators

Merge conflicts

Git merge

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.

A File Diff in 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.

diff-review-pane

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.

Timeline view

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.

Git initialize repository

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:

  1. 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.
  2. 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.

Читайте также: