Git in VS Code

VS Code · Practical · 12 min

Reviewing diffs and staging hunks visually is faster and less error-prone than doing everything on the command line.

VS Code's Source Control view (Ctrl+Shift+G) is a front-end to the git installed on your machine; it runs the same commands you know.

  • Changes lists modified files; clicking one opens a diff editor (left = HEAD or index, right = working tree).
  • The + icon stages a file (git add). In the diff editor you can stage or revert individual ranges via the gutter or by selecting lines and running "Stage Selected Ranges" — the GUI equivalent of git add -p.
  • Type a message and press Ctrl+Enter to commit what is staged.
  • The status bar shows the current branch (click to switch or create one) and a sync button that pulls then pushes.
  • The editor gutter shows coloured bars for added, modified and deleted lines; click one to see the change inline.

Merge conflicts open with inline "Accept Current / Accept Incoming / Accept Both" actions, and a three-way merge editor shows yours, theirs and the result side by side. After resolving, stage the file and commit as usual.

The Timeline view in the Explorer shows a file's commit history, and "Open Changes" on a commit diffs it. Popular extensions such as GitLens add blame annotations and richer history.

Whatever you click, the Git output is logged: open the Output panel and choose "Git" to see the exact commands VS Code ran, a great way to learn and debug.

Example

# Ctrl+Shift+G         open Source Control
# click file           diff editor: HEAD/index vs working tree
# +                    stage file          (git add file)
# select lines > right-click > Stage Selected Ranges   (like git add -p)
# message + Ctrl+Enter commit staged       (git commit -m)
# status bar branch    switch/create branch (git switch / -c)
# sync button          git pull then git push
# Output panel > Git   shows the real commands, e.g.
#   > git add -A -- /home/ann/shop/src/cart.ts
#   > git commit --quiet --allow-empty-message --file -

Remember

  • Source Control is a GUI over your local git
  • Stage files or selected ranges, Ctrl+Enter to commit
  • Output > Git shows the exact git commands run

Watch out for

  • Pressing Sync without checking what it will push and pull; it runs pull and push together.

Check yourself

  1. How do you stage only some changed lines of a file in VS Code?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: code.visualstudio.com/docs/sourcecontrol/overview