Главная страница » Как установить git в vs code

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

  • автор:

Introduction to Git in VS Code

Want to easily manage your source code and collaborate with others? Git and GitHub are the tools you need! And with Visual Studio Code, you can set up and use them in a snap. Even if you’re a beginner, VS Code’s user-friendly interface guides you through common Git actions like pushing and pulling code, creating and merging branches, and committing code changes. And if you’re a pro, you’ll love the ability to perform Git actions directly within the editor, saving you time and effort compared to using the Git command line. Plus, the seamless workflow between VS Code and Git means you can stay in your editor and get more done.

Set up Git in VS Code

To use Git and GitHub in VS Code, first make sure you have Git installed on your computer. If Git is missing, the Source Control view shows instructions on how to install it. Make sure to restart VS Code afterwards.

Additionally you can sign into VS Code with your GitHub account in the Accounts menu in the lower right of the Activity bar to enables additional features like Settings Sync, but also cloning and publishing repositories from GitHub.

Open a Git repository

VS Code provides several ways to get started in a Git repository, from local to remote cloud-powered environments like GitHub Codespaces.

Clone a repository locally

Screenshot of the Clone Repository quick prompt, searching for repositories with the name vscode

To clone a repository from GitHub, execute the Git: Clone command or select the Clone Repository button in the Source Control view. If you clone from GitHub, VS Code will prompt you to authenticate with GitHub. This allows you to search all available repositories and clone private repositories. For other Git providers, enter the repository URL and select Clone and pick a folder. VS Code opens the folder once the repository is cloned on your local machine.

Initialize a repository in a local folder

To initialize a new local repository, pick an existing or new folder on your computer and open it in VS Code. In the Source Control view, select the Initialize Repository button. This creates a new Git repository in the current folder, allowing you to start tracking code changes.

Publish local repository to GitHub

Once you have a local Git repository set up, you can publish it to GitHub. This will create a new repository on your GitHub account, and push your local code to the remote repository. Having your source code on a remote repository is a great way to back up your code, collaborate with others, and automate your workflow with GitHub Actions.

Source Control view for a workspace not under Git source control will offer to Initialize a Git repo or Publish to GitHub

Use the Publish to GitHub command button in the Source Control view. You can then choose a name and description for the repository, and whether to make it public or private. Once the repository has been created, VS Code will push your local code to the remote repository. Your code is now backed up on GitHub, and you can start collaborating with others with commits and pull requests.

Open a GitHub repository in a codespace

GitHub Codespaces let you open a GitHub repository in a full configured cloud-based development environment, allowing you to develop in a browser without having to install any software on your local computer. GitHub Codespaces allows free usage for individuals, which makes it easy to get started working on open source projects.

Install the GitHub Codespaces extension into VS Code and sign in with GitHub. Run the Codespaces: Create New Codespace command and pick the repository and branch you want to open. The new codespace will open in a new window.

Creating a codespace from a repo within VS Code Desktop

Alternatively, you can also start with a template from the GitHub’s Codespaces site. If you already have a codespace open in your browser, you can open it in your VS Code Desktop by running the Codespaces: Open in VS Code Desktop command. You can learn more about GitHub Codespaces, including customization such as forwarding ports, in the Developing in a codespace documentation.

Open a GitHub repository remotely

VS Code’s remote repository support allows you to browse and edit a GitHub repository without cloning it to your local computer. This is useful for quickly making changes to a remote repository without having to clone the entire codebase to your machine.

First install the GitHub Repositories extension. Run the command Remote Repositories: Open Remote Repository. or use the Open Remote Repository button the Explorer view. Search and select the GitHub repository that you want to open.

Remote Repositories opening a remote GitHub repo, pull request or Azure repo

Tip: If you need to execute code or run terminal commands, you can seamlessly switch from a remote repository to a codespace with the command Continue Working on.

Staging and committing code changes

Once you have a Git repository set up, you can start tracking code changes by staging and committing your newly created and edited code.

Source Control view with one file staged and other changes, a diff showing in the editor that highlights the changes

Tip: Commit your changes early and often. This will make it easier to revert back to previous versions of your code if needed.

To stage a file, select the + (plus) icon next to the file in the Source Control view. This will add the file to the Staged Changes section, indicating that it will be included in the next commit. Staged changes can also be discarded by selecting the (minus) icon next to the file.

To commit your staged changes, type a commit message in the upper text box and select the Commit button. This saves your changes to the local Git repository, allowing you to revert to previous versions of your code if needed. You can navigate through and review all local file changes and commits in the Timeline view available in the bottom of the Explorer.

Timeline view with one item selected and its change being shown in the editor

Pushing and pulling remote changes

Once you have made commits to your local Git repository, you can push them to the remote repository. The Sync Changes button indicates how many commits are going to be pushed and pulled. Selecting the Sync Changes button downloads (pull) any new remote commits and uploads (push) new local commits to the remote repository.

Sync button with one change to push

Tip: You can enable the Git: Autofetch setting to always get an up-to-date remote commit indicator.

Push and pull can also be performed individually by using their respective commands.

Using branches

In Git, branches allow you to work on multiple versions of your codebase simultaneously. This is useful for experimenting with new features or making large code changes without affecting the main codebase.

Branch indicator in the Status bar

The branch indicator in the Status bar shows the current branch and lets you switch to new and existing branches. To create a new branch, select the branch indicator and choose to create it from the current branch or another local one. Type a name for the new branch, and confirm. VS Code creates a new branch and switches to it, allowing you to make changes to your code without affecting the main branch.

Tip: If you use the GitHub Pull Requests and Issues extension, you can create a branch directly from an issue, which gets you started working in a new local branch and automatically prefills the pull request for you.

To push the branch to the remote repository, select Publish Branch in the Source Control view. This will create a new branch on the remote repository, allowing you to collaborate with others in that branch.

Creating and reviewing GitHub pull requests

In Git and GitHub, pull requests (PRs) are a way for collaborators to review and merge code changes from separate branches into the main branch. This allows teams to review and approve code changes before they are incorporated into the main codebase, ensuring that only high-quality changes are merged.

To use pull requests in VS Code, you need to install the GitHub Pull Requests and Issues extension. This extension adds PR and issue tracking functionality to VS Code, allowing you to create, review, and merge PRs from within the editor.

To create a PR, make sure you are on a separate branch from the main branch, and push your code changes to the remote repository. In the Source Control view, select the Create Pull Request button. This will open the PR creation form, where you can enter a title and description for the PR, and choose which branch to merge the changes into. Select Create to create the PR.

To review a PR, select the Review Pull Request button in the Source Control view, and select the PR you want to review. This will open the PR in a new editor window, where you can review the code changes and leave comments. Once you are satisfied with the code changes, you can select the Merge button to merge the PR into the targeted branch.

Learn more about pull requests in VS Code’s GitHub documentation.

Using Git in the built-in terminal

As all Git state is kept in the local repository, you can easily switch between VS Code’s UI, the built-in terminal, or external tools like GitHub Desktop. You can also set up VS Code as your default Git editor, allowing you to use VS Code to edit commit messages and other Git-related files.

Git Bash on Windows

Git Bash is a popular shell environment for Windows that provides a Unix-like command-line interface for working with Git and other command-line tools. Visual Studio Code’s integrated terminal supports Git Bash as a shell, allowing you to seamlessly integrate Git Bash into your development workflow. Installing Git on your Windows machine will also install Git Bash, if it wasn’t deselected during the installation steps.

Selecting Git Bash as shell in Visual Studio Code

Start by opening View > Terminal ( ⌃` (Windows, Linux Ctrl+` ) ). Click on the dropdown arrow next to the + icon in the terminal panel to pick a new shell to open. If Git Bash is installed, it will be shown in the list. You can toggle between different terminals and shells in the Terminal sidebar. With Git Bash configured in Visual Studio Code, you can now use all of your favorite Git commands directly from the terminal in your code editor.

If you want to set Git Bash as your default shell, open the Terminal dropdown (next to the + icon) and select Select Default Shell. This will open a list of available shells, including Git Bash. Selecting Git Bash will set it as your default shell, and all future terminals will be opened with Git Bash. More advanced tips are available in the terminal documentation.

Tutorial #1 — Git and Visual Studio Code Setup

Every big software project requires a version control system to facilitate working on different modules and versions by different teams. Git is the most popular choice when it comes to source control management although there are other alternatives like Fossil, SVN. When it comes to text-editors, we prefer Visual Studio Code, as it is a perfect blend of lightweight editors like Sublime, additionally supporting a wide variety of plugins that makes you feel almost like using an IDE. So, without further ado, let’s hop on!!

Step 01: Git Installation and Set-up

Download and Install Git from the official website according to your OS platform. Follow the recommended choices during installation and you should be fine. Git has a variety of configuration options which one might need to tweak in order to get it working. e.g. Most of the time corporations use proxy-servers as middle-ware servers in their basic internet connections. To get git working in a proxy environment, one needs to set global proxy settings as:

Or, one can edit the global gitconfig file, present in different platforms as:

Just add the following lines to get it working in a proxy environment:

There are variety of other config options which you can tangle with and can be found here.

Step 02: Install a Git Desktop Client

Git is a pure command-line utility. It quickly becomes a hassle when one needs to perform complex operations such as resolving merge conflicts, branching, rebasing etc. For easier management, git desktop clients should be used. We recommend Gitkraken as it is well-maintained and comes for both Windows and Ubuntu. Download from here according to your platform.

Step 03: Choosing Web-based Repository Hosting Service (Bitbucket or Github)

Both Bitbucket and Github are great choices for storing code-base remotely. Github is a more popular choice amongst developers, however Bitbucket fares well in all the necessary features one needs for source control management. One feature that differentiates between the two is their approach in providing private repositories. Bitbucket offers free private repos, however Github has paid subscription for private repos. If you are a student, you can get away with private repos for your project via the Github Student Developer Pack. Still not sure. check out more differences between the two here.

Step 04: Visual Studio Code Setup

Download and Install Visual Studio Code from here. Follow the recommended choices during installation. The power of VS Code lies in it’s simplicity and the number of plugins. Some of the extensions we use are:

  • GitLens
  • Sublime Text KeyMap
  • Python & Pylint (for syntax highlighting & indentation)

VS Code has an active community and help pages. So, almost all common problems and issues are addressed and solved. We would like to discuss about GitLens plugin a bit more. In some cases, one might feel Desktop clients like Gitkraken an extra heavy software running slowing things down.

Gitlens in VS Code is a great lightweight alternative that can perform all basic functionalities (pull, fetch, stash, commit, push, merge-conflict resolution). So, one can get away without installing any Desktop Client at all.

We will be back with python virtual environment and pip packages setup.

For Regular Updates and other blogs of the this tutorial series. You may Follow — React DJ Facebook Page

Our series of tutorials are currently organized at — srplabs.in

For Introduction of the Tutorial Series You may read—Building Practical Web Applications with React & Django

�� Read this story later in Journal.

�� Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >

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 в Visual Studio Code

Использование интеграции Git в Visual Studio Code

Редактор 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 (иконка выглядит как развилка дороги) в левой панели:

Иконка Source Control

Затем нажмите кнопку Open Folder:

Снимок экрана с кнопкой Open Folder

При нажатии кнопки откроется проводник файлов, где будет открыт текущий каталог. Выберите предпочитаемый каталог проекта и нажмите Open.

Затем нажмите Initialize Repository:

Снимок экрана с кнопкой инициализации репозитория Initialize Repository

Если теперь вы посмотрите на свою файловую систему, вы увидите, что она содержит каталог .git . Чтобы сделать это, используйте терминал для перехода в каталог проекта и вывода его содержимого:

Вы увидите созданный каталог .git :

Это означает, что репозиторий инициализирован, и теперь вам следует добавить в него файл index.html .

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

Снимок экрана с изображением неотслеживаемого файла, обозначенного буквой U

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

После этого рядом с файлом появится буква A. A обозначает новый файл, который был добавлен в репозиторий.

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

Снимок экрана с изображением добавленного файла, помеченного буквой A, и команды отправки

После этого вы увидите, что несохраненных изменений нет.

Теперь добавьте немного содержания в файл index.html .

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

На панели исходного кода вы увидите, что ваш файл изменился. Рядом с именем файла появится буква M, означающая, что файл изменен:

Снимок измененного файла, обозначенного буквой M

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

Теперь вы познакомились с работой через панель контроля исходного кода, и мы переходим к интерпретации показателей gutter.

Шаг 2 — Интерпретация показателей Gutter

На этом шаге мы рассмотрим концепцию Gutter («Желоб») в VS Code. Gutter — это небольшая область справа от номера строки.

Если ранее вы использовали сворачивание кода, то в области Gutter находятся иконки «Свернуть» и «Развернуть».

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

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

Теперь добавьте новую строку в конец раздела <body> и обратите внимание на зеленую полосу. Вертикальная зеленая полоса обозначает добавленную строку кода.

В этом примере описаны индикаторы области Gutter для случаев изменения, удаления и добавления строки:

Снимок экрана с примерами трех индикаторов области Gutter

Шаг 3 — Просмотр отличий файлов

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

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

В этом примере мы видим, что в текущей версии добавлена строка:

Снимок разделенного экрана для сравнения версий

Шаг 4 — Работа с ветвлением

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

Индикатор ветви в нижней панели VS Code с именем: master

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

Диалог создания новой ветви

Создайте новую ветвь с именем 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 Blame на нижней панели инструментов

Git History

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

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

Результаты работы расширения Git History

Также вы сможете сравнивать ветви и записанные в репозиторий версии, создавать ветви из записанных версий и т. д.

Git Lens

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

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

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

Функционал Git Blame в Git Lens

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

При этом откроется следующее окно:

Функционал Git History в Git Lens

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

Заключение

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

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

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