Как загрузить проект на github из visual studio 2019
В ней будет коротко рассмотрено что это за вещи, зачем нужны, и простой способ работы – из среды Visual Studio. То есть Bash или GitHub клиент использоваться не будут.
Внимание:
На Хабре уже есть похожая статья – [вот она]. В своей публикации я дополню слова Алексея и расскажу метод проще.
Для кого:
Статья направлена в помощь людям которые не работали с Git, GitHub, и хотят освоить в общих чертах как можно быстрее и без сложностей начать работу с ними.
О тексте:
Старался писать проще и с большим количеством скриншотов и пояснений. Ведь лучше, когда они есть чем, когда их нет и о чем-то приходится догадываться.
Итак, немного теории чтоб понять, что делать дальше:
- Visual Studio 2015 года или новее
- Подключение к интернету
- Несколько гигабайт памяти на жестком диске
Инструкция:
-
Переходим в меню Tools → Extensions and Updates → откроется вкладка Installed → если в расширениях отсутствует «GitHub Extension for Visual Studio» идем дальше, иначе перейдите к пункту следующему пункту инструкции → вкладка Online → ищем в поиске наше расширение → скачиваем и устанавливаем.
После, с GitHub копируем ссылку:
-
Может возникнуть вопрос – Что значат другие иконки?
Ответ:
Карандаш для того чтоб фиксировать изменения локально (commit). Используйте когда есть что сохранить, то есть код или файлы изменились.
Дополнительно:
Чтоб GitHub верно отображал русские комментарии (если есть) при просмотре кода через сайт нужно сделать следующее:
Cоветую всё-таки изучить Git Bash.
Я старался писать как можно понятнее, если что-то не так, то поправьте в комментариях!
На этом все. Спасибо за внимание!
В ней будет коротко рассмотрено что это за вещи, зачем нужны, и простой способ работы – из среды Visual Studio. То есть Bash или GitHub клиент использоваться не будут.
Внимание:
На Хабре уже есть похожая статья – [вот она]. В своей публикации я дополню слова Алексея и расскажу метод проще.
Для кого:
Статья направлена в помощь людям которые не работали с Git, GitHub, и хотят освоить в общих чертах как можно быстрее и без сложностей начать работу с ними.
О тексте:
Старался писать проще и с большим количеством скриншотов и пояснений. Ведь лучше, когда они есть чем, когда их нет и о чем-то приходится догадываться.
Итак, немного теории чтоб понять, что делать дальше:
- Visual Studio 2015 года или новее
- Подключение к интернету
- Несколько гигабайт памяти на жестком диске
Инструкция:
-
Переходим в меню Tools → Extensions and Updates → откроется вкладка Installed → если в расширениях отсутствует «GitHub Extension for Visual Studio» идем дальше, иначе перейдите к пункту следующему пункту инструкции → вкладка Online → ищем в поиске наше расширение → скачиваем и устанавливаем.
После, с GitHub копируем ссылку:
-
Может возникнуть вопрос – Что значат другие иконки?
Ответ:
Карандаш для того чтоб фиксировать изменения локально (commit). Используйте когда есть что сохранить, то есть код или файлы изменились.
Дополнительно:
Чтоб GitHub верно отображал русские комментарии (если есть) при просмотре кода через сайт нужно сделать следующее:
Cоветую всё-таки изучить Git Bash.
Я старался писать как можно понятнее, если что-то не так, то поправьте в комментариях!
На этом все. Спасибо за внимание!
Git и TFS: история дружбы
Git — распределенная система контроля версий, где каждый разработчик имеет копию всего репозитория, что означает отличную поддержку оффлайн-разработки. Еще у Git есть хорошая, понятная модель бранчинга, и разработчику не надо долго думать о том, как создавать локальные или приватные бранчи для удобства работы. В общем, с Git все хорошо, и на MSDN есть посвященный Git бранч.
Проект Git в Team Foundation Service
После регистрации в TFS на странице команд есть новая кнопка — New Team Project + Git. Пара кликов — и проект Git готов.
Собственно, на этом все. :) Но это — верхушка айсберга, внутри интеграция гораздо сложнее. Дальше — про то, как из Visual Studio подключиться и поманипулировать нашим Git-проектом.
Visual Studio и Git
Делаю сразу оговорку — Visual Studio — не замена существующему UI Git. Visual Studio может быть заменой, но чаще используется в совокупности с другими средствами. Если Git был создан внутри TFS, то у разработчика появляются некоторые фичи, пришедшие из TFS, например, Work Items, но VS спокойно работает с любыми локальными репозиториями и заслуженными Git-деятелями в лице GitHub и BitBucket.
Для подключения к Git-репозиторию достаточно нажать TEAM | Connect to Team Foundation Server.
Откроется Team Explorer. Как видите, у меня уже есть склонированный (с GitHub) репозиторий, и тут же — репозиторий TFS. Для клонирования нового репозитория Git можно нажать Clone и ввести данные подключения.
Для подключения аккаунта Visual Studio Online нажмем Select Team Projects, выберем аккаунт и установим, какой репозиторий надо подтянуть к нам в VS.
После подключения проектов выберем нужный и нажмем в контекстном меню кнопку Clone.
На этом процесс клонирования закончен — в бранче Local Git Repositories в Team Explorer появится склонированный репозиторий. Повторюсь — с помощью Clone можно клонировать любой Git-репозиторий.
Еще одна интересная фича интеграции Visual Studio и Git — это возможность создать новый проект и сразу добавить его в локальную систему контроля версий. Для этого при создании нового проекта в VS достаточно отметить Add to source control.
Перед тем, когда вы будете коммитить что-то в репозиторий, нужно установить данные для коммитов — нажать на Changes и предупреждение о том, что нужно ввести данные.
Полезные функции на этой странице есть еще внутри Repository Settings — можно настроить .gitIgnore и .gitattributes.
Дальше можно коммитить.
Чтобы сделать Pull и получить последние апдейты от команды, нужно перейти на Commits и нажать Fetch для того, чтобы сначала посмотреть, что там вообще придет (и есть ли чему придти).
Все хорошо — нажмем Pull и получим последний апдейт. Дополнительные сведения можно найти тут — Pull changes from the team.
Использование бранчей
Для использования бранчей в Team Explorer выделена специальная секци Branches.
После подключения к репозиторию доступна только master.
Создадим новый бранч, нажав New Branch.
Поскольку бранчи Git локальны до момента Push, новый бранч будет размещен в Unpublished Branches. Поменять бранч для коммитов можно на уже упоминавшейся выше странице Commits.
Замерджить контент можно, нажав Merge и выбрав бранчи. Подробнее про бранчи и мерджи — Git Branching.
Если в процессе мерджа или пулла возникнут конфликты, они тут же могут быть разрезолвены (самые простые, конечно).
Для просмотра истории достаточно нажать View History в контекстном меню бранча.
По нажатию на коммит получим подробные сведения о том, что произошло.
Многое из этого также доступно на портале TFS. Для того, чтобы перейти туда из VS, нужно на странице проекта в Team Explorer нажать Web Portal.
Уже на портале можно изучить общее состояние репозитория…
… и подробную информацию об этих коммитах.
Резюме
Мы кратко посмотрели на то, как выглядит очень простой процесс взаимодействия Visual Studio и Git. Как говорилось в самом начале, плод интеграции Git в Visual Studio — это не намек на то, что Visual Studio полностью заменит рабочий процесс. Но то, что одна из самых популярных IDE стала отлично поддерживать одну из самых популярных систем контроля версий — это, на мой взгляд, замечательный факт, и обязательно понравится тем, кто использует и то и другое.
To get started with the GitHub in VS Code, you'll need to create a GitHub account and install the GitHub Pull Requests and Issues extension. In this topic, we'll demonstrate how you can use some of your favorite parts of GitHub without leaving VS Code.
If you're new to source control or want to learn more about VS Code's basic Git support, you can start with the Version Control topic.
Getting started with GitHub Pull Requests and Issues
Once you've installed the GitHub Pull Requests and Issues extension, you'll need to sign in. Follow the prompts to authenticate with GitHub in the browser and return to VS Code.
Setting up a repository
Cloning a repository
You can search for and clone a repository from GitHub using the Git: Clone command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by using the Clone Repository button in the Source Control view (available when you have no folder open).
From the GitHub repository dropdown you can filter and pick the repository you want to clone locally.
Authenticating with an existing repository
Enabling authentication through GitHub happens when you run any Git action in VS Code that requires GitHub authentication, such as pushing to a repository that you're a member of or cloning a private repository. You don't need to have any special extensions installed for authentication; it is built into VS Code so that you can efficiently manage your repository.
When you do something that requires GitHub authentication, you'll see a prompt to sign in:
Follow the steps to sign into GitHub and return to VS Code. If authenticating with an existing repository doesn't work automatically, you may need to manually provide a personal access token. See Personal Access Token authentication for more information.
Note that there are several ways to authenticate to GitHub, including using your username and password with two-factor authentication (2FA), a personal access token, or an SSH key. See About authentication to GitHub for more information and details about each option.
Note: If you'd like to work on a repository without cloning the contents to your local machine, you can install the GitHub Repositories extension to browse and edit directly on GitHub. You can learn more below in the GitHub Repositories extension section.
Editor integration
Hovers
When you have a repository open and a user is @-mentioned, you can hover over that username and see a GitHub-style hover.
Suggestions
The issues that appear in the suggestion can be configured with the GitHub Issues: Queries ( githubIssues.queries ) setting. The queries use the GitHub search syntax.
You can also configure which files show these suggestions using the settings GitHub Issues: Ignore Completion Trigger ( githubIssues.ignoreCompletionTrigger ) and GitHub Issues: Ignore User Completion Trigger ( githubIssues.ignoreUserCompletionTrigger ). These settings take an array of language identifiers to specify the file types.
Pull requests
From the Pull Requests view you can view, manage, and create pull requests.
The queries used to display pull requests can be configured with the GitHub Pull Requests: Queries ( githubPullRequests.queries ) setting and use the GitHub search syntax.
Creating Pull Requests
Once you have committed changes to your fork or branch, you can use the GitHub Pull Requests: Create Pull Request command or the Create Pull Request button in the Pull Requests view to create a pull request.
A new Create Pull Request view will be displayed where you can select the repository and branch you'd like your pull request to target as well as fill in details such as the title, description, and whether it is a draft PR. If your repository has a pull request template, this will automatically be used for the description.
Once you select Create, if you have not already pushed your branch to a GitHub remote, the extension will ask if you'd like to publish the branch and provides a dropdown to select the specific remote.
The Create Pull Request view now enters Review Mode, where you can review the details of the PR, add comments, reviewers, and labels, and merge the PR once it's ready.
After the PR is merged, you'll have the option to delete both the remote and local branch.
Reviewing
Pull requests can be reviewed from the Pull Requests view. You can assign reviewers and labels, add comments, approve, close, and merge all from the pull request Description.
From the Description page, you can also easily checkout the pull request locally using the Checkout button. This will switch VS Code to open the fork and branch of the pull request (visible in the Status bar) in Review Mode and add a new Changes in Pull Request view from which you can view diffs of the current changes as well as all commits and the changes within these commits. Files that have been commented on are decorated with a diamond icon. To view the file on disk, you can use the Open File inline action.
The diff editors from this view use the local file, so file navigation, IntelliSense, and editing work as normal. You can add comments within the editor on these diffs. Both adding single comments and creating a whole review is supported.
When you are done reviewing the pull request changes you can merge the PR or select Exit Review Mode to go back to the previous branch you were working on.
Issues
Creating issues
Issues can be created from the + button in the Issues view and by using the GitHub Issues: Create Issue from Selection and GitHub Issues: Create Issue from Clipboard commands. They can also be created using a Code Action for "TODO" comments. When creating issues, you can take the default description or select the Edit Description pencil icon in the upper right to bring up an editor for the issue body.
You can configure the trigger for the Code Action using the GitHub Issues: Create Issue Triggers ( githubIssues.createIssueTriggers ) setting.
Working on issues
From the Issues view, you can see your issues and work on them.
By default, when you start working on an issue (Start Working on Issue context menu item), a branch will be created for you, as shown in the Status bar in the image below.
The Status bar also shows the active issue and if you select that item, a list of issue actions are available such as opening the issue on the GitHub website or creating a pull request.
Once you are done working on the issue and want to commit a change, the commit message input box in the Source Control view will be populated with a message, which can be configured with GitHub Issues: Working Issue Format SCM ( githubIssues.workingIssueFormatScm ).
GitHub Repositories extension
The GitHub Repositories extension lets you quickly browse, search, edit, and commit to any remote GitHub repository directly from within Visual Studio Code, without needing to clone the repository locally. This can be fast and convenient for many scenarios, where you just need to review source code or make a small change to a file or asset.
Opening a repository
Once you have installed the GitHub Repositories extension, you can open a repository with the GitHub Repositories: Open Repository. command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by clicking the Remote indicator in the lower left of the Status bar.
When you run the Open Repository command, you then choose whether to open a repository from GitHub, open a Pull Request from GitHub, or reopen a repository that you had previously connected to.
If you haven't logged into GitHub from VS Code before, you'll be prompted to authenticate with your GitHub account.
You can provide the repository URL directly or search GitHub for the repository you want by typing in the text box.
Once you have selected a repository or Pull Request, the VS Code window will reload and you will see the repository contents in the File Explorer. You can then open files (with full syntax highlighting and bracket matching), make edits, and commit changes, just like you would working on a local clone of a repository.
One difference from working with a local repository is that when you commit a change with the GitHub Repository extension, the changes are pushed directly to the remote repository, similar to if you were working in the GitHub web interface.
Another feature of the GitHub Repositories extension is that every time you open a repository or branch, you get the up-to-date sources available from GitHub. You don't need to remember to pull to refresh as you would with a local repository.
Switching branches
You can easily switch between branches by clicking on the branch indicator in the Status bar. One great feature of the GitHub Repositories extension is that you can switch branches without needing to stash uncommitted changes. The extension remembers your changes and reapplies them when you switch branches.
Remote Explorer
You can quickly reopen remote repositories with the Remote Explorer available on the Activity bar. This view shows you the previously opened repositories and branches.
Create Pull Requests
If your workflow uses Pull Requests, rather than direct commits to a repository, you can create a new PR from the Source Control view. You'll be prompted to provide a title and create a new branch.
Once you have created a Pull Request, you can use the GitHub Pull Request and Issues extension to review, edit, and merge your PR as described earlier in this topic.
Virtual file system
Without a repository's files on your local machine, the GitHub Repositories extension creates a virtual file system in memory so you can view file contents and make edits. Using a virtual file system means that some operations and extensions which assume local files are not enabled or have limited functionality. Features such as tasks, debugging, and integrated terminals are not enabled and you can learn about the level of support for the virtual file system via the features are not available link in the Remote indicator hover.
Extension authors can learn more about running in a virtual file system and workspace in the Virtual Workspaces extension author's guide.
Continue Working on.
Sometimes you'll want to switch to working on a repository in a development environment with support for a local file system and full language and development tooling. The GitHub Repositories extension makes it easy for you to clone the repository locally or into a Docker container (if you have Docker and the Microsoft Docker extension installed) with the GitHub Repositories: Continue Working on. command available from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by clicking on the Remote indicator in the Status bar.
If you are using the browser-based editor, the "Continue Working On. " command has the options to open the repository locally or within a cloud-hosted environment in GitHub Codespaces.
Visual Studio Code has integrated source control management (SCM) and includes Git support out-of-the-box. Many other source control providers are available through extensions on the VS Code Marketplace.
Tip: Click on an extension tile to read the description and reviews in the Marketplace.
SCM Providers
VS Code has support for handling multiple Source Control providers simultaneously. For example, you can open multiple Git repositories alongside your Azure DevOps Server local workspace and seamlessly work across your projects. To turn on the Source Control Providers view, select the overflow menu in the Source Control view ( ⌃⇧G (Windows, Linux Ctrl+Shift+G ) ), hover over Views, and make sure that Source Control Repositories is marked with a check. The Source Control Providers view shows the detected providers and repositories, and you can scope the display of your changes by selecting a specific provider.
SCM Provider extensions
If you would like to install another SCM provider, you can search on the scm providers extension category in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ). Start typing '@ca' and you will see suggestions for extension categories like debuggers and linters. Select @category:"scm providers" to see available SCM providers.
Git support
VS Code ships with a Git source control manager (SCM) extension. Most of the source control UI and work flows are common across other SCM extensions, so reading about the general Git support in VS Code will help you understand how to use another provider.
Note: If you are new to Git, the git-scm website is a good place to start, with a popular online book, Getting Started videos and cheat sheets. The VS Code documentation assumes you are already familiar with Git.
Note: VS Code will leverage your machine's Git installation, so you need to install Git first before you get these features. Make sure you install at least version 2.0.0 .
👉 When you commit, be aware that if your username and/or email is not set in your Git configuration, Git will fall back to using information from your local machine. You can find the details in Git commit information.
The Source Control icon in the Activity Bar on the left will always indicate an overview of how many changes you currently have in your repository. Selecting the icon will show you the details of your current repository changes: CHANGES, STAGED CHANGES and MERGE CHANGES.
Clicking each item will show you in detail the textual changes within each file. Note that for unstaged changes, the editor on the right still lets you edit the file: feel free to use it!
You can also find indicators of the status of your repository in the bottom-left corner of VS Code: the current branch, dirty indicators, and the number of incoming and outgoing commits of the current branch. You can checkout any branch in your repository by clicking that status indicator and selecting the Git reference from the list.
Tip: You can open VS Code in a sub-directory of a Git repository. VS Code's Git services will still work as usual, showing all changes within the repository, but file changes outside of the scoped directory are shaded with a tool tip indicating they are located outside the current workspace.
Commit
Staging (git add) and unstaging (git reset) can be done via contextual actions in the files or by drag-and-drop.
You can type a commit message above the changes and press Ctrl+Enter (macOS: ⌘+Enter ) to commit them. If there are any staged changes, only those changes will be committed. Otherwise, you'll get a prompt asking you to select what changes you'd like to commit and get the option to change your commit settings.
We've found this to be a great workflow. For example, in the earlier screenshot, only the staged changes to overview.jpg will be included in the commit. Later staging and commit actions could include the changes to versioncontrol.md and the two other .jpg images as a separate commit.
More specific Commit actions can be found in the Views and More Actions . menu on the top of the Source Control view.
Tip: If you commit your change to the wrong branch, undo your commit using the Git: Undo Last Commit command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
Cloning a repository
If you haven't opened a folder yet, the Source Control view will give you the options to Open Folder from your local machine or Clone Repository.
If you select Clone Repository, you will be asked for the URL of the remote repository (for example on GitHub) and the parent directory under which to put the local repository.
For a GitHub repository, you would find the URL from the GitHub Code dialog.
You would then paste that URL into the Git: Clone prompt.
You'll also see the option to Clone from GitHub. Once you authenticate with your GitHub account in VS Code, you'll be able to search through repositories by name, and select any repo to clone it. You can also start the flow to clone a Git repository with the Git: Clone command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). To see a step-by-step walkthrough, check out our Clone repos from VS Code video.
Note: If you'd like to work on a repository without cloning the contents to your local machine, you can install the GitHub Repositories extension to browse and edit directly on GitHub. You can learn more in the GitHub Repositories extension section.
Branches and Tags
You can create and checkout branches directly within VS code through the Git: Create Branch and Git: Checkout to commands in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
If you run Git: Checkout to, you will see a dropdown list containing all of the branches or tags in the current repository. It will also give you the option to create a new branch if you decide that's a better option, or checkout a branch in detached mode.
The Git: Create Branch command lets you quickly create a new branch. Just provide the name of your new branch and VS Code will create the branch and switch to it. If you choose to Create new branch from. , you'll get an extra prompt that allows you to specify which commit the new branch should be pointing to.
Remotes
Given that your repository is connected to some remote and that your checked out branch has an upstream link to a branch in that remote, VS Code offers you useful actions to push, pull, and sync that branch (the latter will run a pull command followed by a push command). You can find these actions in the Views and More Actions . menu, along with the option to add or remove a remote.
VS Code is able to periodically fetch changes from your remotes. This enables VS Code to show how many changes your local repository is ahead or behind the remote. Starting with VS Code 1.19, this feature is disabled by default and you can use the git.autofetch setting to enable it.
Tip: You should set up a credential helper to avoid getting asked for credentials every time VS Code talks to your Git remotes. If you don't do this, you may want to consider disabling automatic fetching via the git.autofetch setting to reduce the number of prompts you get.
Git Status Bar actions
There is a Synchronize Changes action in the Status Bar, next to the branch indicator, when the current checked out branch has an upstream branch configured. Synchronize Changes will pull remote changes down to your local repository and then push local commits to the upstream branch.
If there is no upstream branch configured and the Git repository has remotes set up, the Publish action is enabled. This will let you publish the current branch to a remote.
Gutter indicators
If you open a folder that is a Git repository and begin making changes, VS Code will add useful annotations to the gutter and to the overview ruler.
- A red triangle indicates where lines have been deleted
- A green bar indicates new added lines
- A blue bar indicates modified lines
Merge conflicts
Merge conflicts are recognized by VS Code. Differences are highlighted and there are inline actions to accept either one or both changes. Once the conflicts are resolved, stage the conflicting file so you can commit those changes.
Viewing diffs
Our Git tooling supports viewing of diffs within VS Code.
Tip: You can diff any two files by first right clicking on a file in the Explorer or OPEN EDITORS list and selecting Select for Compare and then right-click on the second file to compare with and select Compare with 'file_name_you_chose'. Alternatively from the keyboard hit ⇧⌘P (Windows, Linux Ctrl+Shift+P ) and select File: Compare Active File With and you will be presented with a list of recent files.
Diff editor review pane
There is a review pane in the Diff editor that presents changes in a unified patch format. You can navigate between changes with Go to Next Difference ( F7 ) and Go to Previous Difference ( ⇧F7 (Windows, Linux Shift+F7 ) ). Lines can be navigated with arrow keys and pressing Enter will jump back in the Diff editor and the selected line.
Note: This experience is especially helpful for screen reader users.
Timeline view
The Timeline view, accessible at the bottom of the File Explorer by default, is a unified view for visualizing time-series events (for example, Git commits) for a file.
VS Code's built-in Git support provides the Git commit history of the specified file. Selecting a commit will open a diff view of the changes introduced by that commit. When you right-click on a commit, you'll get options to Copy Commit ID and Copy Commit Message.
Visual Studio Code supports more Git history workflows through extensions available on the VS Code Marketplace.
Tip: Click on an extension tile to read the description and reviews in the Marketplace.
Git output window
You can always peek under the hood to see the Git commands we are using. This is helpful if something strange is happening or if you are just curious. :)
To open the Git output window, run View > Output and select Git from the dropdown list.
Initialize a repository
If your workspace is on your local machine, you can enable Git source control by creating a Git repository with the Initialize Repository command. When VS Code doesn't detect an existing Git repository, the Source Control view will give you the options to Initialize Repository or Publish to GitHub.
You can also run the Git: Initialize Repository and Publish to GitHub commands from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Running Initialize Repository will create the necessary Git repository metadata files and show your workspace files as untracked changes ready to be staged. Publish to GitHub will directly publish your workspace folder to a GitHub repository, allowing you to choose between a private and public repositories. Check out our publishing repos video for more information about publishing to GitHub.
VS Code as Git editor
When you launch VS Code from the command line, you can pass the --wait argument to make the launch command wait until you have closed the new VS Code instance. This can be useful when you configure VS Code as your Git external editor so Git will wait until you close the launched VS Code instance.
Here are the steps to do so:
- Make sure you can run code --help from the command line and you get help.
- if you do not see help, please follow these steps:
- macOS: Select Shell Command: Install 'Code' command in path from the Command Palette.
- Windows: Make sure you selected Add to PATH during the installation.
- Linux: Make sure you installed Code via our new .deb or .rpm packages.
- if you do not see help, please follow these steps:
- From the command line, run git config --global core.editor "code --wait"
Now you can run git config --global -e and use VS Code as editor for configuring Git.
VS Code as Git diff tool
Add the following to your Git configurations to use VS Code as the diff tool:
This leverages the --diff option you can pass to VS Code to compare two files side by side.
To summarize, here are some examples of where you can use VS Code as the editor:
- git rebase HEAD~3 -i do interactive rebase using VS Code
- git commit use VS Code for the commit message
- git add -p followed by e for interactive add
- git difftool ^ use VS Code as the diff editor for changes
Working with pull requests
Visual Studio Code also supports pull request workflows through the GitHub Pull Requests and Issues extension available on the VS Code Marketplace. Pull request extensions let you review, comment, and verify source code contributions directly within VS Code.
Next steps
-
- An introductory video providing an overview of VS Code Git support. - Learn about the powerful VS Code editor. - Move quickly through your source code. - This is where VS Code really shines - Running tasks with Gulp, Grunt, and Jake. Showing Errors and Warnings - If you want to integrate another Source Control provider into VS Code, see our Source Control API.
Common questions
I initialized my repo but the actions in the . menu are all grayed out
To push, pull, and sync you need to have a Git origin set up. You can get the required URL from the repository host. Once you have that URL, you need to add it to the Git settings by running a couple of command-line actions. For example:
My team is using Team Foundation Version Control (TFVC) instead of Git. What should I do?
Use the Azure Repos extension and this will light up TFVC support.
Why do the Pull, Push and Sync actions never finish?
This usually means there is no credential management configured in Git and you're not getting credential prompts for some reason.
You can always set up a credential helper in order to pull and push from a remote server without having VS Code prompt for your credentials each time.
How can I sign in to Git with my Azure DevOps organization that requires multi-factor authentication?
Git Credential Manager (GCM) is the recommended Git credential helper for Windows, macOS, and Linux. If you're running Git for Windows, GCM has already been installed and configured for you. If you're running on macOS or Linux, the GCM README has setup instructions.
I have GitHub Desktop installed on my computer but VS Code ignores it
VS Code only supports the official Git distribution for its Git integration.
I keep getting Git authentication dialogs whenever VS Code is running
VS Code automatically fetches changes from the server in order to present you with a summary of incoming changes. The Git authentication dialog is independent from VS Code itself and is a part of your current Git credential helper.
One way to avoid these prompts is to set up a credential helper that remembers your credentials.
Another option is to disable the auto fetch feature by changing the following setting: "git.autofetch": false .
Can I use SSH Git authentication with VS Code?
Yes, though VS Code works most easily with SSH keys without a passphrase. If you have an SSH key with a passphrase, you'll need to launch VS Code from a Git Bash prompt to inherit its SSH environment.
Читайте также: