Как установить git в vs code
Перейти к содержимому

Как установить git в vs code

  • автор:

Name already in use

vscode-docs / docs / sourcecontrol / github.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Working with GitHub in VS Code

GitHub is a cloud-based service for storing and sharing source code. Using GitHub with Visual Studio Code lets you share your source code and collaborate with others right within your editor. There are many ways to interact with GitHub, for example, via their website at https://github.com or the Git command-line interface (CLI), but in VS Code, the rich GitHub integration is provided by the GitHub Pull Requests and Issues extension.

Install the GitHub Pull Requests and Issues extension

To get started with the GitHub in VS Code, you’ll need to install Git, 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 Source 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

If you are not redirected to VS Code, you can add your authorization token manually. In the browser window, you will receive your authorization token. Copy the token, and switch back to VS Code. Select Signing in to github.com. in the Status bar, paste the token, and hit kbstyle(Enter) .

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 ( kb(workbench.action.showCommands) ) 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.

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

There is a similar hover for #-mentioned issue numbers, full GitHub issue URLs, and repository specified issues.

Issue Hover

User suggestions are triggered by the «@» character and issue suggestions are triggered by the «#» character. Suggestions are available in the editor and in the Source Control view’s input box.

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.

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.

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

The default issue triggers are:

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

You can configure the name of the branch using the GitHub Issues: Issue Branch Title ( githubIssues.issueBranchTitle ) setting. If your workflow doesn’t involve creating a branch, or if you want to be prompted to enter a branch name every time, you can skip that step by turning off the GitHub Issues: Use Branch For Issues ( githubIssues.useBranchForIssues ) setting.

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 ( kb(workbench.action.showCommands) ) 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.

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

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:

  • Create a GitHub codespace (if you have the GitHub Codespaces extension).
  • Clone the repository locally.
  • Clone the repository into a Docker container (if you have Docker and the Microsoft Docker extension installed).

To switch development environments, use the Continue Working On. command, available from the Command Palette ( kb(workbench.action.showCommands) ) 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.

Continue Working On from web-based editor

The first time that you use Continue Working On with uncommitted changes, you will have the option to bring your edits to your selected development environment using Cloud Changes, which uses a VS Code service to store your pending changes.

These changes are deleted from our service once they are applied to your target development environment. If you choose to continue without your uncommitted changes, you can always change this preference later by configuring the setting «workbench.cloudChanges.continueOn»: «prompt» .

In VS Code, you can enhance your coding with artificial intelligence (AI), such as suggestions for lines of code or entire functions, fast documentation creation, and help creating code-related artifacts like tests.

GitHub Copilot is an AI-powered code completion tool that helps you write code faster and smarter. You can use the GitHub Copilot extension in VS Code to generate code, or to learn from the code it generates.

Copilot extension in the VS Code Marketplace

You can learn more about how to get started with Copilot in the Copilot documentation.

Set up GitHub with Visual Studio code [Step-by-Step]

Getting started with steps to setup GitHub with Visual Code

Knowing how to set up GitHub with visual studio code will simplify your software development process. Here’s what happens in a typical git-GitHub-Visual Studio Code workflow.

You build a remote repo on GitHub and clone it on your terminal. Next, you create and modify files in the Visual Studio Code. You then return to the terminal to stage, commit and push the changes to the remote repo.

The back and forth switching between applications can be tiresome. Worse yet, you may lack the skills to use the terminal. Or you want to see details of what you do on a GUI.

Thanks to constant improvements to Visual Studio Code, you can now log into and interact with your GitHub account right from the Visual Studio Code.

To get started, you need to install git and Visual Studio Code on your computer, have a GitHub account, then do some settings in Visual Studio Code. One of the settings is enabling git in the Visual Studio Code through these steps.

After that, you can modify, commit and push files. As you will see in this tutorial, you can comfortably make branches, merge and delete them from Visual Studio Code. You can also handle pull requests and issues using extensions we will install.

Let’s dive into a detailed explanation of the concepts before learning how to set up GitHub with visual studio code with examples.

Introduction to git, GitHub, and Visual Studio Code

Git is a free, open-source, actively maintained, distributed version control system. It gives you the convenience of tracking file changes and software versions online and offline.

In an offline setting, git stores the changes in the git database, whose details lie in the .git subdirectory of your project’s root directory. You can take a snapshot of your repo in a cloud-based service like GitHub, GitLab, or Bitbucket.

But how do you modify the files? That is where a code editor like Visual Studio Code comes in. Visual Code Studio is a cross-platform source-code editor made by Microsoft.

Requirements to set up GitHub with visual studio code

Get the software

Install git and Visual Studio Code of your operating system, then create a GitHub account.

Know the basics of git workflow

Before attempting to set up GitHub with Visual Studio Code, you should understand what happens in a git workflow. Learn the three levels of the workflow: working directory, file staging, and change committing.

Next, you should know how to push and undo changes. Lastly, it would be best to understand git pulling, branching, merging, and rebasing.

That is all you need to set up GitHub with visual studio code. We can now prepare a lab to manage a GitHub repo using Visual Studio Code.

Set up GitHub with Visual Studio Code

In this section, we will log in to GitHub from Visual Studio Code, enable git on Visual Studio Code, and create a remote repo to practice a basic Visual Studio Code-GitHub workflow.

Confirm installations

It would help to confirm our git and Visual Studio code installations before doing any practice or trying to set up GitHub with visual studio code.

To check for git installation, open your terminal or command line and run the following command.

Similarly, you can check the Visual studio code installation as follows.

Set up GitHub with Visual Studio code [Step-by-Step]

Configure global details

Configure your git username, email, and text editor because git will need them for the commits.

I am setting mine as follows:

Here, code represents Visual Studio Code.

Enable git in VS Code

Open a new Visual Studio Code window. On the bottom-left corner, you see the settings icon which tooltips to Manage on hover.

Set up GitHub with Visual Studio code [Step-by]Step]

Click on it followed by settings. In the search box, type git enable, scroll down and check the box labelled, Git: Enabled .

Set up GitHub with Visual Studio code [Step-by]Step]

Sign in to GitHub from Visual Studio Code

Return to Visual Studio Code’s main page. Next to the Manage icon is Accounts. Click on it followed by Turn on Settings Sync, then Sign in and Turn on and Sign in with GitHub.

The system takes you to your default browser, from where you can log in to your GitHub account, enabling you to set up GitHub with Visual Code Studio. Click Continue and accept prompts till you get redirected to Visual Studio Code.

Set up GitHub with Visual Studio code [Step-by]Step]

Create a remote repo

Head over to GitHub and create a repo to practice setup GitHub with Visual Studio Code.

remote to set up GitHub with visual studio code

Now that we have set up GitHub with visual studio code, let’s use the environment to explore a standard git workflow.

Example-1: Set up GitHub with visual studio code to commit and push a file

Click on Clone repository. Choose Clone from GitHub. If you are logged in, you will see a list of your remote repos.

Otherwise, GitHub leads you to the login page where you can sign in to GitHub. It then redirects you to Visual Code Studio on successful login.

Pick the repo, new_repo , we created in the lab section.

Set up GitHub with Visual Studio code [Step-by]Step]

Save the repo in a folder, create a text file with the words «text file» and save it.

The Source control tab shows we have a new change. Likewise, the file gets marked with U meaning untracked. Click on the Source Control tab and the plus, + sign on the file. That’s the equivalent of git staging on a terminal workflow.

Set up GitHub with Visual Studio code [Step-by]Step]

Enter a text message in the textbox and click on the tick whose hover reveals Commit.

The entered text is our commit message. Lastly, we can push the changes using these four main ways.

You can click on:

  1. Sync Changes,
  2. View -> Command Palette -> Git: Push,
  3. the ellipsis . followed by push, or
  4. The bottom-left cycle icon next to the current branch.

I am using the option 4 above.

Checking the repo on GitHub confirms our git push action was successful.

Set up GitHub with Visual Studio code [Step-by]Step]

We can modify the file, stage, commit and push the changes using the same steps. Let’s see how to collaborate on the remote.

Example-2: Branching, merging, and pulling using Visual Studio Code

Creating, switching between, and pushing branches is simple after setting up GitHub with Visual Studio Code. Click on Source Control ( Ctrl+Shift+G ), the ellipsis . followed by Branch, then choose a target option.

We can also create a branch by clicking on the current branch, main, then follow prompts till we make and check out a branch. I have created one called branch_B .

Set up GitHub with Visual Studio code [Step-by]Step]

Let’s modify file.txt by appending the line «modified».

Set up GitHub with Visual Studio code [Step-by]Step]

And follow the example-1 steps above to push the changes.

Lastly, we can merge branches and pull changes by checking out the main branch, clicking Source Control ( Ctrl+Shift+G ), the ellipsis . followed by Branch and choosing Merge branch, picking branch_B then pushing the changes to synchronize the remote repo with the local one.

Bonus tricks

There are multiple extensions to apply as we set up GitHub with visual studio code. Here are two of the most crucial ones.

    — manage pull requests and related challenges
  1. GitHub Repositories — view, search, edit and commit changes to any remote repos.

Head over to the Extensions tab and search the extensions’ respective names.

After installing the GitHub Pull Requests and Issues extension, you should see the GitHub icon. On the other hand, the GitHub Repositories extension creates a screen-like shape named Remote Explorer on hover.

Set up GitHub with Visual Studio code [Step-by]Step]

Their friendly docs should guide you to use them smoothly. You can also find guidelines on how to use GitHub Repositories Visual Studio Code’s documentation.

Key Takeaway

You just learned how to set up GitHub with Visual Studio Code and practiced a basic git workflow. Now is the time to ease your software tracking journey by using the workflow alongside command-line commands.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Git для новичков (часть 1)

Git — это консольная утилита, для отслеживания и ведения истории изменения файлов, в вашем проекте. Чаще всего его используют для кода, но можно и для других файлов. Например, для картинок — полезно для дизайнеров.

С помощью Git-a вы можете откатить свой проект до более старой версии, сравнивать, анализировать или сливать свои изменения в репозиторий.

Репозиторием называют хранилище вашего кода и историю его изменений. Git работает локально и все ваши репозитории хранятся в определенных папках на жестком диске.

Так же ваши репозитории можно хранить и в интернете. Обычно для этого используют три сервиса:

Каждая точка сохранения вашего проекта носит название коммит (commit). У каждого commit-a есть hash (уникальный id) и комментарий. Из таких commit-ов собирается ветка. Ветка — это история изменений. У каждой ветки есть свое название. Репозиторий может содержать в себе несколько веток, которые создаются из других веток или вливаются в них.

Как работает

Если посмотреть на картинку, то становиться чуть проще с пониманием. Каждый кружок, это commit. Стрелочки показывают направление, из какого commit сделан следующий. Например C3 сделан из С2 и т. д. Все эти commit находятся в ветке под названием main . Это основная ветка, чаще всего ее называют master . Прямоугольник main* показывает в каком commit мы сейчас находимся, проще говоря указатель.

В итоге получается очень простой граф, состоящий из одной ветки ( main ) и четырех commit. Все это может превратиться в более сложный граф, состоящий из нескольких веток, которые сливаются в одну.

Об этом мы поговорим в следующих статьях. Для начала разберем работу с одной веткой.

Установка

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

Но для начала, все же установим сам Git.

Windows. Проходим по этой ссылке, выбираем под вашу ОС (32 или 64 битную), скачиваем и устанавливаем.

Для Mac OS. Открываем терминал и пишем:

Linux. Открываем терминал и вводим следующую команду.

Настройка

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

Открываем терминал (Linux и MacOS) или консоль (Windows) и вводим следующие команды.

Создание репозитория

Теперь вы готовы к работе с Git локально на компьютере.

Создадим наш первый репозиторий. Для этого пройдите в папку вашего проекта.

Теперь Git отслеживает изменения файлов вашего проекта. Но, так как вы только создали репозиторий в нем нет вашего кода. Для этого необходимо создать commit.

Отлично. Вы создали свой первый репозиторий и заполнили его первым commit.

Процесс работы с Git

Не стоит после каждого изменения файла делать commit. Чаще всего их создают, когда:

Создан новый функционал

Добавлен новый блок на верстке

Исправлены ошибки по коду

Вы завершили рабочий день и хотите сохранить код

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

Визуальный интерфейс

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

Но существуют и отдельные программы по работе с Git. Могу посоветовать эти:

Я не буду рассказывать как они работают. Предлагаю разобраться с этим самостоятельно.

Создаем свой первый проект и выкладываем на GitHub

Давайте разберемся как это сделать, с помощью среды разработки Visual Studio Code (VS Code).

Перед началом предлагаю зарегистрироваться на GitHub.

Создайте папку, где будет храниться ваш проект. Если такая папка уже есть, то создавать новую не надо.

После открываем VS Code .

Установите себе дополнительно анализаторы кода для JavaScript и PHP

Откройте вашу папку, которую создали ранее

После этого у вас появится вот такой интерфейс

Здесь будут располагаться все файлы вашего проекта

Здесь можно работать с Git-ом

Кнопка для создания нового файла

Кнопка для создания новой папки

Если ваш проект пустой, как у меня, то создайте новый файл и назовите его index.html . После этого откроется окно редактирование этого файла. Напишите в нем ! и нажмите кнопку Tab . Автоматически должен сгенерироваться скелет пустой HTML страницы. Не забудьте нажать ctrl+s чтобы файл сохранился.

Давайте теперь перейдем во вкладу для работы с Git-ом.

Откроется вот такое окно:

Кнопка для публикации нашего проекта на GitHub

После нажатия на кнопку 1 , появится всплывающее окно. Нужно выбрать второй вариант или там где присутствует фраза . public repository

Если вы хотите создать локальный репозиторий и опубликовать код в другой сервис, то необходимо нажать на кнопку Initialize Repository . После этого, вручную выбрать сервис куда публиковать.

После того, как выбрали «Опубликовать на GitHub публичный репозиторий» (пункт 2), программа предложит вам выбрать файлы, которые будут входить в первый commit. Проставляем галочки у всех файлов, если не проставлены и жмем ОК . Вас перекинет на сайт GitHub, где нужно будет подтвердить вход в аккаунт.

Вы создали и опубликовали репозиторий на GitHub.

Теперь сделаем изменения в коде и попробуем их снова опубликовать. Перейдите во вкладку с файлами, отредактируйте какой-нибудь файл, не забудьте нажать crtl+s (Windows) или cmd+s (MacOS), чтобы сохранить файл. Вернитесь обратно во вкладу управления Git.

Если посмотреть на значок вкладки Git, то можно увидеть цифру 1 в синем кружке. Она означает, сколько файлов у нас изменено и незакоммичено. Давайте его закоммитим и опубликуем:

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

Добавляем наш файл для будущего commit

Отправляем наш commit в GitHub

Поздравляю, вы научились создавать commit и отправлять его в GitHub!

Это первая вводная статья по утилите Git. Здесь мы рассмотрели:

Как его устанавливать

Как его настраивать

Как инициализировать репозиторий и создать commit через консоль

Как на примере VS Code, опубликовать свой код на GitHub

Забегая вперед, советую вам погуглить, как работают следующие команды:

P.S. Для облегчения обучения, оставлю вам ссылку на бесплатный тренажер по Git.

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

Интеграция Git с Visual Studio Code

Интеграция Git с Visual Studio Code

В веб-разработке Visual Studio Code (VS Code) стал одним из самых популярных редакторов. Он приобрел такую популярность благодаря множеству встроенных функций, среди которых есть и интеграция системы управления версиями Git. Использование Git через VS Code может сделать ваш рабочий процесс более эффективным и надежным.

В этом мануале мы расскажем, как использовать интеграцию системы управления версиями Git в VS Code.

Требования

  • Установка 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 означает, что файл неотслеживаемый (untracked) – этот новый или отредактированный файл еще не добавлен в репозиторий.

Теперь вы можете нажать кнопку с плюсом (+) рядом с файлом index.html, чтобы отслеживать файл по репозиторию.

После добавления файла в репозиторий буква U рядом с файлом изменится на A. Символ A (added) представляет новый файл, который был добавлен в репозиторий.

Чтобы зафиксировать изменения, введите сообщение о коммите в поле ввода в верхней части панели Source Control. Затем кликните значок check, чтобы отправить коммит.

После этого вы увидите, что у вас нет изменений, ожидающих проверки и сохранения.

Затем добавьте немного кода в файл index.html.

Для создания скелета HTML5 в VS Code можно использовать плагин Emmet, нажав клавиши !+Tab. Добавьте что-нибудь в <body>, например, заголовок <h1>, и сохраните его.

В панели Source Control вы увидите, что ваш файл изменился. Рядом с ним будет отображаться буква M (modified), которая указывает на отредактированный файл

Это изменение можно также сохранить через коммит.

Теперь, когда вы знакомы с панелью Source Control, мы можем переходить к индикаторам gutter.

2: Интерпретация индикаторов gutter

На этом этапе мы рассмотрим индикаторы gutter, или индикаторы желоба. Желоб – это узкая область, которая находится между индикатором строк и кодом.

Если ранее вы использовали сворачивание кода, то знаете, что значки разворачивания и сворачивания кода расположены именно в области желоба.

Начнем с внесения небольших изменений в файл index.html – можно, например, изменить контент в теге <h1>. После этого вы увидите синюю вертикальную метку в желобе напротив измененной строки. Вертикальная синяя метка означает, что соответствующая строка кода была отредактирована.

Теперь попробуйте удалить одну из строк в разделе <body> вашего файла index.html. Обратите внимание на красный треугольник в желобе. Красный треугольник указывает на строку или группу строк, которые были удалены.

Теперь перейдите к нижней части раздела <body> и добавьте туда новую строку кода. Обратите внимание на вертикальную зеленую полосу – она указывает на добавленную строку кода.

3: Определение отличий между версиями файла

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

Чтобы просмотреть отличия между версиями файла, откройте панель управления исходным кодом Source Control и дважды кликните на измененный файл. В нашем случае нужно дважды кликнуть на файл index.html. На экране появится сравнение текущей версии файла (слева) и его предыдущей версии (справа).

4: Работа с ветками

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

Чтобы создать нову ветку, кликните на имя текущей ветки. На экране должно появиться меню, дающее вам возможность создать новую ветку.

Для примера создайте новую ветку под названием test.

Теперь внесите изменения в свой файл index.html, чтобы обозначить, что вы находитесь в новой ветке: например добавьте текст «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 предоставляет возможность просматривать информацию состояния для текущей выбранной строки.

Название этого расширения может прозвучать пугающе, но Git Blame не предполагает, что вы будете буквально винить или стыдить кого-то в изменении кода: практичность расширения заключается в том, что оно позволяет выяснить, кому можно задать вопросы по определенным фрагментам кода.

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

Git History

Просматривать текущие изменения, отслеживать разницу между версиями и управлять ветками можно и с помощью встроенных функций VS Code, однако они не предоставляют подробной истории Git. Расширение Git History решает эту проблему.

Это расширение позволяет тщательно изучить историю файла, автора, ветки. Чтобы активировать окно Git History, нужно кликнуть на файл правой кнопкой мыши и выбрать Git: View File History.

Кроме того, вы можете сравнивать ветки и коммиты, создавать ветки из коммитов и многое другое.

Git Lens

Git Lens расширяет возможности Git, встроенные в Visual Studio Code. Этот плагин помогает с первого взгляда определить авторство кода с помощью аннотаций Git blame и линзы кода, перемещаться по репозиториям Git и исследовать их, получать ценную информацию с помощью команд сравнения и многое другое.

Расширение Git Lens – одно из самых популярных и мощных. В большинстве случаев его функциональность может заменить каждое из двух предыдущих расширений.

Получить информацию, как в Git Blame, можно справа от строки, над которой вы сейчас работаете: над ней появляется небольшое сообщение, из которого становится известно, кто и когда внес изменение и отправил коммит. При наведении курсора на это сообщение появляется дополнительная информация: изменение кода, временная метка времени и т.п.

Это расширение предоставляет множество функций, позволяющих получить историю Git, в том числе легкий доступ к множеству опций (отображение истории файлов, просмотр различий между версиями и многое другое). Чтобы открыть эти параметры, вы можете кликнуть на текст в строке состояния (он содержит информацию об авторе, который редактировал строку кода, и о времени последней редакции).

Это расширение обладает множеством функций, и вам, вероятно, потребуется время, чтобы разобраться со всеми ними.

Заключение

В этом мануале вы узнали, как использовать интеграцию системы управления версиями Git с VS Code.

VS Code «из коробки» предлагает многие функции, для которых ранее требовалась загрузка отдельного инструмента.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *