VSCode 版本控制
演示在 VS Code 源代码管理(Source Control)视图中使用内置 Git 集成完成仓库初始化、单文件或批量暂存更改以及填写提交消息执行本地提交。
学完这一章,你能够
- 演示在 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' 后工作区归零。
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2203.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2219.zip
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
点击单文件 `+` 仅将该文件移入暂存区便于拆分精细提交,而 `Stage All Changes` 会一次性暂存全部改动;清晰的提交消息用于记录本次变更意图,是团队审查与回溯历史的关键依据。