xb-init 2.6.1__tar.gz → 2.6.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. {xb_init-2.6.1 → xb_init-2.6.2}/.gitignore +2 -0
  2. {xb_init-2.6.1 → xb_init-2.6.2}/PKG-INFO +4 -4
  3. {xb_init-2.6.1 → xb_init-2.6.2}/README.md +3 -3
  4. {xb_init-2.6.1 → xb_init-2.6.2}/pyproject.toml +1 -1
  5. xb_init-2.6.2/tests/test_doctor.py +167 -0
  6. xb_init-2.6.2/xb/commands/doctor.py +318 -0
  7. {xb_init-2.6.1 → xb_init-2.6.2}/xb/commands/init.py +7 -2
  8. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/build.py.j2 +3 -2
  9. xb_init-2.6.1/xb/commands/doctor.py +0 -109
  10. {xb_init-2.6.1 → xb_init-2.6.2}/.github/workflows/ci.yml +0 -0
  11. {xb_init-2.6.1 → xb_init-2.6.2}/docs/screenshot.png +0 -0
  12. {xb_init-2.6.1 → xb_init-2.6.2}/tests/test_cli.py +0 -0
  13. {xb_init-2.6.1 → xb_init-2.6.2}/tests/test_config_form.py +0 -0
  14. {xb_init-2.6.1 → xb_init-2.6.2}/tests/test_template_render.py +0 -0
  15. {xb_init-2.6.1 → xb_init-2.6.2}/tests/test_update_templates.py +0 -0
  16. {xb_init-2.6.1 → xb_init-2.6.2}/tests/test_upgrade.py +0 -0
  17. {xb_init-2.6.1 → xb_init-2.6.2}/xb/__init__.py +0 -0
  18. {xb_init-2.6.1 → xb_init-2.6.2}/xb/cli.py +0 -0
  19. {xb_init-2.6.1 → xb_init-2.6.2}/xb/commands/__init__.py +0 -0
  20. {xb_init-2.6.1 → xb_init-2.6.2}/xb/commands/build.py +0 -0
  21. {xb_init-2.6.1 → xb_init-2.6.2}/xb/commands/dev.py +0 -0
  22. {xb_init-2.6.1 → xb_init-2.6.2}/xb/commands/upgrade.py +0 -0
  23. {xb_init-2.6.1 → xb_init-2.6.2}/xb/commands/version.py +0 -0
  24. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/api/__init__.py.j2 +0 -0
  25. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/api/config.py.j2 +0 -0
  26. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/api/ports.py.j2 +0 -0
  27. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/api/terminal/__init__.py.j2 +0 -0
  28. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/api/terminal/routes.py.j2 +0 -0
  29. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/api/update/__init__.py.j2 +0 -0
  30. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/app_version.py.j2 +0 -0
  31. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/backend_build.py.j2 +0 -0
  32. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/main.py.j2 +0 -0
  33. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/managers/__init__.py.j2 +0 -0
  34. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/managers/logger_manager.py.j2 +0 -0
  35. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/managers/path_manager.py.j2 +0 -0
  36. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/managers/privileged_manager.py.j2 +0 -0
  37. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/managers/secret_obfuscator.py.j2 +0 -0
  38. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/requirements.txt.j2 +0 -0
  39. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/services/__init__.py.j2 +0 -0
  40. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/services/feishu_client.py.j2 +0 -0
  41. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/backend/services/updater.py.j2 +0 -0
  42. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/configs/config_changes.json.j2 +0 -0
  43. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/configs/global_config.yaml.j2 +0 -0
  44. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/configs/secrets.yaml.example.j2 +0 -0
  45. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/launcher.js.j2 +0 -0
  46. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/main.js.j2 +0 -0
  47. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/package.json.j2 +0 -0
  48. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/port_diagnostics.js.j2 +0 -0
  49. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/preload.js.j2 +0 -0
  50. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/prepare.js.j2 +0 -0
  51. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/resources/polkit/privileged-helper.sh.j2 +0 -0
  52. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/resources/polkit/privileged.policy.j2 +0 -0
  53. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/resources/polkit/privileged.rules.j2 +0 -0
  54. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/resources/postinst.py.j2 +0 -0
  55. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/resources/postrm.py.j2 +0 -0
  56. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/electron/resources/uninstaller.nsh.j2 +0 -0
  57. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/index.html.j2 +0 -0
  58. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/package.json.j2 +0 -0
  59. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/App.vue.j2 +0 -0
  60. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/DashboardHome.vue.j2 +0 -0
  61. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/FileManager.vue.j2 +0 -0
  62. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/GitVersionBadge.vue.j2 +0 -0
  63. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/RefreshButton.vue.j2 +0 -0
  64. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/TerminalPanel.vue.j2 +0 -0
  65. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/TerminalView.vue.j2 +0 -0
  66. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/ThemeToggle.vue.j2 +0 -0
  67. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/version/CommitHistoryPanel.vue.j2 +0 -0
  68. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/components/version/UpdatePanel.vue.j2 +0 -0
  69. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/composables/useTerminalSessions.js.j2 +0 -0
  70. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/composables/useUpdate.js.j2 +0 -0
  71. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/main.js.j2 +0 -0
  72. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/src/style.css.j2 +0 -0
  73. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/frontend/vite.config.js.j2 +0 -0
  74. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/.gitignore.j2 +0 -0
  75. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/AGENTS.md.j2 +0 -0
  76. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/LICENSE.j2 +0 -0
  77. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/README.md.j2 +0 -0
  78. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/dev.py.j2 +0 -0
  79. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/docs/images/feishu-folder.png +0 -0
  80. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/docs/images/feishu-permission.png +0 -0
  81. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/docs/images/release-upload.png +0 -0
  82. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/docs/images/update-dialog.png +0 -0
  83. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/docs//350/207/252/345/212/250/346/233/264/346/226/260/350/257/264/346/230/216.md" +0 -0
  84. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/root/pyproject.toml.j2 +0 -0
  85. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/scripts/example.py.j2 +0 -0
  86. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/scripts/feishu_upload.py.j2 +0 -0
  87. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/version/hooks/pre-commit.py.j2 +0 -0
  88. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/version/scripts/gui_version_manager.py.j2 +0 -0
  89. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/version/scripts/install_hooks.py.j2 +0 -0
  90. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/version/scripts/version_manager.py.j2 +0 -0
  91. {xb_init-2.6.1 → xb_init-2.6.2}/xb/templates/version/scripts/web_version_manager.py.j2 +0 -0
  92. {xb_init-2.6.1 → xb_init-2.6.2}/xb/utils/__init__.py +0 -0
  93. {xb_init-2.6.1 → xb_init-2.6.2}/xb/utils/click_helpers.py +0 -0
  94. {xb_init-2.6.1 → xb_init-2.6.2}/xb/utils/config_form.py +0 -0
  95. {xb_init-2.6.1 → xb_init-2.6.2}/xb/utils/project.py +0 -0
  96. {xb_init-2.6.1 → xb_init-2.6.2}/xb/utils/template_engine.py +0 -0
  97. {xb_init-2.6.1 → xb_init-2.6.2}/xb/utils/validators.py +0 -0
  98. {xb_init-2.6.1 → xb_init-2.6.2}/xb/utils/version_check.py +0 -0
@@ -36,3 +36,5 @@ htmlcov/
36
36
  *.log
37
37
  .env
38
38
  .env.local
39
+
40
+ uv.lock
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: xb-init
3
- Version: 2.6.1
3
+ Version: 2.6.2
4
4
  Summary: Project management tool for UV + FastAPI + Vue3 + Electron desktop applications
5
5
  Project-URL: Homepage, https://github.com/xuebli/xb
6
6
  Project-URL: Documentation, https://github.com/xuebli/xb#readme
@@ -157,7 +157,7 @@ Electron 二进制镜像通过 `ELECTRON_MIRROR` 环境变量注入。
157
157
  | `xb build [all\|frontend\|backend\|electron]` | 构建项目 |
158
158
  | `xb build -f / -b / -e / -a` | 构建快捷 flag |
159
159
  | `xb version [patch\|minor\|major]` | 读取或更新版本号 |
160
- | `xb doctor` | 检查开发环境 |
160
+ | `xb doctor [--fix]` | 检查开发环境;`--fix` 自动安装 nrm/uv、交互式配置 git 身份 |
161
161
  | `xb --upgrade` | 升级 xb 到 PyPI 最新版本 |
162
162
 
163
163
  ## 应用图标
@@ -271,8 +271,8 @@ xb/
271
271
  ## 环境要求
272
272
 
273
273
  - **Python**: 3.12+
274
- - **Node.js**: 16+
275
- - **npm**: 8+
274
+ - **Node.js**: 20.19+(推荐 22 LTS;模板前端使用 Vite 8,Node 18 及以下会构建报错)
275
+ - **npm**: 10+
276
276
  - **uv**: 已安装
277
277
  - **OS**: Windows 10/11 或 Ubuntu/Debian
278
278
  - **Windows 终端**: 使用 `--terminal` 时自动安装 Windows 专用 `pywinpty`
@@ -128,7 +128,7 @@ Electron 二进制镜像通过 `ELECTRON_MIRROR` 环境变量注入。
128
128
  | `xb build [all\|frontend\|backend\|electron]` | 构建项目 |
129
129
  | `xb build -f / -b / -e / -a` | 构建快捷 flag |
130
130
  | `xb version [patch\|minor\|major]` | 读取或更新版本号 |
131
- | `xb doctor` | 检查开发环境 |
131
+ | `xb doctor [--fix]` | 检查开发环境;`--fix` 自动安装 nrm/uv、交互式配置 git 身份 |
132
132
  | `xb --upgrade` | 升级 xb 到 PyPI 最新版本 |
133
133
 
134
134
  ## 应用图标
@@ -242,8 +242,8 @@ xb/
242
242
  ## 环境要求
243
243
 
244
244
  - **Python**: 3.12+
245
- - **Node.js**: 16+
246
- - **npm**: 8+
245
+ - **Node.js**: 20.19+(推荐 22 LTS;模板前端使用 Vite 8,Node 18 及以下会构建报错)
246
+ - **npm**: 10+
247
247
  - **uv**: 已安装
248
248
  - **OS**: Windows 10/11 或 Ubuntu/Debian
249
249
  - **Windows 终端**: 使用 `--terminal` 时自动安装 Windows 专用 `pywinpty`
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "xb-init"
7
- version = "2.6.1"
7
+ version = "2.6.2"
8
8
  description = "Project management tool for UV + FastAPI + Vue3 + Electron desktop applications"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -0,0 +1,167 @@
1
+ import subprocess
2
+
3
+ from click.testing import CliRunner
4
+
5
+ import xb.commands.doctor as doctor_module
6
+ from xb import cli
7
+ from xb.commands.doctor import CheckResult, _fix_nrm
8
+
9
+
10
+ def test_doctor_plain_run_does_not_fix(monkeypatch):
11
+ called = []
12
+ monkeypatch.setattr(
13
+ doctor_module,
14
+ "_collect_checks",
15
+ lambda: [CheckResult("uv", False, "未找到", fixable=True)],
16
+ )
17
+ monkeypatch.setitem(doctor_module._FIXERS, "uv", lambda: called.append(1) or True)
18
+
19
+ result = CliRunner().invoke(cli.main, ["doctor"])
20
+
21
+ assert result.exit_code == 0
22
+ assert called == []
23
+ assert "需要处理" in result.output
24
+ assert "正在修复" not in result.output
25
+
26
+
27
+ def test_doctor_fix_invokes_fixer_and_rechecks(monkeypatch):
28
+ calls = []
29
+
30
+ def fake_checks():
31
+ return [
32
+ CheckResult("uv", False, "未找到", fixable=True),
33
+ CheckResult("Node.js", False, "未找到"),
34
+ ]
35
+
36
+ monkeypatch.setattr(doctor_module, "_collect_checks", fake_checks)
37
+ monkeypatch.setitem(doctor_module._FIXERS, "uv", lambda: calls.append("uv") or True)
38
+
39
+ result = CliRunner().invoke(cli.main, ["doctor", "--fix"])
40
+
41
+ assert result.exit_code == 0, result.output
42
+ assert calls == ["uv"]
43
+ assert "可自动修复" in result.output
44
+ assert "uv 已修复" in result.output
45
+ assert "修复后复查" in result.output
46
+ # Node.js 缺失不可自动修复,修复循环不应触碰它
47
+ assert "Node.js 已修复" not in result.output
48
+
49
+
50
+ def test_doctor_fix_reports_failure(monkeypatch):
51
+ monkeypatch.setattr(
52
+ doctor_module,
53
+ "_collect_checks",
54
+ lambda: [CheckResult("uv", False, "未找到", fixable=True)],
55
+ )
56
+ monkeypatch.setitem(doctor_module._FIXERS, "uv", lambda: False)
57
+
58
+ result = CliRunner().invoke(cli.main, ["doctor", "--fix"])
59
+
60
+ assert result.exit_code == 0
61
+ assert "uv 修复失败" in result.output
62
+
63
+
64
+ def test_doctor_fix_nothing_fixable(monkeypatch):
65
+ monkeypatch.setattr(
66
+ doctor_module,
67
+ "_collect_checks",
68
+ lambda: [CheckResult("Node.js", False, "未找到")],
69
+ )
70
+
71
+ result = CliRunner().invoke(cli.main, ["doctor", "--fix"])
72
+
73
+ assert result.exit_code == 0
74
+ assert "没有可自动修复的问题" in result.output
75
+
76
+
77
+ def test_doctor_fix_git_identity(monkeypatch):
78
+ commands = []
79
+
80
+ def fake_run(cmd, **kwargs):
81
+ commands.append(cmd)
82
+ return subprocess.CompletedProcess(cmd, 0)
83
+
84
+ monkeypatch.setattr(
85
+ doctor_module,
86
+ "_collect_checks",
87
+ lambda: [CheckResult("git 身份", False, "未配置 user.name, user.email", fixable=True)],
88
+ )
89
+ monkeypatch.setattr(doctor_module.shutil, "which", lambda name: "/usr/bin/git")
90
+ monkeypatch.setattr(doctor_module.subprocess, "run", fake_run)
91
+
92
+ result = CliRunner().invoke(cli.main, ["doctor", "--fix"], input="张三\nzhangsan@test.com\n")
93
+
94
+ assert result.exit_code == 0, result.output
95
+ assert ["git", "config", "--global", "user.name", "张三"] in commands
96
+ assert ["git", "config", "--global", "user.email", "zhangsan@test.com"] in commands
97
+ assert "git 身份 已修复" in result.output
98
+
99
+
100
+ def test_git_identity_check_in_collect_checks(monkeypatch):
101
+ monkeypatch.setattr(doctor_module.shutil, "which", lambda name: "/usr/bin/git")
102
+ monkeypatch.setattr(
103
+ doctor_module,
104
+ "_git_global_config",
105
+ lambda key: "xb-test" if key == "user.name" else None,
106
+ )
107
+ monkeypatch.setattr(doctor_module, "_command_version", lambda *a, **k: "v22.12.0")
108
+
109
+ checks = {item.name: item for item in doctor_module._collect_checks()}
110
+
111
+ assert checks["git 身份"].ok is False
112
+ assert "user.email" in checks["git 身份"].detail
113
+ assert checks["git 身份"].fixable is True
114
+ assert checks["uv"].fixable is True
115
+ assert checks["nrm (npm 源测速)"].fixable is True
116
+ assert checks["Node.js"].fixable is False
117
+
118
+
119
+ def test_version_tuple_parses_tool_output():
120
+ assert doctor_module._version_tuple("v22.23.2") == (22, 23, 2)
121
+ assert doctor_module._version_tuple("npm 10.9.8") == (10, 9, 8)
122
+ assert doctor_module._version_tuple("git version 2.43.0") == (2, 43, 0)
123
+ assert doctor_module._version_tuple("无版本号输出") is None
124
+ assert doctor_module._version_tuple(None) is None
125
+ assert doctor_module._version_tuple("") is None
126
+
127
+
128
+ def test_node_version_too_low_rejected(monkeypatch):
129
+ versions = {
130
+ "uv": "uv 0.12.8 (x86_64-unknown-linux-gnu)",
131
+ "node": "v18.19.0",
132
+ "npm": "9.8.1",
133
+ "git": "git version 2.43.0",
134
+ }
135
+ monkeypatch.setattr(doctor_module, "_command_version", lambda name, *a, **k: versions.get(name))
136
+ monkeypatch.setattr(doctor_module.shutil, "which", lambda name: None)
137
+
138
+ checks = {item.name: item for item in doctor_module._collect_checks()}
139
+
140
+ assert checks["Node.js"].ok is False
141
+ assert "版本过低" in checks["Node.js"].detail
142
+ assert "20.19" in checks["Node.js"].detail
143
+ assert checks["npm"].ok is False
144
+ assert checks["uv"].ok is True
145
+ assert checks["git"].ok is True
146
+
147
+
148
+ def test_node_version_met_passes(monkeypatch):
149
+ versions = {
150
+ "uv": "uv 0.12.8",
151
+ "node": "v20.19.0",
152
+ "npm": "10.9.8",
153
+ "git": "git version 2.43.0",
154
+ }
155
+ monkeypatch.setattr(doctor_module, "_command_version", lambda name, *a, **k: versions.get(name))
156
+ monkeypatch.setattr(doctor_module.shutil, "which", lambda name: None)
157
+
158
+ checks = {item.name: item for item in doctor_module._collect_checks()}
159
+
160
+ assert checks["Node.js"].ok is True
161
+ assert checks["npm"].ok is True
162
+
163
+
164
+ def test_fix_nrm_skips_without_npm(monkeypatch):
165
+ monkeypatch.setattr(doctor_module.shutil, "which", lambda name: None)
166
+
167
+ assert _fix_nrm() is False
@@ -0,0 +1,318 @@
1
+ """
2
+ xb doctor 命令实现
3
+ 检查本机运行 xb 生成项目所需的基础环境。
4
+
5
+ --fix 可自动修复的项:
6
+ - nrm 未安装:npm install -g nrm
7
+ - uv 未安装:官方安装脚本(Linux 走 curl | sh,Windows 走 PowerShell)
8
+ - git 身份未配置:交互式询问并写入 git config --global
9
+ 其余(Python 版本过低、Node.js/git/npm 缺失)只提示,不强修。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Callable
22
+
23
+ import click
24
+ from rich.console import Console
25
+ from rich.table import Table
26
+
27
+ from .. import __version__
28
+ from ..utils.click_helpers import HELP_CONTEXT, ChineseHelpCommand
29
+
30
+ console = Console()
31
+
32
+ UV_INSTALL_SH = "https://astral.sh/uv/install.sh"
33
+ UV_INSTALL_PS1 = "https://astral.sh/uv/install.ps1"
34
+
35
+ # 生成项目的最低版本要求:模板前端用 Vite 8(硬性要求 Node >= 20.19 / >= 22.12)
36
+ MIN_VERSIONS = {
37
+ "node": ((20, 19), "Vite 8 要求 Node >= 20.19,推荐 22 LTS"),
38
+ "npm": ((10,), "Node 20.19+/22 自带 npm 10"),
39
+ }
40
+
41
+ # nrm 未装时无法用 nrm 测速切源(先有鸡还是先有蛋),安装 nrm 本身直接走 npmmirror
42
+ NPM_INSTALL_REGISTRY = "https://registry.npmmirror.com"
43
+
44
+
45
+ @dataclass
46
+ class CheckResult:
47
+ name: str
48
+ ok: bool
49
+ detail: str
50
+ optional: bool = False # 缺失时可自动安装/稍后补装,不算阻塞项
51
+ fixable: bool = False # xb doctor --fix 可自动修复
52
+
53
+
54
+ def _command_version(command: str, args: list[str] | None = None) -> str | None:
55
+ path = shutil.which(command)
56
+ if not path:
57
+ return None
58
+
59
+ cmd = [command, *(args or ["--version"])]
60
+ try:
61
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=5, check=False)
62
+ except Exception:
63
+ return path
64
+
65
+ output = (result.stdout or result.stderr).strip().splitlines()
66
+ return output[0] if output else path
67
+
68
+
69
+ def _version_tuple(text: str | None) -> tuple[int, ...] | None:
70
+ """从版本输出中提取数字版本元组,如 'v22.23.2' -> (22, 23, 2)。"""
71
+ if not text:
72
+ return None
73
+ match = re.search(r"(\d+(?:\.\d+)+)", text)
74
+ if not match:
75
+ return None
76
+ return tuple(int(part) for part in match.group(1).split("."))
77
+
78
+
79
+ def _git_global_config(key: str) -> str | None:
80
+ """读取 git 全局配置项,未配置或 git 不可用时返回 None。"""
81
+ if not shutil.which("git"):
82
+ return None
83
+ try:
84
+ result = subprocess.run(
85
+ ["git", "config", "--global", "--get", key],
86
+ capture_output=True,
87
+ text=True,
88
+ timeout=5,
89
+ check=False,
90
+ )
91
+ except Exception:
92
+ return None
93
+ return (result.stdout or "").strip() or None
94
+
95
+
96
+ def _collect_checks() -> list[CheckResult]:
97
+ checks = [
98
+ CheckResult("Python", sys.version_info >= (3, 12), sys.version.split()[0]),
99
+ ]
100
+
101
+ for label, command in (
102
+ ("uv", "uv"),
103
+ ("Node.js", "node"),
104
+ ("npm", "npm"),
105
+ ("git", "git"),
106
+ ):
107
+ version = _command_version(command)
108
+ ok = version is not None
109
+ detail = version or "未找到"
110
+ minimum = MIN_VERSIONS.get(command)
111
+ if minimum and ok:
112
+ parsed = _version_tuple(version)
113
+ if parsed is not None and parsed < minimum[0]:
114
+ ok = False
115
+ detail = f"{version}(版本过低,{minimum[1]})"
116
+ checks.append(CheckResult(label, ok, detail, fixable=label == "uv"))
117
+
118
+ # 源管理工具:缺失时 init / build / dev.py 会自动安装,只作提醒不阻塞
119
+ version = _command_version("nrm")
120
+ checks.append(
121
+ CheckResult(
122
+ "nrm (npm 源测速)",
123
+ version is not None,
124
+ version or "未找到(xb doctor --fix 可安装)",
125
+ optional=True,
126
+ fixable=True,
127
+ )
128
+ )
129
+
130
+ # git 身份:git commit / xb init 自动提交首个 commit 需要
131
+ if shutil.which("git"):
132
+ user_name = _git_global_config("user.name")
133
+ user_email = _git_global_config("user.email")
134
+ if user_name and user_email:
135
+ detail = f"{user_name} <{user_email}>"
136
+ else:
137
+ missing = []
138
+ if not user_name:
139
+ missing.append("user.name")
140
+ if not user_email:
141
+ missing.append("user.email")
142
+ detail = f"未配置 {', '.join(missing)}(git commit 需要)"
143
+ checks.append(CheckResult("git 身份", bool(user_name and user_email), detail, fixable=True))
144
+
145
+ return checks
146
+
147
+
148
+ def _fix_nrm() -> bool:
149
+ npm = "npm.cmd" if os.name == "nt" else "npm"
150
+ if not shutil.which(npm):
151
+ console.print(" [yellow]跳过 nrm 安装:未找到 npm(请先安装 Node.js)[/yellow]")
152
+ return False
153
+ console.print(" [dim]正在安装 nrm(npm install -g nrm,走 npmmirror 镜像)...[/dim]")
154
+ try:
155
+ result = subprocess.run(
156
+ [npm, "install", "-g", "nrm", "--registry", NPM_INSTALL_REGISTRY],
157
+ capture_output=True,
158
+ text=True,
159
+ timeout=180,
160
+ check=False,
161
+ )
162
+ except Exception as e:
163
+ console.print(f" [yellow]nrm 安装失败: {e}[/yellow]")
164
+ return False
165
+ return result.returncode == 0
166
+
167
+
168
+ def _uv_installed_after_fix() -> bool:
169
+ if shutil.which("uv"):
170
+ return True
171
+ exe = "uv.exe" if os.name == "nt" else "uv"
172
+ return (Path.home() / ".local" / "bin" / exe).exists()
173
+
174
+
175
+ def _fix_uv() -> bool:
176
+ if os.name == "nt":
177
+ cmd = ["powershell", "-ExecutionPolicy", "ByPass", "-c", f"irm {UV_INSTALL_PS1} | iex"]
178
+ elif shutil.which("curl"):
179
+ cmd = ["sh", "-c", f"curl -LsSf {UV_INSTALL_SH} | sh"]
180
+ else:
181
+ console.print(
182
+ f" [yellow]跳过 uv 安装:未找到 curl(可手动执行: curl -LsSf {UV_INSTALL_SH} | sh)[/yellow]"
183
+ )
184
+ return False
185
+
186
+ console.print(" [dim]正在安装 uv(官方安装脚本)...[/dim]")
187
+ try:
188
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300, check=False)
189
+ except Exception as e:
190
+ console.print(f" [yellow]uv 安装失败: {e}[/yellow]")
191
+ return False
192
+
193
+ if result.returncode == 0 and _uv_installed_after_fix():
194
+ if not shutil.which("uv"):
195
+ console.print(" [dim]uv 安装到 ~/.local/bin,新开终端(PATH 生效)后可用[/dim]")
196
+ return True
197
+ return False
198
+
199
+
200
+ def _git_set_config(key: str, value: str) -> bool:
201
+ try:
202
+ result = subprocess.run(
203
+ ["git", "config", "--global", key, value],
204
+ capture_output=True,
205
+ text=True,
206
+ timeout=5,
207
+ check=False,
208
+ )
209
+ except Exception:
210
+ return False
211
+ return result.returncode == 0
212
+
213
+
214
+ def _fix_git_identity() -> bool:
215
+ if not shutil.which("git"):
216
+ console.print(" [yellow]跳过 git 身份配置:未找到 git[/yellow]")
217
+ return False
218
+ try:
219
+ name = click.prompt("请输入 git user.name", default="", show_default=False)
220
+ email = click.prompt("请输入 git user.email", default="", show_default=False)
221
+ except (click.Abort, EOFError):
222
+ return False
223
+ if not name and not email:
224
+ console.print(" [yellow]未输入任何内容,跳过 git 身份配置[/yellow]")
225
+ return False
226
+
227
+ ok = True
228
+ if name:
229
+ ok = _git_set_config("user.name", name) and ok
230
+ if email:
231
+ ok = _git_set_config("user.email", email) and ok
232
+ return ok
233
+
234
+
235
+ _FIXERS: dict[str, Callable[[], bool]] = {
236
+ "uv": _fix_uv,
237
+ "nrm (npm 源测速)": _fix_nrm,
238
+ "git 身份": _fix_git_identity,
239
+ }
240
+
241
+
242
+ def _run_fixers(checks: list[CheckResult]) -> tuple[int, int]:
243
+ """对失败且可修复的检查逐项执行修复,返回 (成功数, 失败数)。"""
244
+ fixed = failed = 0
245
+ for item in checks:
246
+ if item.ok or not item.fixable:
247
+ continue
248
+ fixer = _FIXERS.get(item.name)
249
+ if fixer is None:
250
+ continue
251
+ console.print(f"\n[bold cyan]>>>[/bold cyan] 正在修复: {item.name}")
252
+ try:
253
+ ok = fixer()
254
+ except Exception as e:
255
+ console.print(f" [red]✗[/red] 修复出错: {e}")
256
+ failed += 1
257
+ continue
258
+ if ok:
259
+ console.print(f" [green]✓[/green] {item.name} 已修复")
260
+ fixed += 1
261
+ else:
262
+ console.print(f" [red]✗[/red] {item.name} 修复失败,请按上方提示手动处理")
263
+ failed += 1
264
+ return fixed, failed
265
+
266
+
267
+ def _print_table(checks: list[CheckResult], fix: bool, heading: str = "环境检查") -> None:
268
+ console.print(f"[bold green]{heading}[/bold green] [dim]xb {__version__}[/dim]")
269
+
270
+ table = Table(show_header=True, header_style="bold cyan")
271
+ table.add_column("项目")
272
+ table.add_column("状态")
273
+ table.add_column("详情")
274
+
275
+ for item in checks:
276
+ if item.ok:
277
+ status = "[green]通过[/green]"
278
+ elif fix and item.fixable:
279
+ status = "[cyan]可自动修复[/cyan]"
280
+ elif item.optional:
281
+ status = "[yellow]可自动安装[/yellow]"
282
+ else:
283
+ status = "[red]需要处理[/red]"
284
+ table.add_row(item.name, status, item.detail)
285
+
286
+ console.print(table)
287
+
288
+
289
+ @click.command(cls=ChineseHelpCommand, context_settings=HELP_CONTEXT)
290
+ @click.option("--fix", is_flag=True, help="自动修复可处理的问题(安装 nrm/uv、配置 git 身份)。")
291
+ def doctor(fix: bool) -> None:
292
+ """检查 xb 开发环境"""
293
+ checks = _collect_checks()
294
+ _print_table(checks, fix=fix)
295
+
296
+ if not fix:
297
+ blocking_failed = any(not item.ok and not item.optional for item in checks)
298
+ if blocking_failed:
299
+ console.print(
300
+ "[yellow]提示:[/yellow] 缺失或版本过低的工具可手动安装/升级后重新运行 xb doctor 检查。"
301
+ )
302
+ return
303
+
304
+ fixed, failed = _run_fixers(checks)
305
+ if fixed == 0 and failed == 0:
306
+ console.print("[dim]没有可自动修复的问题。[/dim]")
307
+ return
308
+
309
+ rechecks = _collect_checks()
310
+ console.print()
311
+ _print_table(rechecks, fix=False, heading="修复后复查")
312
+
313
+ remaining = [item.name for item in rechecks if not item.ok and not item.optional]
314
+ if remaining:
315
+ console.print(
316
+ f"[yellow]提示:[/yellow] 仍有未解决项: {', '.join(remaining)},"
317
+ "可手动处理后重新运行 xb doctor 检查。"
318
+ )
@@ -25,6 +25,9 @@ from .upgrade import install_upgrade
25
25
 
26
26
  console = Console()
27
27
 
28
+ # nrm 未装时无法用 nrm 测速切源(先有鸡还是先有蛋),安装 nrm 本身直接走 npmmirror
29
+ NPM_INSTALL_REGISTRY = "https://registry.npmmirror.com"
30
+
28
31
 
29
32
  def _prompt_upgrade_before_init() -> None:
30
33
  """检测到新版 xb 时询问是否先升级;同意则升级后用 execvp 重跑 init 替换当前进程。
@@ -168,9 +171,11 @@ def nrm_speedtest(console: Console, npm_command: str) -> None:
168
171
  nrm_command = "nrm.cmd" if os.name == "nt" and shutil.which("nrm.cmd") else "nrm"
169
172
  try:
170
173
  if not shutil.which(nrm_command):
171
- console.print("[dim]未检测到 nrm,自动安装(npm install -g nrm)...[/dim]")
174
+ console.print(
175
+ "[dim]未检测到 nrm,自动安装(npm install -g nrm,走 npmmirror 镜像)...[/dim]"
176
+ )
172
177
  subprocess.run(
173
- [npm_command, "install", "-g", "nrm"],
178
+ [npm_command, "install", "-g", "nrm", "--registry", NPM_INSTALL_REGISTRY],
174
179
  capture_output=True,
175
180
  text=True,
176
181
  timeout=120,
@@ -162,8 +162,9 @@ def nrm_speedtest() -> None:
162
162
  """
163
163
  nrm = "nrm.cmd" if sys.platform == "win32" else "nrm"
164
164
  if not shutil.which("nrm"):
165
- print("未检测到 nrm,自动安装(npm install -g nrm)...")
166
- run([NPM, "install", "-g", "nrm"])
165
+ print("未检测到 nrm,自动安装(npm install -g nrm,走 npmmirror 镜像)...")
166
+ # nrm 未装时无法用 nrm 切源,安装 nrm 本身直接走 npmmirror
167
+ run([NPM, "install", "-g", "nrm", "--registry", "https://registry.npmmirror.com"])
167
168
 
168
169
  try:
169
170
  # nrm test 测全部内置源,输出形如 " huawei ------- 96 ms",
@@ -1,109 +0,0 @@
1
- """
2
- xb doctor 命令实现
3
- 检查本机运行 xb 生成项目所需的基础环境。
4
- """
5
-
6
- from __future__ import annotations
7
-
8
- import shutil
9
- import socket
10
- import subprocess
11
- import sys
12
- from dataclasses import dataclass
13
-
14
- import click
15
- from rich.console import Console
16
- from rich.table import Table
17
-
18
- from .. import __version__
19
- from ..utils.click_helpers import HELP_CONTEXT, ChineseHelpCommand
20
-
21
- console = Console()
22
-
23
-
24
- @dataclass
25
- class CheckResult:
26
- name: str
27
- ok: bool
28
- detail: str
29
- optional: bool = False # 缺失时可自动安装/稍后补装,不算阻塞项
30
-
31
-
32
- def _command_version(command: str, args: list[str] | None = None) -> str | None:
33
- path = shutil.which(command)
34
- if not path:
35
- return None
36
-
37
- cmd = [command, *(args or ['--version'])]
38
- try:
39
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=5, check=False)
40
- except Exception:
41
- return path
42
-
43
- output = (result.stdout or result.stderr).strip().splitlines()
44
- return output[0] if output else path
45
-
46
-
47
- def _port_is_free(port: int) -> bool:
48
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
49
- sock.settimeout(0.3)
50
- return sock.connect_ex(('127.0.0.1', port)) != 0
51
-
52
-
53
- def _collect_checks() -> list[CheckResult]:
54
- checks = [
55
- CheckResult('Python', sys.version_info >= (3, 12), sys.version.split()[0]),
56
- ]
57
-
58
- for label, command in (
59
- ('uv', 'uv'),
60
- ('Node.js', 'node'),
61
- ('npm', 'npm'),
62
- ('git', 'git'),
63
- ):
64
- version = _command_version(command)
65
- checks.append(CheckResult(label, version is not None, version or '未找到'))
66
-
67
- # 源管理工具:缺失时 init / build / dev.py 会自动安装,只作提醒不阻塞
68
- version = _command_version('nrm')
69
- checks.append(
70
- CheckResult(
71
- 'nrm (npm 源测速)',
72
- version is not None,
73
- version or '未找到(首次安装依赖/构建时自动安装)',
74
- optional=True,
75
- )
76
- )
77
-
78
- for port in (8000, 5173):
79
- free = _port_is_free(port)
80
- checks.append(CheckResult(f'端口 {port}', free, '可用' if free else '已被占用'))
81
-
82
- return checks
83
-
84
-
85
- @click.command(cls=ChineseHelpCommand, context_settings=HELP_CONTEXT)
86
- def doctor() -> None:
87
- """检查 xb 开发环境"""
88
- console.print(f'[bold green]环境检查[/bold green] [dim]xb {__version__}[/dim]')
89
-
90
- table = Table(show_header=True, header_style='bold cyan')
91
- table.add_column('项目')
92
- table.add_column('状态')
93
- table.add_column('详情')
94
-
95
- checks = _collect_checks()
96
- for item in checks:
97
- if item.ok:
98
- status = '[green]通过[/green]'
99
- elif item.optional:
100
- status = '[yellow]可自动安装[/yellow]'
101
- else:
102
- status = '[red]需要处理[/red]'
103
- table.add_row(item.name, status, item.detail)
104
-
105
- console.print(table)
106
-
107
- blocking_failed = any(not item.ok and not item.optional for item in checks)
108
- if blocking_failed:
109
- console.print('[yellow]提示:[/yellow] 端口占用可先停止相关服务,或修改生成项目的 configs/global_config.yaml。')
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes