Work with git on windows

Содержание
  1. Git Guides
  2. Get started with git and GitHub
  3. Get started using Git on Windows Subsystem for Linux
  4. Git can be installed on Windows AND on WSL
  5. Installing Git
  6. Git config file setup
  7. Git Credential Manager setup
  8. Adding a Git Ignore file
  9. Git and VS Code
  10. Git line endings
  11. Интерфейс GIT в Visual Studio Git experience in Visual Studio
  12. Использование GIT в Visual Studio How to use Git in Visual Studio
  13. Создание репозитория GIT Create a new Git repository
  14. Клонирование существующего репозитория GIT Clone an existing Git repository
  15. Открытие существующего локального репозитория Open an existing local repository
  16. Просмотр файлов в обозревателе решений View files in Solution Explorer
  17. Окно «Изменения GIT» Git Changes window
  18. Выбор существующей ветви Select an existing branch
  19. Создание ветви Create a new branch
  20. Окно «Репозиторий GIT» Git Repository window
  21. Управление ветвями Manage branches
  22. Входящие и исходящие фиксации Incoming and outgoing commits
  23. Сведения о фиксации Commit Details
  24. Разрешение конфликтов слияния Handle merge conflicts
  25. Редактор слияния The Merge Editor
  26. Настройка параметров GIT Personalize your Git settings
  27. Использование всех возможностей Team Explorer в Visual Studio How to use the full Team Explorer experience in Visual Studio
  28. Что дальше? What’s next

Git Guides

How to install Git on any OS

Git can be installed on the most common operating systems like Windows, Mac, and Linux. In fact, Git comes installed by default on most Mac and Linux machines!

Checking for Git

To see if you already have Git installed, open up your terminal application.

  • If you’re on a Mac, look for a command prompt application called «Terminal».
  • If you’re on a Windows machine, open the windows command prompt or «Git Bash».

Once you’ve opened your terminal application, type git version . The output will either tell you which version of Git is installed, or it will alert you that git is an unknown command. If it’s an unknown command, read further and find out how to install Git.

Install Git Using GitHub Desktop

Installing GitHub Desktop will also install the latest version of Git if you don’t already have it. With GitHub Desktop, you get a command line version of Git with a robust GUI. Regardless of if you have Git installed or not, GitHub Desktop offers a simple collaboration tool for Git. You can learn more here.

Install Git on Windows

  1. Navigate to the latest Git for Windows installer and download the latest version.
  2. Once the installer has started, follow the instructions as provided in the Git Setup wizard screen until the installation is complete.
  3. Open the windows command prompt (or Git Bash if you selected not to use the standard Git Windows Command Prompt during the Git installation).
  4. Type git version to verify Git was installed.

Note: git-scm is a popular and recommended resource for downloading Git for Windows. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git included with the recommended command prompt, Git Bash . The download source is the same Git for Windows installer as referenced in the steps above.

Install Git on Mac

Most versions of MacOS will already have Git installed, and you can activate it through the terminal with git version . However, if you don’t have Git installed for whatever reason, you can install the latest version of Git using one of several popular methods as listed below:

Install Git From an Installer

  1. Navigate to the latest macOS Git Installer and download the latest version.
  2. Once the installer has started, follow the instructions as provided until the installation is complete.
  3. Open the command prompt «terminal» and type git version to verify Git was installed.

Note: git-scm is a popular and recommended resource for downloading Git on a Mac. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git. The download source is the same macOS Git Installer as referenced in the steps above.

Install Git from Homebrew

Homebrew is a popular package manager for macOS. If you already have Homwbrew installed, you can follow the below steps to install Git:

  1. Open up a terminal window and install Git using the following command: brew install git .
  2. Once the command output has completed, you can verify the installation by typing: git version .

Install Git on Linux

Fun fact: Git was originally developed to version the Linux operating system! So, it only makes sense that it is easy to configure to run on Linux.

You can install Git on Linux through the package management tool that comes with your distribution.

  1. Git packages are available using apt .
  2. It’s a good idea to make sure you’re running the latest version. To do so, Navigate to your command prompt shell and run the following command to make sure everything is up-to-date: sudo apt-get update .
  3. To install Git, run the following command: sudo apt-get install git-all .
  4. Once the command output has completed, you can verify the installation by typing: git version .
  1. Git packages are available using dnf .
  2. To install Git, navigate to your command prompt shell and run the following command: sudo dnf install git-all .
  3. Once the command output has completed, you can verify the installation by typing: git version .

Note: You can download the proper Git versions and read more about how to install on specific Linux systems, like installing Git on Ubuntu or Fedora, in git-scm’s documentation.

Other Methods of Installing Git

Looking to install Git via the source code? Learn more here.

Get started with git and GitHub

Review code, manage projects, and build software alongside 40 million developers.

Get started using Git on Windows Subsystem for Linux

Git is the most commonly used version control system. With Git, you can track changes you make to files, so you have a record of what has been done, and have the ability to revert to earlier versions of the files if needed. Git also makes collaboration easier, allowing changes by multiple people to all be merged into one source.

Git can be installed on Windows AND on WSL

An important consideration: when you enable WSL and install a Linux distribution, you are installing a new file system, separated from the Windows NTFS C:\ drive on your machine. In Linux, drives are not given letters. They are given mount points. The root of your file system / is the mount point of your root partition, or folder, in the case of WSL. Not everything under / is the same drive. For example, on my laptop, I’ve installed two version of Ubuntu (20.04 and 18.04), as well as Debian. If I open those distributions, select the home directory with the command cd

, and then enter the command explorer.exe . , Windows File Explorer will open and show me the directory path for that distribution.

Linux distro Windows Path to access home folder
Ubuntu 20.04 \\wsl$\Ubuntu-20.04\home\username
Ubuntu 18.04 \\wsl$\Ubuntu-18.04\home\username
Debian \\wsl$\Debian\home\username
Windows PowerShell C:\Users\username

If you are seeking to access the Windows file directory from your WSL distribution command line, instead of C:\Users\username , the directory would be accessed using /mnt/c/Users/username , because the Linux distribution views your Windows file system as a mounted drive.

You will need to install Git on each file system that you intend to use it with.

Installing Git

Git comes already installed with most of the Windows Subsystem for Linux distributions, however, you may want to update to the latest version. You also will need to set up your git config file.

To install Git, see the Git Download for Linux site. Each Linux distribution has their own package manager and install command.

For the latest stable Git version in Ubuntu/Debian, enter the command:

You also may want to install Git for Windows if you haven’t already.

Git config file setup

To set up your Git config file, open a command line for the distribution you’re working in and set your name with this command (replacing «Your Name» with your Git username):

Set your email with this command (replacing «youremail@domain.com» with the email you use on your Git account):

If you don’t yet have a Git account, you can sign-up for one on GitHub. If you’ve never worked with Git before, GitHub Guides can help you get started. If you need to edit your git config, you can do so with a built-in text editor like nano: nano

Git Credential Manager setup

Git Credential Manager enables you to authenticate a remote Git server, even if you have a complex authentication pattern like two-factor authentication, Azure Active Directory, or using SSH remote URLs that require an SSH key password for every git push. Git Credential Manager integrates into the authentication flow for services like GitHub and, once you’re authenticated to your hosting provider, requests a new authentication token. It then stores the token securely in the Windows Credential Manager. After the first time, you can use git to talk to your hosting provider without needing to re-authenticate. It will just access the token in the Windows Credential Manager.

To set up Git Credential Manager for use with a WSL distribution, open your distribution and enter this command:

Now any git operation you perform within your WSL distribution will use the credential manager. If you already have credentials cached for a host, it will access them from the credential manager. If not, you’ll receive a dialog response requesting your credentials, even if you’re in a Linux console.

If you are using a GPG key for code signing security, you may need to associate your GPG key with your GitHub email.

Adding a Git Ignore file

We recommend adding a .gitignore file to your projects. GitHub offers a collection of useful .gitignore templates with recommended .gitignore file setups organized according to your use-case. For example, here is GitHub’s default gitignore template for a Node.js project.

If you choose to create a new repo using the GitHub website, there are check boxes available to initialize your repo with a README file, .gitignore file set up for your specific project type, and options to add a license if you need one.

Git and VS Code

Visual Studio Code comes with built-in support for Git, including a source control tab that will show your changes and handle a variety of git commands for you. Learn more about VS Code’s Git support.

Git line endings

If you are working with the same repository folder between Windows, WSL, or a container, be sure to set up consistent line endings.

Since Windows and Linux use different default line endings, Git may report a large number of modified files that have no differences aside from their line endings. To prevent this from happening, you can disable line ending conversion using a .gitattributes file or globally on the Windows side. See this VS Code doc about resolving Git line ending issues.

Интерфейс GIT в Visual Studio Git experience in Visual Studio

Теперь GIT является интерфейсом системы управления версиями по умолчанию в Visual Studio 2019. Git is now the default version control experience in Visual Studio 2019. Начиная с версии 16.6 мы работаем над созданием набора функций на основе ваших отзывов. Since version 16.6, we’ve worked on building out the feature set and iterating on it based on your feedback. Новый интерфейс Git по умолчанию включен для всех пользователей, имеющих выпуск версии 16.8. The new Git experience is turned on by default for everyone with the release of version 16.8.

GIT — это наиболее широко используемая современная система управления версиями, которая может быть полезна как профессиональным разработчиком, так и только начинающим изучать программирование. Git is the most widely used modern version control system, so whether you’re a professional developer or if you’re learning how to code, Git can be very useful to you. Если вы не знакомы с GIT, можно начать с веб-сайта https://git-scm.com/. If you are new to Git, the https://git-scm.com/ website is a good place to start. На нем вы найдете памятки, популярную электронную книгу и видеоматериалы по основам GIT. There, you’ll find cheat sheets, a popular online book, and Git Basics videos.

Использование GIT в Visual Studio How to use Git in Visual Studio

Мы подробно расскажем вам о том, как использовать новый интерфейс Git в Visual Studio 2019. Однако если вы хотите ознакомиться с кратким обзором, посмотрите следующее видео: We’ll walk you through how to use the new Git experience in Visual Studio 2019, but if you’d like to take a quick tour first, check out the following video:

Длительность видео: 05:27 мин. Video length: 5.27 minutes

Существует три способа начать использование Git в Visual Studio для повышения производительности: There are three ways to start using Git with Visual Studio to be more productive:

  • Открытие существующего репозитория GIT. Open an existing Git repository. Если у вас уже есть код на компьютере, его можно открыть с помощью пункта меню Файл >Открыть >Решение/проект (или Папка). Visual Studio автоматически определяет, имеется ли инициализированный репозиторий GIT. If your code is already on your machine, you can open it by using File >Open >Project/Solution (or Folder) and Visual Studio automatically detects if it has an initialized Git repository.
  • Создание нового репозитория GIT. Create a new Git repository. Если ваш код не связан с GIT, можно создать новый репозиторий GIT. If your code is not associated with Git, you can create a new Git repository.
  • Клонирование существующего репозитория GIT. Clone an existing Git repository. Если код, с которым вы хотите работать, не находится на вашем компьютере, можно клонировать любые существующие удаленные репозитории. If the code that you would like to work on is not on your machine, you can clone any existing remote repositories.

Начиная с версии 16.8 Visual Studio 2019 включает полностью интегрированный интерфейс для работы с учетными записями GitHub. Starting also with version 16.8, Visual Studio 2019 includes a fully integrated GitHub account experience. Теперь вы можете добавить в цепочку ключей учетные записи GitHub и GitHub Enterprise. You can now add both GitHub and GitHub Enterprise accounts to your keychain. Вы сможете добавлять и использовать их так же, как и учетные записи Майкрософт. Это позволит упростить доступ к ресурсам GitHub в Visual Studio. You’ll be able to add and leverage them just as you do with Microsoft accounts, which means that you’ll have an easier time accessing your GitHub resources across Visual Studio. Дополнительные сведения см. на странице Работа с учетными записями GitHub в Visual Studio. For more information, see the Work with GitHub accounts in Visual Studio page.

Создание репозитория GIT Create a new Git repository

Если ваш код не связан с GIT, можно начать с создания нового репозитория GIT. If your code is not associated with Git, you can start by creating a new Git repository. Для этого в строке меню выберите GIT > Создать репозиторий GIT. To do so, select Git > Create Git Repository from the menu bar. Затем в диалоговом окне Создание репозитория GIT введите свои данные. Then, in the Create a Git repository dialog box, enter your information.

С помощью диалогового окна Создание репозитория GIT можно легко отправить новый репозиторий в GitHub. The Create a Git repository dialog box makes it easy to push your new repository to GitHub. По умолчанию новый репозиторий является частным. Это означает, что доступ к нему есть только у вас. By default, your new repository is private, which means that you are the only one who can access it. Если снять соответствующий флажок, репозиторий будет общедоступным. Это означает, что любой пользователь в GitHub сможет его просмотреть. If you uncheck the box, your repository will be public, which means that anyone on GitHub can view it.

Независимо от того, является ли репозиторий общедоступным или частным, лучше создать удаленную резервную копию кода, которая будет безопасно храниться в GitHub, даже если вы работаете сами по себе. Whether your repository is public or private, it’s best to have a remote backup of your code stored securely on GitHub even if you are not working with a team. Это также позволит вам получать доступ к коду с любого компьютера. This also makes your code available to you no matter what computer you’re using.

Вы можете создать исключительно локальный репозиторий GIT, выбрав параметр Только локальный. You can choose to create a local-only Git repository by using the Local only option. Вы также можете связать локальный проект с любым существующим пустым удаленным репозиторием, размещенным в Azure DevOps или у любого другого поставщика Git, с помощью параметра Существующий удаленный репозиторий. Or, you can link your local project with an existing empty remote repository on Azure DevOps or any other Git provider by using the Existing Remote option.

Клонирование существующего репозитория GIT Clone an existing Git repository

В Visual Studio процесс клонирования прост. Visual Studio includes a straightforward clone experience. Если вы знаете URL-адрес репозитория, который нужно клонировать, можно вставить его в разделе Расположение репозитория, а затем выбрать место на диске, в которое будет клонирован репозиторий. If you know the URL of the repository that you would like to clone, you can paste the URL in the Repository location section and then choose the disk location you would like Visual Studio to clone to.

Если вы не знаете URL-адрес репозитория, в Visual Studio можно легко перейти к существующему репозиторию GitHub или Azure DevOps и выбрать его. If you don’t know the repository URL, Visual Studio makes it easy to browse to and then clone your existing GitHub or Azure DevOps repository.

Открытие существующего локального репозитория Open an existing local repository

После клонирования или создания репозитория GIT Visual Studio обнаружит его и добавит в список Локальные репозитории в меню GIT. After you’ve cloned a repository or created one, Visual Studio detects the Git repository and adds it to your list of Local Repositories in the Git menu. В нем можно быстро открывать репозитории GIT и переключаться между ними. From here, you can quickly access and switch between your Git repositories.

Просмотр файлов в обозревателе решений View files in Solution Explorer

При клонировании репозитория или открытии локального репозитория Visual Studio переключается в этот контекст GIT, сохраняя и закрывая все ранее открытые решения и проекты. When you clone a repository or open a local repository, Visual Studio switches you into that Git context by saving and closing any previously open solutions and projects. Обозреватель решений загружает папку в корне репозитория GIT и проверяет дерево каталогов на наличие файлов представлений. Solution Explorer loads the folder at the root of the Git repository and scans the directory tree for any View files. К ним относятся такие файлы, как CMakeLists.txt или файлы с расширением SLN. These include files such as CMakeLists.txt or those with the .sln file extension.

Visual Studio настраивает представление в зависимости от файла представления, загруженного в обозревателе решений. Visual Studio adjusts its View based on which View file you load in Solution Explorer:

  • При клонировании репозитория, содержащего один SLN-файл, обозреватель решений напрямую загружает это решение. If you clone a repository that contains a single .sln file, then Solution Explorer directly loads that solution for you.
  • Если обозреватель решений не обнаруживает файлов SLN в репозитории, по умолчанию он загружает представление папки. If Solution Explorer doesn’t detect any .sln files in your repository, then by default it loads Folder View.
  • Если репозиторий содержит несколько файлов SLN, то обозреватель решений выводит список доступных представлений для выбора. If your repository has more than one .sln file, then Solution Explorer shows you the list of available Views for you to choose from.

Переключаться между текущим представлением и списком представлений можно с помощью кнопки Переключить представления на панели инструментов обозревателя решений. You can toggle between the currently open View and the list of Views by using the Switch Views button in the Solution Explorer toolbar.

Окно «Изменения GIT» Git Changes window

GIT отслеживает изменения файлов в репозитории в процессе работы и разделяет файлы на три категории. Git tracks file changes in your repo as you work, and separates the files in your repo into three categories. Это те же изменения, которые отображаются при вводе команды git status в командной строке. These changes are equivalent to what you would see when you enter the git status command in the command line:

  • Файлы без изменений: эти файлы не были изменены с момента последней фиксации. Unmodified files: These files haven’t changed since your last commit.
  • Измененные файлы: эти файлы изменились с момента последней фиксации, но еще не были подготовлены для следующей фиксации. Modified files: These files have changes since your last commit, but you haven’t yet staged them for the next commit.
  • Промежуточные файлы: эти файлы содержат изменения, которые будут добавлены в следующую фиксацию. Staged files: These files have changes that will be added to the next commit.

В процессе работы Visual Studio отслеживает изменения в файлах проекта в разделе Изменения окна Изменения GIT. As you do your work, Visual Studio keeps track of the file changes to your project in the Changes section of the Git Changes window.

Когда вы будете готовы подготовить изменения, нажмите кнопку + (плюс) для каждого из файлов, которые необходимо подготовить, или щелкните файл правой кнопкой мыши и выберите пункт Промежуточно сохранить. When you are ready to stage changes, click the + (plus) button on each file you want to stage, or right-click a file and then select Stage. Можно также подготовить все измененные файлы одним щелчком мыши, используя кнопку «Промежуточно сохранить все» ( + ) в верхней части раздела Изменения. You can also stage all your modified files with one click by using the stage all + (plus) button at the top of the Changes section.

При подготовке изменения Visual Studio создает раздел Подготовленные изменения. When you stage a change, Visual Studio creates a Staged Changes section. Только изменения из раздела Подготовленные изменения добавляются к следующей фиксации, которую можно выполнить, выбрав команду Зафиксировать промежуточные. Only changes in the Staged Changes section are added to the next commit, which you can do by selecting Commit Staged. Эквивалентная команда для этого действия — git commit -m «Your commit message» . The equivalent command for this action is git commit -m «Your commit message» . Можно также отменить подготовку изменений, нажав кнопку (минус). Changes can also be unstaged by clicking the (minus) button. Эквивалентная команда для этого действия — git reset для отмены размещения одного файла или git reset для отмены размещения всех файлов в каталоге. The equivalent command for this action is git reset to unstage a single file or git reset to unstage all the files in a directory.

Кроме того, можно отказаться от подготовки измененных файлов, пропустив область подготовки. You can also choose not to stage your modified files by skipping the staging area. В этом случае Visual Studio позволяет зафиксировать изменения напрямую без предварительной подготовки. In this case, Visual Studio allows you to commit your changes directly without having to stage them. Просто введите сообщение о фиксации и выберите Зафиксировать все. Just enter your commit message and then select Commit All. Эквивалентная команда для этого действия — git commit -a . The equivalent command for this action is git commit -a .

Visual Studio также позволяет выполнить фиксацию и синхронизацию одним щелчком мыши с помощью ярлыков Зафиксировать все и отправить и Зафиксировать все и синхронизировать. Visual Studio also makes it easy to commit and sync with one click by using the Commit All and Push and Commit All and Sync shortcuts. Если дважды щелкнуть любой файл в разделе Изменения или Подготовленные изменения, то можно построчно сравнить измененную версию файла с неизмененной. When you double-click any file in the Changes and the Staged changes sections, you can see a line-by-line comparison with the unmodified version of the file.

Если вы подключены к репозиторию Azure DevOps, вы можете связать рабочий элемент Azure DevOps с фиксацией, используя символ #. You can associate an Azure DevOps work item with a commit by using the «#» character if you are connected to the Azure DevOps repository. Чтобы подключить репозиторий Azure DevOps, выберите Team Explorer > Управление подключениями. You can connect your Azure DevOps repository through Team Explorer > Manage Connections.

Выбор существующей ветви Select an existing branch

В Visual Studio текущая ветвь отображается в селекторе в верхней части окна Изменения GIT. Visual Studio displays the current branch in the selector at the top of the Git Changes window.

Текущая ветвь также доступна в строке состояния в правом нижнем углу интегрированной среды разработки Visual Studio. The current branch is also available in the status bar on the bottom-right corner of the Visual Studio IDE.

В обоих местах можно переключаться между имеющимися ветвями. From both locations, you can switch between existing branches.

Создание ветви Create a new branch

Можно также создать новую ветвь. You can also create a new branch. Эквивалентная команда для этого действия — git checkout -b
. The equivalent command for this action is git checkout -b
.

Чтобы создать ветвь, достаточно ввести ее имя и указать существующую ветвь, на основе которой будет создана данная. Creating a new branch is as simple as entering the branch name and basing it off an existing branch.

В качестве базовой можно выбрать существующую локальную или удаленную ветвь. You can choose an existing local or remote branch as the base. Если флажок Извлечь ветвь установлен, вы автоматически переключитесь на новую ветвь после ее создания. The Checkout branch checkbox automatically switches you to the newly created branch. Эквивалентная команда для этого действия — git checkout -b . The equivalent command for this action is git checkout -b .

Окно «Репозиторий GIT» Git Repository window

В Visual Studio имеется новое окно Репозиторий GIT, в котором представлены все сведения о репозитории, включая все ветви, удаленные репозитории и журналы фиксации. Visual Studio has a new Git Repository window, which is a consolidated view of all the details in your repository, including all of the branches, remotes, and commit histories. Открыть это окно можно из меню GIT или Вид либо непосредственно из строки состояния. You can access this window directly from either Git or View on the menu bar or from the status bar.

Управление ветвями Manage branches

При выборе в меню GIT пункта Управление ветвями отображается древовидное представление ветвей в окне Репозиторий GIT. When you select Manage Branches from the Git menu, you’ll see the branches tree-view in the Git Repository window. В левой области можно использовать контекстное меню для извлечения, создания, объединения ветвей, перемещения изменений из одной ветви в другую, отбора изменений и других действий. From the left pane, you can use the right-click context menu to checkout branches, create new branches, merge, rebase, cherry-pick, and more. Щелкнув ветвь, можно просмотреть ее журнал фиксаций в правой области. When you click the branch, you can see a preview of its commit history in the right pane.

Входящие и исходящие фиксации Incoming and outgoing commits

При принесении ветви в окне Изменения GIT под раскрывающемся списком ветвей отображается индикатор, который показывает количество фиксаций, которые не были вытянуты из удаленной ветви. When you fetch a branch, the Git Changes window has an indicator under the branch drop-down, which displays the number of unpulled commits from the remote branch. Он также показывает число локальных фиксаций, которые не были отправлены. This indicator also shows you the number of unpushed local commits.

Индикатор также является ссылкой, по которой можно перейти к журналу фиксаций этой ветви в окне Репозиторий GIT. The indicator also functions as a link to take you to the commit history of that branch in the Git Repository window. В начале журнала теперь отображаются сведения об этих входящих и исходящих фиксациях. The top of the history now displays the details of these incoming and outgoing commits. Здесь можно также вытянуть или отправить фиксации. From here, you can also decide to Pull or Push the commits.

Сведения о фиксации Commit Details

Если дважды щелкнуть фиксацию, в Visual Studio откроются сведения о ней в отдельном окне инструментов. When you double-click a Commit, Visual Studio opens its details in a separate tool window. Здесь можно отменить фиксацию, сбросить ее, исправить сообщение о фиксации или создать тег для нее. From here you can revert the commit, reset the commit, amend the commit message, or create a tag on the commit. Если щелкнуть измененный файл в фиксации, в Visual Studio откроется инструмент сравнения, в котором рядом друг с другом показаны фиксация и ее предок. When you click a changed file in the commit, Visual Studio opens the side-by-side Diff view of the commit and its parent.

Разрешение конфликтов слияния Handle merge conflicts

Во время слияния могут возникать конфликты, если два разработчика изменяют одни и те же строки в файле и GIT неизвестно, какой вариант правильный. Conflicts can occur during a merge if two developers modify the same lines in a file and Git doesn’t automatically know which is correct. В этом случае GIT прерывает слияние и сообщает о конфликтном состоянии. Git halts the merge and informs you that you are in a conflicted state.

В Visual Studio можно легко выявлять и устранять конфликты слияния. Visual Studio makes it easy to identify and resolve a merge conflict. Во-первых, в верхней части окна Репозиторий GIT имеется золотистая информационная панель. First, the Git Repository window shows a gold info bar at the top of the window.

В окне Изменения GIT также выводится сообщение Слияние выполняется с конфликтами, под которым в отдельном разделе указываются файлы, слияние которых не было выполнено. The Git Changes window also displays a ‘Merge is in progress with conflicts’ message, with the unmerged files in their separate section below it.

Но если ни одно из этих окон не открыто и вы переходите к файлу с конфликтами слияния, вам не придется искать следующий текст: But if you have neither of these windows open, and instead you go to the file that has merge conflicts, you won’t have to search for the following text:

Вместо этого в верхней части страницы в Visual Studio отображается золотистая информационная панель с сообщением о наличии конфликтов в открытом файле. Instead, Visual Studio displays a gold info bar on the top of the page that indicates that the opened file has conflicts. Щелкните ссылку, чтобы открыть редактор слияния. Then, you can click the link to open the Merge Editor.

Редактор слияния The Merge Editor

Редактор слияния в Visual Studio позволяет выполнять трехстороннее сравнение: в нем приводятся входящие изменения, текущие изменения и результат слияния. The Merge Editor in Visual Studio is a three-way merge tool that displays the incoming changes, your current changes, and the result of the merge. С помощью панели инструментов вверху редактора слияния можно переходить между конфликтами и просматривать результаты автоматического слияния в файле. You can use the tool bar at the top level of the Merge Editor to navigate between conflicts and auto-merged differences in the file.

Можно также использовать переключатели для отображения и скрытия различий, отображения и скрытия различий в словах и настройки макета. You can also use the toggles to show/hide differences, show/hide word differences, and customize the layout. Вверху с каждой стороны есть флажки, с помощью которых можно перенести все изменения с одной стороны на другую. There are checkboxes on the top of each side that you can use to take all the changes from one side or the other. Чтобы перенести отдельные изменения, можно установить флажки слева от конфликтующих строк с любой стороны. But to take individual changes, you can click the checkboxes to the left of the conflicting lines on either side. Завершив разрешение конфликтов, нажмите в редакторе слияния кнопку Принять слияние. Finally, when you finish resolving the conflicts, you can select the Accept Merge button in the Merge Editor. После этого нужно ввести сообщение о фиксации и зафиксировать изменения, чтобы завершить процесс разрешения. You then write a commit message and commit the changes to complete the resolution.

Настройка параметров GIT Personalize your Git settings

Чтобы настроить параметры GIT на уровне репозитория, а также на глобальном уровне, выберите в строке меню пункты GIT > Параметры или Сервис > Параметры > Управление исходным кодом. To personalize and customize your Git settings at a repository level as well as at a global level, go to either Git > Settings on the menu bar, or to Tools > Options > Source Control on the menu bar. Затем выберите нужные параметры. Then, choose the options you want.

Использование всех возможностей Team Explorer в Visual Studio How to use the full Team Explorer experience in Visual Studio

Новый интерфейс GIT — это система контроля версий по умолчанию в Visual Studio 2019 начиная с версии 16.8. The new Git experience is the default version control system in Visual Studio 2019 from version 16.8 onwards. Однако при желании этот интерфейс можно отключить. However, if you want to turn it off, you can. Чтобы вернуться в Team Explorer для Git, выберите Средства > Параметры > Среда > Функции предварительной версии и снимите флажок Новый пользовательский интерфейс Git. Go to Tools > Options > Environment > Preview Features and then toggle the New Git user experience checkbox, which will switch you back to Team Explorer for Git.

Что дальше? What’s next

Хотя новый интерфейс GIT теперь включен по умолчанию в Visual Studio 2019 версии 16.8, мы продолжаем добавлять новые функции для его совершенствования. While the new Git experience is now on by default in Visual Studio 2019 version 16.8, we continue to add new features to enhance the experience. Чтобы ознакомиться с новыми обновлениями для интерфейса GIT в предварительной версии, скачайте и установите ее со страницы Visual Studio Preview. If you’d like to check out new updates to the Git experience in a Preview release, you can download and install it from the Visual Studio Preview page.

Если у вас есть предложение, отправьте его нам. If you have a suggestion for us, please let us know! Мы будем рады вашему участию в работе над решением на портале Сообщества разработчиков. We appreciate the opportunity to engage with you on design decisions via the Developer Community portal.

Читайте также:  Кодовая таблица системе windows
Оцените статью