蓝色天空网mbsky.com · 知识 · 实践 · 创造VS Code · 本地阅读预览
教程 / DevOps / 工程化 / VS Code

VSCode 版本控制

演示在 VS Code 源代码管理(Source Control)视图中使用内置 Git 集成完成仓库初始化、单文件或批量暂存更改以及填写提交消息执行本地提交。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

打开版本控制视图与初始化 Git 仓库

VS Code 通过原生集成 Git 提供可视化版本控制能力。点击左侧活动栏的“源代码管理 / 版本控制”图标即可打开对应面板;使用前需确保本机已安装 Git,若系统未检测到 Git,视图内会直接给出引导下载安装的入口按钮。

若当前打开的工作区尚未纳入版本管理,点击面板中的 “Initialize Repository(初始化仓库)” 按钮即可在项目根目录创建 `.git` 仓库。初始化完成后,视图会立即扫描并列出工作区中的新增与变更文件。

暂存文件变更与提交到本地仓库

准备提交前需将待纳入快照的文件加入暂存区(Staging Area):鼠标悬停于单个变更文件并点击右侧 `+` 图标可逐个暂存;鼠标悬停在“更改(Changes)”分组标题处并点击 “Stage All Changes(暂存所有更改)”,则一次性暂存全部变更文件。

完成暂存后,在面板顶部输入框填写清晰的提交消息(例如 `Add hello function`),点击 “Commit(提交)” 按钮即可把暂存区改动写入本地 Git 提交历史。本站离线状态机脚本已完整验证仓库初始化、单文件/全量暂存、空消息拦截及提交后工作区清空状态。

运行 Git 仓库初始化、单文件/全量暂存与提交消息校验离线状态机验证

python · 阅读源码
"""Offline VS Code Git Source Control workflow state machine verifier for Ch15."""
import hashlib
import json

VERSION = "CPython 3.12.14 offline VS Code Git Source Control verifier"


def check(name, summary, expected, actual):
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = []

    # Case 1: Initialize Repository -> untracked Changes -> stage single (+) -> Stage All Changes
    repo = {
        "initialized": False,
        "changes": {"app.js": "U", "index.html": "U"},
        "staged": {},
        "commits": [],
    }
    repo["initialized"] = True
    # Stage single file app.js
    repo["staged"]["app.js"] = repo["changes"].pop("app.js")
    after_single = (sorted(repo["changes"]), sorted(repo["staged"]))
    # Stage All Changes
    repo["staged"].update(repo["changes"])
    repo["changes"].clear()
    after_all = (sorted(repo["changes"]), sorted(repo["staged"]))
    cases.append(
        check(
            "git_repo_init_and_staging_state",
            "Verify Initialize Repository, single-file '+' staging, and Stage All Changes state transitions",
            {
                "initialized": True,
                "after_single_changes": ["index.html"],
                "after_single_staged": ["app.js"],
                "after_all_changes": [],
                "after_all_staged": ["app.js", "index.html"],
            },
            {
                "initialized": repo["initialized"],
                "after_single_changes": after_single[0],
                "after_single_staged": after_single[1],
                "after_all_changes": after_all[0],
                "after_all_staged": after_all[1],
            },
        )
    )

    # Case 2: Commit staged changes with message validation & commit log verification
    def commit_staged(r: dict, message: str) -> bool:
        if not message.strip() or not r["staged"]:
            return False
        digest = hashlib.sha1(f"{message}:{sorted(r['staged'])}".encode("utf-8")).hexdigest()[:7]
        r["commits"].append({"hash": digest, "message": message.strip(), "files": sorted(r["staged"])})
        r["staged"].clear()
        return True

    empty_rejected = not commit_staged(repo, "   ")
    ok = commit_staged(repo, "Add hello function")
    cases.append(
        check(
            "git_commit_and_history_log",
            "Verify empty commit message rejection, successful commit recording, and clean working tree",
            {
                "empty_message_rejected": True,
                "commit_succeeded": True,
                "commit_count": 1,
                "last_message": "Add hello function",
                "working_tree_clean": True,
            },
            {
                "empty_message_rejected": empty_rejected,
                "commit_succeeded": ok,
                "commit_count": len(repo["commits"]),
                "last_message": repo["commits"][-1]["message"],
                "working_tree_clean": not repo["changes"] and not repo["staged"],
            },
        )
    )

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 Initialize Repository、单文件 '+' 暂存、Stage All Changes、拒绝空白提交消息以及成功写入 'Add hello function' 后工作区归零。
运行 Git 仓库初始化、单文件/全量暂存与提交消息校验离线状态机验证

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:6ea854bfe0c4f475909e14ccdd6d90420549a3b5207e656806bd8e755f2063dc

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载VSCode 版本控制实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:316ab0bfbc7c4bd5510214193b1305ddf5b1c7dc8e4999a2552348531e96bb72

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 VS Code 源代码管理视图中,对单个文件点击 `+` 与对 Changes 栏点击 `Stage All Changes` 有什么区别?为什么提交前必须填写提交消息?

展开参考解答

点击单文件 `+` 仅将该文件移入暂存区便于拆分精细提交,而 `Stage All Changes` 会一次性暂存全部改动;清晰的提交消息用于记录本次变更意图,是团队审查与回溯历史的关键依据。

规范与官方依据