使用 VSCode 的版本控制功能

694 阅读38分钟

概述

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.

Visual Studio Code 集成了源代码控制管理 (SCM),并包含开箱即用的 Git 支持。许多其他源代码控制提供程序可通过 VS Code Marketplace 上的插件获得。

youtu.be/i_23KUAEtUM

在 Git 存储库中工作

Just getting started with 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.

刚刚开始使用 Git? git-scm 网站是一个很好的起点,提供流行的在线书籍、入门视频和备忘单。 VS Code 文档假设你已经熟悉 Git。

Overview of Git

Make sure Git is installed. VS Code will use your machine's Git installation (at least version 2.0.0), so you need to install Git first before you get these features.

确保已安装 Git。 VS Code 将使用你主机安装的 Git (版本至少为 2.0.0 ),因此你需要先安装 Git,然后才能获得这些功能。

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.

左侧活动栏中的源代码管理图标将始终显示你的仓库中当前有多少更改的概览。

image.png

选择该图标将显示当前存储库更改的详细信息:CHANGES, STAGED CHANGESMERGE 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.

你还可以在 VS Code 的左下角找到仓库状态的指示器:当前分支、脏指示器以及当前分支的 incoming 和 outgoing 提交数。你可以通过单击状态指示器并从列表中选择 Git 引用来检出存储库中的任何分支。

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. 提示:你可以在 Git 存储库的子目录中打开 VS Code。 VS Code 的 Git 服务仍将照常工作,显示存储库内的所有更改,但作用域目录之外的文件更改会用工具提示用阴影表示,表明它们位于当前工作区之外。

提交

Staging (git add) and unstaging (git reset) can be done via contextual actions in the files or by drag-and-drop. 暂存 (git add) 和取消暂存 (git reset) 可以通过文件中的上下文操作或通过拖放来完成。

Configure your Git username and email. 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. 配置你的 Git 用户名和电子邮件。当你提交时,请注意,如果你的 Git 配置中未设置你的用户名和/或电子邮件,Git 将回退到使用本地计算机中的信息。你可以在 Git 提交信息中找到详细信息。

Stage all changes button

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. 你可以在更改上方输入提交消息,然后按 Ctrl+Enter(macOS:⌘+Enter)来提交它们。如果有任何暂存(staged)的更改,则只会提交这些更改。否则,你将收到一条提示,要求你选择要提交的更改并获得更改提交设置的选项。

We've found this to be a great workflow. For example, in the earlier screenshot, only the staged changes to overview.png will be included in the commit. Later staging and commit actions could include the changes to versioncontrol.md and the two other .png images as a separate commit. 我们发现这是一个很棒的工作流。例如,在前面的屏幕截图中,只有对 overview.png 的暂存更改才会包含在提交中。稍后的暂存和提交操作可能包括对 versioncontrol.md 和其他两个 .png 图像的更改作为单独的提交。

More specific Commit actions can be found in the Views and More Actions ... menu on the top of the Source Control view. 更具体的提交操作可以在源代码管理视图顶部的视图和更多操作 ... 菜单中找到。

views and more actions button

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). 提示:如果你将更改提交到错误的分支,请使用命令面板中的 Git:撤消上次提交命令 (⇧⌘P) 撤消你的提交。

youtu.be/E6ADS2k8oNQ

使用编辑器编写提交信息

If you don't enter a commit message when commiting changes, VS Code opens an editor for the COMMIT_EDITMSG file where you can author the commit message in the editor. After you provide a commit message, either close the editor tab, or select the Accept Commit Message button in the editor toolbar to commit the changes. 如果你在提交更改时未输入提交消息,VS Code 会打开 COMMIT_EDITMSG 文件的编辑器,你可以在编辑器中编写提交信息。提供提交信息后,关闭编辑器选项卡,或选择编辑器工具栏中的「接受提交消息」按钮以提交更改。

To cancel the commit operation, you can either clear the contents of the text editor and close the editor tab, or select the Discard Commit Message button in the editor toolbar. 要取消提交操作,你可以清除文本编辑器的内容并关闭编辑器选项卡,或者选择编辑器工具栏中的「放弃提交消息」按钮。

Author commit message in a full text editor转存失败,建议直接上传图片文件

You can disable this functionality by toggling the git.useEditorAsCommitInput setting. After the setting is changed, you have to restart VS Code for the change to take effect. 你可以通过切换 git.useEditorAsCommitInput 设置来禁用此功能。设置更改后,必须重新启动 VS Code 才能使更改生效。

To use the same flow for git commit commands executed in the integrated terminal, enable the git.terminalGitEditor setting. 要对集成终端中执行的 git commit 命令使用相同的流程,请启用 git.terminalGitEditor 设置。

克隆存储库

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. 如果你尚未打开文件夹,源代码管理视图将为你提供从本地计算机或克隆存储库打开文件夹的选项。

First run Source Control experience

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. 如果选择 「克隆存储库」,系统将要求你提供远程存储库的 URL(例如在 GitHub 上)以及放置本地存储库的父目录。

For a GitHub repository, you would find the URL from the GitHub Code dialog. 对于 GitHub 存储库,你可以从 GitHub 代码对话框中找到 URL。

clone repository dialog

You would then paste that URL into the Git: Clone prompt. 然后,你可以将该 URL 粘贴到 Git: Clone 提示符中。

set repository URL

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). To see a step-by-step walkthrough, check out our Clone repos from VS Code video. 你还将看到从 GitHub 克隆的选项。在 VS Code 中使用 GitHub 帐户进行身份验证后,你将能够按名称搜索存储库,并选择任何存储库来克隆它。你还可以使用命令面板 (⇧⌘P) 中的 Git: Clone 命令启动克隆 Git 存储库的流程。要查看分步演练,请观看我们的从 VS Code 克隆存储库视频。

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. 注意:如果你想使用存储库而不将内容克隆到本地计算机,则可以安装 GitHub 存储库扩展以直接在 GitHub 上浏览和编辑。你可以在 GitHub 存储库扩展部分了解更多信息。

分支和标签

youtu.be/b9LTz6joMf8

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

你可以通过 Git:创建分支和 Git:检出 命令面板 (⇧⌘P) 中的命令直接在 VS Code 中创建和检出分支。

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. 如果运行 Git: Checkout to,你将看到一个下拉列表,其中包含当前存储库中的所有分支或标签。如果你认为这是更好的选择,它还可以让你选择创建新分支,或者以分离模式检出分支。

Git checkout

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. Git:创建分支命令可让你快速创建新分支。只需提供新分支的名称,VS Code 将创建该分支并切换到该分支。如果你选择从...创建新分支,你将收到一个额外的提示,允许你指定新分支应指向哪个提交。

Tip: VS Code can automatically save and restore open editors when you switch to another branch. Use the scm.workingSets.enabled setting to enable this feature. To control the open editors when switching to a branch for the first time, you can use the scm.workingSets.default setting. 提示:当你切换到另一个分支时,VS Code 可以自动保存和恢复打开的编辑器。使用 scm.workingSets.enabled 设置启用此功能。要控制第一次切换到分支时打开的编辑器,可以使用 scm.workingSets.default 设置。

Remote

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 会为你提供有用的操作来推送、拉取和同步该分支(后者将运行一个拉取命令,后跟通过推送命令)。你可以在「视图和更多操作」 ... 菜单中找到这些操作,以及添加或删除远程的选项。

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. This feature is disabled by default and you can use the git.autofetch setting to enable it. VS Code 能够定期从远程获取更改。这使 VS Code 能够显示本地存储库领先或落后于远程存储库的更改数量。此功能默认处于禁用状态,你可以使用 git.autofetch 设置来启用它。

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. 提示:你应该设置一个凭据帮助程序,以避免每次 VS Code 与 Git 远程通信时都被要求提供凭据。如果你不这样做,你可能需要考虑通过 git.autofetch 设置禁用自动提取,以减少收到的提示数量。

Git 状态栏操作

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. 当当前检出的分支配置了上游分支时,状态栏中的分支指示器旁边有一个「同步更改」操作。同步更改会将远程更改拉到本地存储库,然后将本地提交推送到上游分支。

git status bar sync

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. 如果没有配置上游分支并且 Git 存储库已设置远程,则启用发布操作。这将允许你将当前分支发布到远程。

git status bar publish

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. 如果你打开一个 Git 存储库文件夹并开始进行更改,VS Code 将向装订线和概述标尺添加有用的注释。

  • A red triangle indicates where lines have been deleted 红色三角形表示已删除线的位置
  • A green bar indicates new added lines 绿色条表示新添加的行
  • A blue bar indicates modified lines 蓝色条表示修改的行

Gutter indicators

合并冲突

Git merge

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. VS Code 可以识别合并冲突。差异被高亮显示,并且有 inline actions 来接受单个或同时的更改。解决冲突后,暂存冲突文件,以便你可以提交这些更改。

3 路合并编辑器

To help you resolve merge conflicts, VS Code provides a 3-way merge editor where you can interactively accept incoming and current changes and view and edit the resulting merged file. The 3-way merge editor is opened by selecting the Resolve in Merge Editor button in the bottom right corner of a file with Git merge conflicts. 为了帮助你解决合并冲突,VS Code 提供了一个三路合并编辑器,你可以在其中交互地接受incoming和当前的更改,并查看和编辑生成的合并文件。通过选择具有 Git 合并冲突的文件右下角的「在合并编辑器中解决」按钮,可以打开三路合并编辑器。

The 3-way merge editor displays separate views for Incoming changes (on the left), Current changes (on the right), and the Result of the merge (at the bottom). Conflicts are highlighted and can be resolved by using the CodeLens buttons. 三路合并编辑器显示 incoming 更改(左侧)、当前更改(右侧)和合并结果(底部)的单独视图。冲突会高亮显示,并且可以使用 CodeLens 按钮解决。

3-way merge editor

解决冲突

The 3-way merge editor allows you to resolve conflicts by accepting either one or both changes. You can also manually edit the result of the merge. 三路合并编辑器允许你通过接受 one or both changes 更改来解决冲突。你还可以手动编辑合并结果。

For some conflicts, the merge editor shows an Accept Combination button. Accepting the combination resolves the current conflict by smartly merging both changes. This is especially useful for changes in the same line that don't touch the same characters. 对于某些冲突,合并编辑器会显示「Accept Combination」按钮。Accept Combination 可以通过巧妙地合并这两个更改来解决当前的冲突。这对于同一行中不涉及相同字符的更改特别有用。

Use the Ignore buttons to accept neither the incoming nor current change, but mark the conflict as resolved. This resets the conflicting area to the state before any changes were made. 使用「忽略」按钮既不接受 incoming 的更改也不接受当前的更改,而是将冲突标记为已解决。这会将冲突区域重置为进行任何更改之前的状态。

完成合并

You can use the conflict counter in the right of the result editor to keep track of how many unresolved conflicts are remaining. Clicking on the counter jumps to the next unresolved conflict. Once all conflicts are resolved, you can complete the merge by selecting Complete Merge in the bottom right corner. This stages the file and closes the merge editor. 你可以使用结果编辑器右侧的冲突计数器来跟踪剩余的未解决冲突数量。单击计数器可跳转到下一个未解决的冲突。解决所有冲突后,你可以通过选择右下角的「完成合并」来完成合并。这将暂存文件并关闭合并编辑器。

替代布局

Selecting the three dots ( ··· ) in the top right corner of the merge editor opens a context menu with additional options. You can switch to a vertical layout and display the base view, which shows the state of the file before any changes were made. 选择合并编辑器右上角的三个点 (...) 将打开一个包含其他选项的上下文菜单。你可以切换到垂直布局并显示 base 视图,该视图显示进行任何更改之前文件的状态。

The three dots next to Incoming, Current, and Result offer options for each view, such as showing a side-by-side diff against base, accepting all changes, or resetting the result. 「incoming」、「当前」和「结果」旁边的三个点为每个视图提供选项,例如显示与 base 的并排差异、接受所有更改或重置结果。

了解冲突

If you want to learn more about the details of how 3-way merge editors work, we can recommend the following video: 如果你想了解更多有关三路合并编辑器工作原理的详细信息,我们可以推荐以下视频:

youtu.be/HosPml1qkrg

查看差异

Our Git tooling supports viewing of diffs within VS Code. 我们的 Git 工具支持查看 VS Code 中的差异。

A File Diff in VS Code

The Diff editor has a separate gutter in the middle, which enables you to Stage or Revert changes code blocks. If you select a block of text, you can revert or stage the changes that are included in the selection. Diff 编辑器中间有一个单独的 gutter,使你能够暂存或恢复更改代码块。如果选择文本块,则可以恢复或暂存所选内容中包含的更改。

Screenshot of the Diff editor, showing the Stage and Revert controls in the gutter

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 and select File: Compare Active File With and you will be presented with a list of recent files. 提示:你可以通过首先右键单击资源管理器或打开编辑器列表中的文件并选择选择进行比较来比较任意两个文件,然后右键单击要比较的第二个文件并选择与「file_name_you_chose」进行比较。或者,从键盘上按 ⇧⌘P 并选择文件:比较活动文件,你将看到最近文件的列表。

易于访问的差异查看器

There is an Accessible Diff Viewer 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). Lines can be navigated with arrow keys and pressing Enter will jump back in the Diff editor and the selected line. Diff 编辑器中有一个可访问的 Diff 查看器,它以统一的补丁格式显示更改。你可以使用转到下一个差异 (F7) 和转到上一个差异 (⇧F7) 在更改之间导航。可以使用箭头键导航行,按 Enter 键将跳回 Diff 编辑器和选定的行。

diff-review-pane

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. 默认情况下可在文件资源管理器底部访问的时间轴视图是用于可视化文件的时间序列事件(例如 Git 提交)的统一视图。

Timeline view

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. VS Code 的内置 Git 支持提供指定文件的 Git 提交历史记录。选择一个提交将打开该提交引入的更改的差异视图。当你右键单击提交时,你将获得复制提交 ID 和复制提交消息的选项。

Visual Studio Code supports more Git history workflows through extensions available on the VS Code Marketplace. Visual Studio Code 通过 VS Code Marketplace 上提供的扩展支持更多 Git 历史记录工作流。

Git 输出窗口

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. :) 你可以随时查看我们正在使用的 Git 命令。如果发生奇怪的事情或者你只是好奇,这会很有帮助。 :)

To open the Git output window, run View > Output and select Log (Git) from the dropdown list. 要打开 Git 输出窗口,请运行 视图 > 输出,然后从下拉列表中选择 日志 (Git)。

初始化存储库

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. 如果你的工作区位于本地计算机上,则可以通过使用「初始化存储库」命令创建 Git 存储库来启用 Git 源代码管理。当 VS Code 未检测到现有的 Git 存储库时,「源代码管理」视图将为你提供「初始化存储库」或「发布到 GitHub」的选项。

Git initialize repository

You can also run the Git: Initialize Repository and Publish to GitHub commands from the Command Palette (⇧⌘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 private and public repositories. Check out our publishing repos video for more information about publishing to GitHub. 你还可以从命令面板 (⇧⌘P) 运行 Git:初始化存储库和发布到 GitHub 命令。运行 Initialize Repository 将创建必要的 Git 存储库元数据文件,并将工作区文件显示为准备暂存的未跟踪更改。发布到 GitHub 会将你的工作区文件夹直接发布到 GitHub 存储库,允许你在私有存储库和公共存储库之间进行选择。请观看我们的发布存储库视频,了解有关发布到 GitHub 的更多信息。

VS Code as Git editor VS Code 作为 Git 编辑器

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. 从命令行启动 VS Code 时,可以传递 --wait 参数以使启动命令等待,直到你关闭新的 VS Code 实例。当你将 VS Code 配置为 Git 外部编辑器时,这会很有用,这样 Git 将等待你关闭启动的 VS Code 实例。

Here are the steps to do so: 以下是执行此操作的步骤:

  1. Make sure you can run

    1
    code --help
    

    from the command line and you get help.

    确保你可以从命令行运行 code --help 并获得帮助。

    • if you do not see help, please follow these steps:

      如果你没有看到帮助,请按照以下步骤操作:

      • macOS: Select Shell Command: Install 'Code' command in path from the Command Palette. macOS:选择 Shell 命令:在命令面板的路径中安装「代码」命令。
      • Windows: Make sure you selected Add to PATH during the installation. Windows:确保在安装过程中选择了「添加到路径」。
      • Linux: Make sure you installed Code via our new .deb or .rpm packages. Linux:确保你通过我们新的 .deb.rpm 软件包安装了代码。
  2. From the command line, run git config --global core.editor "code --wait" 从命令行运行 git config --global core.editor "code --wait"

Now you can run git config --global -e and use VS Code as editor for configuring Git. 现在你可以运行 git config --global -e 并使用 VS Code 作为编辑器来配置 Git。

VS Code as Git difftool and mergetool VS Code 作为 Git difftool 和 mergetool

You can use VS Code's diff and merge capabilities even when using Git from command-line. Add the following to your Git configurations to use VS Code as the diff and merge tool: 即使从命令行使用 Git,你也可以使用 VS Code 的差异和合并功能。将以下内容添加到 Git 配置中,以使用 VS Code 作为差异和合并工具:

[diff]
    tool = default-difftool
[difftool "default-difftool"]
    cmd = code --wait --diff $LOCAL $REMOTE
[merge]
  tool = code
[mergetool "code"]
  cmd = code --wait --merge $REMOTE $LOCAL $BASE $MERGED

This uses the --diff option that can be passed to VS Code to compare two files side by side. The merge tool will be used the next time Git discovers a merge conflict. 这使用可传递到 VS Code 的 --diff 选项来并排比较两个文件。下次 Git 发现合并冲突时将使用合并工具。

To summarize, here are some examples of where you can use VS Code as the editor: 总而言之,以下是一些可以使用 VS Code 作为编辑器的示例:

  • git rebase HEAD~3 -i do interactive rebase using VS Code git rebase HEAD~3 -i 使用 VS Code 进行交互式变基
  • git commit use VS Code for the commit message git commit 使用 VS Code 作为提交消息
  • git add -p followed by e for interactive add git add -p 后跟 e 用于交互式添加
  • git difftool <commit>^ <commit> use VS Code as the diff editor for changes git difftool <commit>^ <commit> 使用 VS Code 作为更改的差异编辑器

VS Code 中的 Git 简介

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. 想要轻松管理你的源代码并与他人协作? Git 和 GitHub 是你需要的工具!借助 Visual Studio Code,你可以快速设置和使用它们。即使你是初学者,VS Code 的用户友好的界面也会引导你完成常见的 Git 操作,例如推送和拉取代码、创建和合并分支以及提交代码更改。如果你是专业人士,你会喜欢直接在编辑器中执行 Git 操作的能力,与使用 Git 命令行相比,这可以节省你的时间和精力。此外,VS Code 和 Git 之间的无缝工作流意味着你可以留在编辑器中完成更多工作。

在 VS Code 中设置 Git

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. 要在 VS Code 中使用 Git 和 GitHub,首先确保你的计算机上安装了 Git。如果缺少 Git,源代码管理视图会显示有关如何安装它的说明。确保之后重新启动 VS Code。

Additionally you can sign into VS Code with your GitHub account in the Accounts menu in the lower right of the Activity bar to enable additional features like Settings Sync, but also cloning and publishing repositories from GitHub. 此外,你可以在活动栏右下角的「帐户」菜单中使用 GitHub 帐户登录 VS Code,以启用「设置同步」等其他功能,还可以从 GitHub 克隆和发布仓库。

Screenshot of the Accounts menu in VS Code

打开 Git 仓库

VS Code provides several ways to get started in a Git repository, from local to remote cloud-powered environments like GitHub Codespaces. VS Code 提供了多种在 Git 仓库中开始的方法,从本地到远程云支持的环境(例如 GitHub Codespaces)。

在本地克隆仓库

To clone a repository, run the Git: Clone command in the Command Palette (⇧⌘P), or select the Clone Repository button in the Source Control view. 要克隆仓库,请运行命令面板 (⇧⌘P) 中的 Git: Clone 命令,或选择源代码管理视图中的克隆仓库按钮。

If you clone from GitHub, VS Code prompts you to authenticate with GitHub. Then, select a repository from the list to clone to your machine. The list contains both public and private repositories. 如果从 GitHub 克隆,VS Code 会提示你使用 GitHub 进行身份验证。然后,从列表中选择一个仓库以克隆到你的计算机。该列表包含公共和私有仓库。

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

For other Git providers, enter the repository URL, select Clone, and pick a folder on your local machine to clone the files into. VS Code opens the folder once the repository is cloned on your local machine. 对于其他 Git 提供商,输入仓库 URL,选择「克隆」,然后选择本地计算机上的一个文件夹来将文件克隆到其中。将仓库克隆到本地计算机上后,VS Code 将打开该文件夹。

Screenshot of the Clone Repository quick prompt, searching for a repository by providing the repository URL

在本地文件夹中初始化仓库

To initialize a new local Git repository: 要初始化新的本地 Git 仓库:

  1. Pick an existing or new folder on your computer and open it in VS Code. 选择计算机上的现有或新文件夹并在 VS Code 中打开它。

  2. 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. 这会在当前文件夹中创建一个新的 Git 仓库,允许你开始跟踪代码的更改。

    This action is equivalent to running git init on the command-line. 此操作相当于在命令行上运行 git init

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

将本地仓库发布到 GITHUB

You can also initialize and local repository and publish it directly to GitHub. This creates a new repository on your GitHub account, and pushes your local code changes 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. 你还可以初始化本地仓库并直接发布到 GitHub。这会在你的 GitHub 帐户上创建一个新仓库,并将本地代码更改推送到远程仓库。将源代码放在远程仓库上是备份代码、与他人协作以及使用 GitHub Actions 自动化工作流的好方法。

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. 使用「源代码管理」视图中的「发布到 GitHub」命令按钮。然后,你可以选择仓库的名称和描述,以及将其设为公开还是私有。

Screenshot of the Publish to GitHub quick prompt, showing private and public GitHub repository names

Once the repository has been created, VS Code pushes 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. 创建仓库后,VS Code 会将本地代码推送到远程仓库。你的代码现已备份在 GitHub 上,你可以开始与其他人协作提交和拉取请求。

在代码空间中打开 GitHub 仓库

GitHub Codespaces lets you open a GitHub repository in a fully configured cloud-based development environment, enabling 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. GitHub Codespaces 允许你在完全配置的基于云的开发环境中打开 GitHub 仓库,使你能够在浏览器中进行开发,而无需在本地计算机上安装任何软件。 GitHub Codespaces 允许个人免费使用,这使得开始从事开源项目变得容易。

To create a codespace for your GitHub repository: 要为 GitHub 仓库创建代码空间:

  1. Install the GitHub Codespaces extension in VS Code and sign in with your GitHub account. 在 VS Code 中安装 GitHub Codespaces 插件并使用你的 GitHub 帐户登录。

  2. Run the Codespaces: Create New Codespace command. 运行 Codespaces: Create New Codespace 命令。

  3. Select the repository and branch you want to open. 选择要打开的仓库和分支。

    VS Code opens a new window, which is connected to the codespace. The source code, terminal, and running and debugging are hosted in the remote cloud-based development environment. VS Code 打开一个新窗口,该窗口连接到代码空间。源代码、终端、运行调试均托管在远程云端开发环境中。

    Notice that the File Explorer and Status Bar indicate that the workspace is opened in a codespace. 请注意,文件资源管理器和状态栏指示工作区已在代码空间中打开。

    Screenshot of a workspace opened in a codespace, highlighting the codespace name in the File Explorer and Status Bar

Alternatively, you can also start from a codespace template on the GitHub Codespaces website. 或者,你也可以从 GitHub Codespaces 网站上的代码空间模板开始。

If you already have a codespace open in your browser, run the Codespaces: Open in VS Code Desktop command in the browser to connect to the codespace from your local VS Code Desktop. 如果你已在浏览器中打开了代码空间,请在浏览器中运行 Codespaces: Open in VS Code Desktop 命令,以从本地 VS Code 桌面连接到代码空间。

You can learn more about GitHub Codespaces, including customization such as forwarding ports, in the Developing in a codespace documentation. 你可以在代码空间中开发文档中了解有关 GitHub Codespaces 的更多信息,包括转发端口等自定义。

远程打开 GitHub 仓库

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. VS Code 的远程仓库支持允许你浏览和编辑 GitHub 仓库,而无需将其克隆到本地计算机。这对于快速更改远程仓库非常有用,而无需将整个代码库克隆到你的计算机。

  1. First install the GitHub Repositories extension. 首先安装 GitHub 仓库插件。

  2. Run the command Remote Repositories: Open Remote Repository... or use the Open Remote Repository button the Explorer view. 运行命令远程仓库:打开 Remote Repositories: Open Remote Repository... 或使用资源管理器视图中的 Open Remote Repository 按钮。

  3. Search and select the GitHub repository that you want to open. 搜索并选择你要打开的 GitHub 仓库。

    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. 提示:如果你需要执行代码或运行终端命令,可以使用「继续工作」命令从远程仓库无缝切换到代码空间。

暂存和提交代码更改

Once you have a Git repository set up, you can start tracking code changes by staging and committing your newly created and edited code. 设置 Git 仓库后,你可以通过暂存和提交新创建和编辑的代码来开始跟踪代码更改。

Tip: Commit your changes early and often. This makes it easier to revert back to previous versions of your code if needed. 提示:尽早并经常提交更改。这使得在需要时更容易恢复到以前版本的代码。

You can access the Source Control view from the Activity Bar to list all changed files in your workspace. You can toggle between a tree view or list view by using the tree/list icon in the Source Control view header. 你可以从活动栏访问源代码管理视图,以列出工作区中所有已更改的文件。你可以使用源代码管理视图标题中的树/列表图标在树视图或列表视图之间切换。

Source Control view, highlighting the tree/list view control in the header

When you select a file in the Source Control view, the editor shows a diff view that highlights the file changes, compared to the previously committed file. 当你在「源代码管理」视图中选择文件时,编辑器会显示一个差异视图,突出显示与之前提交的文件相比的文件更改。

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

To stage a file, select the + (plus) icon next to the file in the Source Control view. This adds the file to the Staged Changes section, indicating that it will be included in the next commit. 要暂存文件,请在「源代码管理」视图中选择文件旁边的 +(加号)图标。这会将文件添加到暂存更改部分,表明它将包含在下一次提交中。

Source Control view with four changed files, highlighting the '+' button to stage the changes of a file

You can also stage all pending changes at once by selecting the + (plus) icon next to Changes in the Source Control view. 你还可以通过选择「源代码管理」视图中「更改」旁边的 +(加号)图标来立即暂存所有待处理的更改。

Staged changes can also be discarded by selecting the (minus) icon next to the file. Similarly, you can discard all staged changes by selecting the (minus) icon next to Staged Changes in the Source Control view. 还可以通过选择文件旁边的 -(减号)图标来放弃暂存更改。同样,你可以通过选择「源代码管理」视图中「暂存更改」旁边的 -(减号)图标来放弃所有暂存更改。

Source Control view with four changed files, highlighting the '-' button to unstage the changes of a file

To commit your staged changes, type a commit message in the upper text box, and then 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. 要提交暂存更改,请在上方文本框中键入提交消息,然后选择「提交」按钮。这会将你的更改保存到本地 Git 仓库,以便你可以在需要时恢复到以前版本的代码。

Tip: If you have a GitHub Copilot subscription, and installed the Github Copilot extension, you can use the sparkle icon to generate a commit message. 提示:如果你有 GitHub Copilot 订阅,并安装了 Github Copilot 插件,则可以使用✨图标生成提交消息。

You can navigate through and review all local file changes and commits in the Timeline view available in the bottom of the Explorer view. 你可以在资源管理器视图底部的时间轴视图中导航并查看所有本地文件更改和提交。

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

推送和拉取远程更改

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. 提交到本地 Git 仓库后,你可以将它们推送到远程仓库。 Sync Changes 按钮指示将推送和拉取的提交数。选择 Sync Changes 按钮会下载(拉取)任何新的远程提交并将新的本地提交上传(推送)到远程仓库。

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. 提示:你可以启用 Git:自动获取设置以始终获取最新的远程提交指示器。

Push and pull can also be performed individually by using their respective commands. You can access these commands from the Source Control menu. 推送和拉取也可以使用各自的命令单独执行。你可以从源代码管理菜单访问这些命令。

Source Control menu that shows all source control commands

使用分支

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. 在 Git 中,分支允许你同时处理代码库的多个版本。这对于试验🧪新功能或进行大量代码更改而不影响主代码库非常有用。

The branch indicator in the Status bar shows the current branch and lets you switch to new and existing branches. 状态栏中的分支指示器显示当前分支并允许你切换到新分支和现有分支。

Branch indicator in the Status bar

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. 要创建新分支,请选择分支指示器,然后选择从当前分支或另一个本地分支创建它。输入新分支的名称并确认。 VS Code 创建一个新分支并切换到它,允许你在不影响主分支的情况下对代码进行更改。

Create branch quick prompt that shows when selecting the branch indicator

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. 提示:如果你使用 GitHub Pull Requests and Issues 插件,你可以直接从 Issue 创建分支,这样你就可以开始在新的本地分支中工作,并自动为你预填充拉取请求。

After you create a local branch, you can push the branch to the remote repository by selecting Publish Branch in the Source Control view. This creates a new branch on the remote repository, allowing you to collaborate with others in that branch. 创建本地分支后,你可以通过在「源代码管理」视图中选择「发布分支」将分支推送到远程仓库。这将在远程仓库上创建一个新分支,允许你与该分支中的其他人协作。

创建和审查 GitHub 拉取请求

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 enables teams to review and approve code changes before they are incorporated into the main codebase, ensuring that only high-quality changes are merged. 在 Git 和 GitHub 中,拉取请求 (PR) 是协作者审查代码更改并将其从单独分支合并到主分支的一种方式。这使得团队能够在将代码更改合并到主代码库之前对其进行审查和批准,从而确保仅合并高质量的更改。

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. 要在 VS Code 中使用拉取请求,你需要安装 GitHub 拉取请求和问题插件。此插件向 VS Code 添加了 PR 和问题跟踪功能,允许你从编辑器中创建、查看和合并 PR。

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 opens 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. 要创建 PR,请确保你位于与主分支不同的分支上,并将代码更改推送到远程仓库。在「源代码管理」视图中,选择「创建拉取请求」按钮。这将打开 PR 创建表单,你可以在其中输入 PR 的标题和描述,并选择将更改合并到哪个分支。选择「创建」以创建 PR。

Source Control view, highlighting the 'Create pull request' button

To review a PR, select the Review Pull Request button in the Source Control view, and select the PR you want to review. This opens 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. 要审查 PR,请在「源代码管理」视图中选择「审查拉取请求」按钮,然后选择要审查的 PR。这将在新的编辑器窗口中打开 PR,你可以在其中查看代码更改并留下评论。一旦你对代码更改感到满意,你可以选择「合并」按钮将 PR 合并到目标分支中。

Learn more about pull requests in VS Code's GitHub documentation. 在 VS Code 的 GitHub 文档中了解有关拉取请求的更多信息。

在内置终端中使用 Git

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 状态都保存在本地仓库中,因此你可以轻松地在 VS Code 的 UI、内置集成终端或 GitHub Desktop 等外部工具之间切换。你还可以将 VS Code 设置为默认 Git 编辑器,以便使用 VS Code 编辑提交消息和其他与 Git 相关的文件。

源代码控制常见问题解答

如何恢复或撤消 Git 提交?

Revert your last commit with the Git: Undo Last Commit command. This will reset your branch to the state right before you did the commit, including all changes. The command is also available as menu in More Actions ... under Commit on the top of the Source Control view. 使用 Git: Undo Last Commit 命令恢复上次提交。这会将你的分支重置为提交之前的状态,包括所有更改。该命令还可以在「源代码管理」视图顶部的「提交」下的「更多操作 ... 」中作为菜单使用。

如何重命名本地分支?

The Git: Rename Branch… command will prompt you for the new name. Git: Rename Branch… 命令将提示你输入新名称。

如何在提交之前撤消 git add ?

Added files listed in the Staged Changes can be unstaged with the - icon or by drag-and-drop. 可以使用 - 图标或通过拖放来取消暂存「暂存更改」中列出的添加文件。

如何编辑最近的提交消息?

To update the commit message for the last local commit use the Git: Commit Staged (Amend) command. It will open an editor to edit and save the last message. Make sure that no other changes are staged, as they would be included with the commit. 要更新上次本地提交的提交消息,请使用 Git: Commit Staged (Amend) 命令。它将打开一个编辑器来编辑并保存最后一条消息。确保没有暂存其他更改,因为它们将包含在提交中。

我初始化了我的存储库,但...菜单中的操作全部呈灰色

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: 要推送、拉取和同步,你需要设置 Git 源。你可以从存储库主机获取所需的 URL。获得该 URL 后,你需要通过运行几个命令行操作将其添加到 Git 设置中。例如:

 > git remote add origin https://github.com/<repo owner>/<repo name>.git
 > git push -u origin main

为什么拉取、推送和同步操作永远不会完成?

This usually means there is no credential management configured in Git and you're not getting credential prompts for some reason. 这通常意味着 Git 中没有配置凭据管理,并且由于某种原因你没有收到凭据提示。

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. 你始终可以设置凭据帮助程序,以便从远程服务器拉取和推送,而无需 VS Code 每次都提示你输入凭据。

如何通过需要多重身份验证的 Azure DevOps 组织登录 Git?

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. Git Credential Manager (GCM) 是推荐用于 Windows、macOS 和 Linux 的 Git 凭据帮助程序。如果你运行的是 Windows 版 Git,则已经为你安装并配置了 GCM。如果你在 macOS 或 Linux 上运行,GCM 自述文件包含设置说明。