Как подключить git к visual studio code
Рано или поздно у разработчика наступает момент, когда разработка вида "хренак, хренак и в продакшен" уже не устраивает и требуются системы, которые бы работали как сохранения в игре, и в любой момент можно вернуться к определенному шагу разработки. Такие системы называют системами контроля версий, их очень много, но речь сегодня пойдет именно про 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. Поэтому вы можете работать с проектом удалённо на любой машине, не переживая, что какие-то из ваших файлов потеряются — все данные будут в репозитории при условии, что вы их туда отправите. Но об этом позже.
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.
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 (VS Code) стал одним из самых популярных для веб-разработки. Его популярность обусловлена множеством встроенных возможностей, в том числе интеграции с системой контроля исходного кода, а именно с Git. Использование возможностей Git из VS Code позволяет сделать рабочие процессы более эффективными и надежными.
В этом учебном модуле мы изучим интеграцию контроля исходного кода в VS с помощью Git.
Предварительные требования
Для этого обучающего модуля вам потребуется следующее:
- Git, установленный на вашем компьютере. Более подробную информацию о том, как добиться этого, можно найти в учебном модуле Введение в Git.
- Последняя версия Visual Studio Code, установленная на вашем компьютере.
Шаг 1 — Знакомство с вкладкой Source Control
Прежде всего, чтобы воспользоваться преимуществами интеграции контроля исходного кода, следует инициализировать проект как репозиторий Git.
Откройте Visual Studio Code и запустите встроенный терминал. Вы можете открыть его, используя сочетание клавиш CTRL + ` в Linux, macOS или Windows.
Используя терминал, создайте каталог для нового проекта и перейдите в этот каталог:
Затем создайте репозиторий Git:
Также вы можете сделать это в Visual Studio Code, открыв вкладку Source Control (иконка выглядит как развилка дороги) в левой панели:
Затем нажмите кнопку Open Folder:
При нажатии кнопки откроется проводник файлов, где будет открыт текущий каталог. Выберите предпочитаемый каталог проекта и нажмите Open.
Затем нажмите Initialize Repository:
Если теперь вы посмотрите на свою файловую систему, вы увидите, что она содержит каталог .git . Чтобы сделать это, используйте терминал для перехода в каталог проекта и вывода его содержимого:
Вы увидите созданный каталог .git :
Это означает, что репозиторий инициализирован, и теперь вам следует добавить в него файл index.html .
После этого на панели Source Control вы увидите, что рядом с именем вашего нового файла отображается буква U. Обозначение U означает, что файл не отслеживается, то есть, что это новый или измененный файл, который еще не был добавлен в репозиторий:
Вы можете нажать значок плюс (+) рядом с файлом index.html , чтобы включить отслеживание файла в репозитории.
После этого рядом с файлом появится буква A. A обозначает новый файл, который был добавлен в репозиторий.
Чтобы записать изменения, введите команду отправки в поле ввода в верхней части панели Source Control. Затем нажмите иконку отметки check для отправки файла в репозиторий.
После этого вы увидите, что несохраненных изменений нет.
Теперь добавьте немного содержания в файл index.html .
Вы можете использовать ярлык Emmet для генерирования базовой структуры кода HTML5 в VS Code, нажав ! , а затем клавишу Tab . Теперь добавьте что-нибудь в раздел , например, заголовок , и сохраните файл.
На панели исходного кода вы увидите, что ваш файл изменился. Рядом с именем файла появится буква M, означающая, что файл изменен:
Для практики давайте запишем это изменение в репозиторий.
Теперь вы познакомились с работой через панель контроля исходного кода, и мы переходим к интерпретации показателей gutter.
Шаг 2 — Интерпретация показателей Gutter
На этом шаге мы рассмотрим концепцию Gutter («Желоб») в VS Code. Gutter — это небольшая область справа от номера строки.
Если ранее вы использовали сворачивание кода, то в области Gutter находятся иконки «Свернуть» и «Развернуть».
Для начала внесем небольшое изменение в файл index.html , например, изменим содержание внутри тега . После этого вы увидите, что измененная строка помечена в области Gutter синей вертикальной чертой. Синяя вертикальная черта означает, что соответствующая строка кода была изменена.
Теперь попробуйте удалить строку кода. Вы можете удалить одну из строк в разделе вашего файла index.html . Обратите внимание, что в области Gutter появился красный треугольник. Красный треугольник означает строку или группу строк, которые были удалены.
Теперь добавьте новую строку в конец раздела и обратите внимание на зеленую полосу. Вертикальная зеленая полоса обозначает добавленную строку кода.
В этом примере описаны индикаторы области Gutter для случаев изменения, удаления и добавления строки:
Шаг 3 — Просмотр отличий файлов
VS Code также позволяет посмотреть отличия между разными версиями файла. Обычно для этого нужно загружать отдельный инструмент diff, так что встроенная функция повысит эффективность работы.
Чтобы посмотреть отличия, откройте панель контроля исходного кода и дважды нажмите на измененный файл. В этом случае следует дважды нажать на файл index.html . Откроется типовое окно сравнения, где текущая версия файла отображается слева, а ранее сохраненная в репозитории версия — справа.
В этом примере мы видим, что в текущей версии добавлена строка:
Шаг 4 — Работа с ветвлением
Вы можете использовать нижнюю панель для создания и переключения ветвей кода. В нижней левой части редактора отображается иконка контроля исходного кода (которая выглядит как дорожная развилка), после которой обычно идет имя главной ветви или ветви, над которой вы сейчас работаете.
Чтобы создать ветвление, нажмите на имя ветви. Откроется меню, где вы сможете создать новую ветвь:
Создайте новую ветвь с именем test .
Теперь внесите изменение в файл index.html , чтобы перейти в новую ветвь test , например, добавьте текст this is the new test branch .
Сохраните эти изменения ветви test в репозитории. Затем нажмите на имя ветви в левом нижнем углу еще раз, чтобы переключиться обратно на главную ветвь master .
После переключения обратно на ветвь master вы увидите, что текст this is the new test branch , сохраненный для ветви test , отсутствует в главной ветви.
Шаг 5 — Работа с удаленными репозиториями
В этом учебном модуле мы не будем вдаваться в детали, но панель Source Control также предоставляет доступ для работы с удаленными репозиториями. Если вы уже работали с удаленными репозиториями, то вы увидите знакомые вам команды, такие как pull, sync, publish, stash и т. д.
Шаг 6 — Установка полезных расширений
В VS Code имеется не только множество встроенных функций для Git, но и несколько очень популярных расширений, добавляющих дополнительные функции.
Git Blame
Это расширение дает возможность просматривать информацию Git Blame в панели состояния для текущей выделенной строки.
Английское слово Blame имеет значение «винить», но не стоит беспокоиться — расширение Git Blame призвано сделать процесс разработки более практичным, а не обвинять кого-то в чем-то плохом. Идея «винить» кого-то за изменения кода относится не к буквальному возложению вины, а к идентификации человека, к которому следует обращаться с вопросами в отношении определенных частей кода.
Git History
Хотя вы можете просматривать текущие изменения, сравнивать версии и управлять ветвлением с помощью встроенных функций VS Code, они не дают возможности просматривать историю Git. Расширение Git History решает эту проблему.
Как можно увидеть на снимке ниже, это расширение позволяет тщательно изучать историю файла, автора, ветви и т. д. Чтобы активировать показанное ниже окно Git History, нажмите на файл правой кнопкой мыши и выберите пункт Git: View File History:
Также вы сможете сравнивать ветви и записанные в репозиторий версии, создавать ветви из записанных версий и т. д.
Git Lens
GitLens дополняет возможности Git, встроенные в Visual Studio Code. Это расширение помогает визуализировать принадлежность кода через аннотации Git Blame и линзу кода, просматривать и изучать репозитории Git из среды VS Code, получать полезные аналитические данные с помощью мощных команд сравнения, а также выполнять многие другие задачи.
Расширение Git Lens — одно из самых мощных и популярных среди сообщества разработчиков расширений. В большинстве случаев его функции могут заменить каждое из вышеперечисленных двух расширений.
Также данное расширение предоставляет много функций, связанных с историей Git. Вы можете легко получить доступ к разнообразной информации, включая историю файлов, сравнение с предыдущими версиями, открытие определенных редакций и т. д. Чтобы открыть эти опции, вы можете нажать на текст на нижней панели состояния, где указан автор, изменивший строку кода, а также время ее изменения.
При этом откроется следующее окно:
Это расширение имеет очень много функций, и потребуется время, чтобы разобраться со всеми открываемыми им возможностями.
Заключение
В этом учебном модуле вы научились использовать интеграцию с системой контроля исходного кода в VS Code. VS Code предоставляет множество функций, для использования которых раньше нужно было загружать отдельный инструмент.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Visual Studio Code (VS Code) has become one of the most popular editors out there for web development. It has gained such popularity thanks to its many built-in features such as source control integration, namely with Git. Harnessing the power of Git from within VS Code can make your workflow more efficient and robust.
In this tutorial, you will explore using Source Control Integration in VS Code with Git.
Prerequisites
To complete this tutorial, you will need the following:
- Git installed on your machine. For more details on accomplishing this, review the Getting Started with Git tutorial.
- The latest version of Visual Studio Code installed on your machine.
Step 1 — Familiarizing with the Source Control Tab
The first thing you need to do to take advantage of source control integration is initialize a project as a Git repository.
Open Visual Studio Code and access the built-in terminal. You can open this by using the keyboard shortcut CTRL + ` on Linux, macOS, or Windows.
In your terminal, make a directory for a new project and change into that directory:
Then, create a Git repository:
Another way to accomplish this with Visual Studio Code is by opening up the Source Control tab (the icon looks like a split in the road) in the left-side panel:
Next, select Open Folder:
This will open up your file explorer to the current directory. Select the preferred project directory and click Open.
Then, select Initialize Repository:
If you now check your file system, you will see that it includes a .git directory. To do this, use the terminal to navigate to your project directory and list all of the contents:
You will see the .git directory that was created:
Now that the repo has been initialized, add a file called index.html .
After doing so, you’ll see in the Source Control panel that your new file shows up with the letter U beside it. U stands for untracked file, meaning a file that is new or changed, but has not yet been added to the repository:
You can now click the plus icon (+) by the index.html file listing to track the file by the repository.
Once added, the letter next to the file will change to an A. A represents a new file that has been added to the repository.
To commit your changes, type a commit message into the input box at the top of the Source Control panel. Then, click the check icon to perform the commit.
After doing so, you will notice that are no pending changes.
Next, add a bit of content to your index.html file.
You can use an Emmet shortcut to generate an HTML5 skeleton in VS Code by pressing the ! key followed by Tab key. Go ahead and add something in the like a heading and save it.
In the source control panel, you will see that your file has been changed. It will show the letter M next to it, which stands for a file that has been modified:
For practice, go ahead and commit this change as well.
Now that you’re familiar interacting with the source control panel, you will move on to interpreting gutter indicators.
Step 2 — Intepreting Gutter Indicators
In this step you will take a look at what’s called the “Gutter” in VS Code. The gutter is the skinny area to the right of the line number.
If you’ve used code folding before, the maximize and minimize icons are located in the gutter.
Let’s start by making a small change to your index.html file, such as a change to the content within the tag. After doing so, you will notice a blue vertical mark in the gutter of the line that you changed. The vertical blue mark signifies that the corresponding line of code has been changed.
Now, try deleting a line of code. You can delete one of the lines in the section of your index.html file. Notice now in the gutter that there is a red triangle. The red triangle signifies a line or group of lines that has been deleted.
Lastly, at the bottom of your section, add a new line of code and notice the green bar. The vertical green bar signifies a line of code that has been added.
This example depicts gutter indicators for a modified line, a removed line, and a new line:
Step 3 — Diffing Files
VS Code also has the ability to perform a diff on a file. Typically, you would have to download a separate diff tool to do this, so this built-in feature can help you work more efficiently.
To view a diff, open up the source control panel and double-click a changed file. In this case, double-click the index.html file. You will be brought to a typical diff view with the current version of the file on the left and the previously committed version of the file on the right.
This example shows that a line has been added in the current version:
Step 4 — Working with Branches
Moving to the bottom bar, you have the ability to create and switch branches. If you take a look at the very bottom left of the editor, you should see the source control icon (the one that looks like a split in the road) followed most likely by master or the name of the current working branch.
To create a branch, click on that branch name. A menu should pop up giving you the ability to create a new branch:
Go ahead and create a new branch called test .
Now, make a change to your index.html file that signifies you are in the new test branch, such as adding the text this is the new test branch .
Commit those changes to the test branch. Then, click the branch name in the bottom left again to switch back to the master branch.
After switching back to the master branch, you’ll notice that the this is the new test branch text committed to the test branch is no longer present.
Step 5 — Working with Remote Repositories
This tutorial won’t touch on it in-depth, but through the Source Control panel, you do have access to work with remote repositories. If you’ve worked with a remote repository before you’ll notice familiar commands like pull, sync, publish, stash, etc.
Step 6 — Installing Useful Extensions
Not only does VS Code come with lots of built-in functionality for Git, there are also several very popular extensions to add additional functionality.
Git Blame
This extension provides the ability to view Git Blame information in the status bar for the currently selected line.
This may sound intimidating, but not to worry, the Git Blame extension is much more about practicality than it is about making someone feel bad. The idea of “blaming” someone for a code change is less about shaming them, and more about figuring out the right person to ask questions to for certain pieces of code.
As you can see in the screenshot, this extension provides a subtle message related to the current line of code you are working on in the bottom toolbar explaining who made the change and when they made it.
Git History
Although you can view current changes, perform diffs, and manage branches with the built-in features in VS Code, it does not provide an in-depth view into your Git history. The Git History extension solves that issue.
As you can see in the image below, this extension allows you to thoroughly explore the history of a file, a given author, a branch, etc. To activate the Git History window below, right-click on a file and choose Git: View File History:
Additionally, you can compare branches and commits, create branches from commits, and more.
Git Lens
GitLens supercharges the Git capabilities built into Visual Studio Code. It helps you to visualize code authorship at a glance via Git blame annotations and code lens, seamlessly navigate and explore Git repositories, gain valuable insights via powerful comparison commands, and so much more.
The Git Lens extension is one of the most popular in the community and is also the most powerful. In most ways, it can replace each of the previous two extension with its functionality.
For “blame” information, a subtle message appears to the right of the line you are currently working on to inform you of who made the change, when they made it, and the associated commit message. There are some additional pieces of information that pop up when hovering over this message like the code change itself, the timestamp, and more.
For Git history information, this extension provides a lot of functionality. You have easy access to tons of options including showing file history, performing diffs with previous versions, opening a specific revision, and more. To open up these options you can click the text in the bottom status bar that contains the author who edited the line of code and how long ago it was edited.
This will open up the following window:
This extension is packed with functionality, and it will take a while to take in all that it has to offer.
Conclusion
In this tutorial, you explored how to use source control integration with VS Code. VS Code can handle many features that previously would have required the download of a separate tool.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Читайте также: