dsh-stm32 0.1.7 → 0.1.9

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 (153) hide show
  1. package/README.md +567 -516
  2. package/README_EN.md +544 -510
  3. package/client/client.js +7033 -682
  4. package/docs/reading-guide.md +921 -859
  5. package/lib/client.js +7033 -682
  6. package/lib/commands/register.js +2 -0
  7. package/lib/data/firmware-packages.js +35 -0
  8. package/lib/data/firmware-pins.js +7 -0
  9. package/lib/data/install-guides.js +110 -0
  10. package/lib/data/ioc-presets.js +118 -0
  11. package/lib/engine/artifacts.js +123 -0
  12. package/lib/engine/breakpoint-hits.js +73 -0
  13. package/lib/engine/build.js +161 -5
  14. package/lib/engine/channel-tap.js +227 -0
  15. package/lib/engine/channels.js +48 -0
  16. package/lib/engine/clocks.js +192 -0
  17. package/lib/engine/datasheet/auto.js +74 -0
  18. package/lib/engine/datasheet/digest.js +74 -0
  19. package/lib/engine/datasheet/lcsc.js +60 -0
  20. package/lib/engine/datasheet/pinout.js +119 -0
  21. package/lib/engine/datasheet/price.js +152 -0
  22. package/lib/engine/datasheet/search.js +147 -0
  23. package/lib/engine/datasheet/store.js +371 -0
  24. package/lib/engine/debug-session.js +48 -2
  25. package/lib/engine/ecad/autobuild.js +156 -0
  26. package/lib/engine/ecad/bom.js +238 -0
  27. package/lib/engine/ecad/brief.js +205 -0
  28. package/lib/engine/ecad/checks.js +239 -0
  29. package/lib/engine/ecad/design.js +177 -0
  30. package/lib/engine/ecad/dfm.js +314 -0
  31. package/lib/engine/ecad/easyeda.js +454 -0
  32. package/lib/engine/ecad/fabrication.js +104 -0
  33. package/lib/engine/ecad/gen/footprint.js +159 -0
  34. package/lib/engine/ecad/gen/symbol.js +103 -0
  35. package/lib/engine/ecad/import.js +372 -0
  36. package/lib/engine/ecad/jlcpcb.js +141 -0
  37. package/lib/engine/ecad/libs.js +316 -0
  38. package/lib/engine/ecad/models3d.js +89 -0
  39. package/lib/engine/ecad/netgate.js +286 -0
  40. package/lib/engine/ecad/normalize.js +182 -0
  41. package/lib/engine/ecad/package.js +126 -0
  42. package/lib/engine/ecad/padmerge.js +128 -0
  43. package/lib/engine/ecad/padprecheck.js +123 -0
  44. package/lib/engine/ecad/part-import.js +257 -0
  45. package/lib/engine/ecad/pcb/apply.js +53 -0
  46. package/lib/engine/ecad/pcb/emc-deep.js +396 -0
  47. package/lib/engine/ecad/pcb/emc.js +275 -0
  48. package/lib/engine/ecad/pcb/geometry.js +63 -0
  49. package/lib/engine/ecad/pcb/gerber.js +499 -0
  50. package/lib/engine/ecad/pcb/hand-sync.js +242 -0
  51. package/lib/engine/ecad/pcb/impedance.js +119 -0
  52. package/lib/engine/ecad/pcb/ipc-open.js +78 -0
  53. package/lib/engine/ecad/pcb/ipc-script.js +276 -0
  54. package/lib/engine/ecad/pcb/ipc.js +129 -0
  55. package/lib/engine/ecad/pcb/krt.js +182 -0
  56. package/lib/engine/ecad/pcb/links.js +393 -0
  57. package/lib/engine/ecad/pcb/mech.js +201 -0
  58. package/lib/engine/ecad/pcb/model-fix.js +178 -0
  59. package/lib/engine/ecad/pcb/netlist.js +146 -0
  60. package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
  61. package/lib/engine/ecad/pcb/placement.js +140 -0
  62. package/lib/engine/ecad/pcb/power.js +203 -0
  63. package/lib/engine/ecad/pcb/render3d.js +208 -0
  64. package/lib/engine/ecad/pcb/route.js +167 -0
  65. package/lib/engine/ecad/pcb/router.js +469 -0
  66. package/lib/engine/ecad/pcb/rules.js +122 -0
  67. package/lib/engine/ecad/pcb/scene.js +513 -0
  68. package/lib/engine/ecad/pcb/stackup.js +154 -0
  69. package/lib/engine/ecad/pcb/swap.js +222 -0
  70. package/lib/engine/ecad/pcb/tracks.js +70 -0
  71. package/lib/engine/ecad/runtime.js +227 -0
  72. package/lib/engine/ecad/toolchain.js +146 -0
  73. package/lib/engine/ecad/tsci.js +362 -0
  74. package/lib/engine/ecad/zip.js +98 -0
  75. package/lib/engine/event-bus.js +158 -0
  76. package/lib/engine/event-log.js +335 -0
  77. package/lib/engine/fault-hints.js +146 -0
  78. package/lib/engine/generate-script.js +4 -1
  79. package/lib/engine/generate.js +145 -5
  80. package/lib/engine/interrupts.js +247 -0
  81. package/lib/engine/ioc-diff.js +369 -0
  82. package/lib/engine/ioc-plan.js +12 -2
  83. package/lib/engine/ioc-sync.js +58 -0
  84. package/lib/engine/mcu-info.js +134 -0
  85. package/lib/engine/msys2-install.js +31 -6
  86. package/lib/engine/panel-actions.js +103 -0
  87. package/lib/engine/pdf/curve.js +321 -0
  88. package/lib/engine/pdf/png.js +83 -0
  89. package/lib/engine/pdf/reader.js +336 -0
  90. package/lib/engine/pdf/schematic.js +93 -0
  91. package/lib/engine/pdf/tables.js +249 -0
  92. package/lib/engine/pdf/toolchain.js +50 -0
  93. package/lib/engine/pinout.js +140 -0
  94. package/lib/engine/probe-info.js +95 -0
  95. package/lib/engine/probe.js +45 -0
  96. package/lib/engine/progress.js +99 -0
  97. package/lib/engine/project-conf.js +254 -0
  98. package/lib/engine/project-layout.js +198 -0
  99. package/lib/engine/project-repair.js +205 -0
  100. package/lib/engine/schematic/checks.js +153 -0
  101. package/lib/engine/schematic/draw.js +390 -0
  102. package/lib/engine/schematic/edit.js +229 -0
  103. package/lib/engine/schematic/kicad-sch.js +225 -0
  104. package/lib/engine/schematic/model.js +442 -0
  105. package/lib/engine/schematic/nets.js +219 -0
  106. package/lib/engine/schematic/pcb.js +144 -0
  107. package/lib/engine/schematic/review.js +134 -0
  108. package/lib/engine/schematic/sexpr.js +134 -0
  109. package/lib/engine/schematic/to-ioc.js +197 -0
  110. package/lib/engine/schematic/transform.js +25 -0
  111. package/lib/engine/session-context.js +106 -0
  112. package/lib/engine/source-slice.js +59 -0
  113. package/lib/engine/tool-events.js +119 -0
  114. package/lib/engine/toolchain-gate.js +8 -0
  115. package/lib/engine/watch-admin.js +101 -0
  116. package/lib/engine/watch-record.js +39 -0
  117. package/lib/engine/watch-recorder.js +116 -0
  118. package/lib/engine/web-api.js +1123 -4
  119. package/lib/engine/web-routes.js +18 -1
  120. package/lib/engine/workspace-memo.js +41 -0
  121. package/lib/index.js +118 -24
  122. package/lib/skill/stm32-workflow.js +1 -1
  123. package/lib/tools/build.js +10 -2
  124. package/lib/tools/code-patch.js +2 -2
  125. package/lib/tools/datasheet.js +447 -0
  126. package/lib/tools/debug-session.js +9 -4
  127. package/lib/tools/debug.js +2 -2
  128. package/lib/tools/doctor.js +2 -2
  129. package/lib/tools/ecad.js +903 -0
  130. package/lib/tools/flash.js +2 -2
  131. package/lib/tools/gen.js +166 -0
  132. package/lib/tools/generate.js +7 -5
  133. package/lib/tools/import-circuit.js +146 -0
  134. package/lib/tools/ioc-apply.js +11 -2
  135. package/lib/tools/ioc-inspect.js +2 -2
  136. package/lib/tools/ioc-plan.js +2 -2
  137. package/lib/tools/ioc-verify.js +2 -2
  138. package/lib/tools/layout.js +92 -0
  139. package/lib/tools/mcu-info.js +163 -0
  140. package/lib/tools/part-import.js +182 -0
  141. package/lib/tools/pcb.js +2316 -0
  142. package/lib/tools/pdf.js +423 -0
  143. package/lib/tools/project-create.js +28 -0
  144. package/lib/tools/project-dir.js +25 -1
  145. package/lib/tools/regs.js +2 -2
  146. package/lib/tools/route-plan.js +2 -2
  147. package/lib/tools/rtt.js +10 -2
  148. package/lib/tools/sch-draw.js +433 -0
  149. package/lib/tools/sch-edit.js +145 -0
  150. package/lib/tools/schematic.js +817 -0
  151. package/lib/tools/serial.js +22 -0
  152. package/lib/tools/watch.js +24 -2
  153. package/package.json +1 -1
@@ -0,0 +1,254 @@
1
+ /**
2
+ * `dsh-stm32.conf`:工程与工作区的自描述文件(S81)。
3
+ *
4
+ * 两处同名文件、两种用途:
5
+ * - 工程根:记录检测这个工程需要的最小事实(型号、.ioc、构建配置名)。
6
+ * - 工作区根:记录这个工作区里有哪些工程,供面板的工程选择器用。
7
+ *
8
+ * 格式是有意的极简 `key=value`:一行一条、`#` 开头是注释、`project=` 可重复。
9
+ * 不用 JSON——这个文件会被人手工改,多一行缩进就多一种改坏的方式。
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
12
+ import { basename, join, resolve } from "node:path";
13
+ /** 两个位置用同一个文件名。 */
14
+ export const CONF_FILE_NAME = "dsh-stm32.conf";
15
+ /**
16
+ * 工作区索引的规范位置(S128)。
17
+ *
18
+ * 索引与工程描述都是 `key=value`,放在同一个文件里就必然出现「这一行属于谁」的歧义;
19
+ * 从 S128 起索引单独放 `<工作区>/.dsh-stm32/workspace.conf`,工程根的
20
+ * `dsh-stm32.conf` 只写工程描述。旧位置仍可读,由 `planLayoutFix()` 迁移。
21
+ */
22
+ export const WORKSPACE_CONF_REL = ".dsh-stm32/workspace.conf";
23
+ /** 把文本解析成 `key=value` 文档;非法行跳过,不抛。 */
24
+ export function parseConf(text, confPath = "") {
25
+ const single = new Map();
26
+ const multi = new Map();
27
+ for (const line of text.split(/\r?\n/u)) {
28
+ const trimmed = line.trim();
29
+ if (trimmed === "" || trimmed.startsWith("#"))
30
+ continue;
31
+ const eq = trimmed.indexOf("=");
32
+ if (eq <= 0)
33
+ continue;
34
+ const key = trimmed.slice(0, eq).trim();
35
+ const value = trimmed.slice(eq + 1).trim();
36
+ if (key === "")
37
+ continue;
38
+ if (key === "project") {
39
+ const list = multi.get(key) ?? [];
40
+ list.push(value);
41
+ multi.set(key, list);
42
+ continue;
43
+ }
44
+ if (!single.has(key))
45
+ single.set(key, value);
46
+ }
47
+ return { path: confPath, single, multi };
48
+ }
49
+ /** 读文件;不存在或读不了一律返回空文档,由调用方按「没有描述」处理。 */
50
+ export function readConf(confPath) {
51
+ try {
52
+ return parseConf(readFileSync(confPath, "utf8"), confPath);
53
+ }
54
+ catch {
55
+ return parseConf("", confPath);
56
+ }
57
+ }
58
+ /** 工作区根:相对路径解析到这里。 */
59
+ function resolveWorkspaceRoot(workspaceRoot) {
60
+ const trimmed = workspaceRoot.trim();
61
+ return resolve(trimmed === "" ? process.cwd() : trimmed);
62
+ }
63
+ /** 读工作区索引:`project=` 每行一个,可写目录名或相对路径。 */
64
+ export function readWorkspaceIndex(workspaceRoot) {
65
+ const root = resolveWorkspaceRoot(workspaceRoot);
66
+ const confPath = join(root, WORKSPACE_CONF_REL);
67
+ const legacyPath = join(root, CONF_FILE_NAME);
68
+ // 新位置优先;没有就退回旧位置(工程根的 dsh-stm32.conf)。
69
+ const doc = readConf(existsSync(confPath) ? confPath : legacyPath);
70
+ const names = doc.multi.get("project") ?? [];
71
+ const seen = new Set();
72
+ const projects = [];
73
+ for (const raw of names) {
74
+ const dir = resolve(root, raw);
75
+ if (seen.has(dir))
76
+ continue;
77
+ seen.add(dir);
78
+ projects.push({ name: basename(dir), dir, exists: existsSync(dir) });
79
+ }
80
+ // exists 表示「索引存在」,新旧两个位置都算;confPath 仍是新位置,写入只写它。
81
+ return { workspaceRoot: root, confPath, exists: existsSync(confPath) || existsSync(legacyPath), projects };
82
+ }
83
+ /** 把工程登记进工作区索引;已存在则不重复写,返回是否真的追加了。 */
84
+ export function registerWorkspaceProject(workspaceRoot, projectDir) {
85
+ const root = resolveWorkspaceRoot(workspaceRoot);
86
+ const target = resolve(projectDir);
87
+ const index = readWorkspaceIndex(root);
88
+ if (index.projects.some((item) => item.dir === target))
89
+ return false;
90
+ // 用相对于工作区根的路径,工作区整体搬家后仍然成立。
91
+ const relative = target.startsWith(root + "\\") || target.startsWith(root + "/")
92
+ ? target.slice(root.length + 1).replace(/\\/gu, "/")
93
+ : target.replace(/\\/gu, "/");
94
+ const header = [
95
+ "# dsh-stm32 工作区索引:由插件写入,手工增删也可。",
96
+ "# 一行一个工程,写相对路径或目录名。",
97
+ "version=1",
98
+ ].join("\n");
99
+ const body = index.exists ? readFileSync(index.confPath, "utf8").replace(/\s*$/u, "\n") : header + "\n";
100
+ try {
101
+ mkdirSync(join(root, ".dsh-stm32"), { recursive: true });
102
+ writeFileSync(index.confPath, body + "project=" + relative + "\n", "utf8");
103
+ return true;
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ }
109
+ /** 读工程描述;缺字段返回空串,面板据此判断「这个工程还没被插件创建过」。 */
110
+ export function readProjectConf(projectDir) {
111
+ const dir = resolve(projectDir.trim() === "" ? "." : projectDir);
112
+ const confPath = join(dir, CONF_FILE_NAME);
113
+ const doc = readConf(confPath);
114
+ return {
115
+ projectDir: dir,
116
+ confPath,
117
+ exists: existsSync(confPath),
118
+ name: doc.single.get("name") ?? basename(dir),
119
+ mcu: doc.single.get("mcu") ?? "",
120
+ ioc: doc.single.get("ioc") ?? "",
121
+ build: doc.single.get("build") ?? "",
122
+ firmware: doc.single.get("firmware") ?? "",
123
+ hardware: doc.single.get("hardware") ?? "",
124
+ };
125
+ }
126
+ /**
127
+ * 写工程描述:只写检测该工程所需的最小事实,写入是覆盖式的。
128
+ *
129
+ * `createdAt` 保留首次创建时间——重写不改变它,便于回答「这个工程什么时候建的」。
130
+ */
131
+ export function writeProjectConf(projectDir, facts) {
132
+ const dir = resolve(projectDir.trim() === "" ? "." : projectDir);
133
+ const confPath = join(dir, CONF_FILE_NAME);
134
+ const existing = readConf(confPath);
135
+ const createdAt = existing.single.get("createdAt") ?? new Date().toISOString();
136
+ // 工作区根与工程根可能是同一个目录(工程即工作区):同一份文件里既有
137
+ // `project=` 索引,也有工程事实。重写时保留所有非本函数管辖的行,
138
+ // 否则每写一次工程描述就会把工作区索引删掉(S96)。
139
+ const managed = new Set(["version", "name", "mcu", "ioc", "build", "firmware", "hardware", "createdAt"]);
140
+ const kept = [];
141
+ try {
142
+ for (const raw of readFileSync(confPath, "utf8").split(/\r?\n/u)) {
143
+ const line = raw.trim();
144
+ if (line === "" || line.startsWith("#"))
145
+ continue;
146
+ const eq = line.indexOf("=");
147
+ if (eq <= 0)
148
+ continue;
149
+ const key = line.slice(0, eq).trim();
150
+ if (managed.has(key))
151
+ continue;
152
+ kept.push(line);
153
+ }
154
+ }
155
+ catch {
156
+ /* 首次写入:没有可保留的行 */
157
+ }
158
+ const lines = [
159
+ "# dsh-stm32 工程描述:由插件写入,手工改也可。",
160
+ "version=1",
161
+ "name=" + (facts.name ?? existing.single.get("name") ?? basename(dir)),
162
+ "mcu=" + (facts.mcu ?? existing.single.get("mcu") ?? ""),
163
+ "ioc=" + (facts.ioc ?? existing.single.get("ioc") ?? ""),
164
+ "build=" + (facts.build ?? existing.single.get("build") ?? ""),
165
+ "firmware=" + (facts.firmware ?? existing.single.get("firmware") ?? ""),
166
+ "hardware=" + (facts.hardware ?? existing.single.get("hardware") ?? ""),
167
+ "createdAt=" + createdAt,
168
+ ...kept,
169
+ ];
170
+ try {
171
+ mkdirSync(dir, { recursive: true });
172
+ writeFileSync(confPath, lines.join("\n") + "\n", "utf8");
173
+ return true;
174
+ }
175
+ catch {
176
+ return false;
177
+ }
178
+ }
179
+ /**
180
+ * 扫描工作区里的工程(S82):深度 ≤2 的目录里,含 `*.ioc` 或 `CMakeLists.txt` 就算一个。
181
+ *
182
+ * 只在工作区索引缺失或用户想「找回来」时用;结果与索引合并展示,不写回索引。
183
+ */
184
+ export function scanWorkspaceProjects(workspaceRoot, maxDepth = 2) {
185
+ const root = resolveWorkspaceRoot(workspaceRoot);
186
+ const found = [];
187
+ /** 目录是不是一个工程:认四种标记里的任意一种(S95)。 */
188
+ const isProjectDir = (dir) => {
189
+ let names = [];
190
+ try {
191
+ names = readdirSync(dir, { withFileTypes: true })
192
+ .filter((item) => item.isFile())
193
+ .map((item) => item.name);
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ if (names.some((name) => name.endsWith(".ioc") || name === "CMakeLists.txt"))
199
+ return true;
200
+ if (names.some((name) => name.endsWith(".kicad_pro")))
201
+ return true;
202
+ // 单有 conf 不算工程:工作区根也用同名文件,它记的是索引而不是工程事实。
203
+ // 只有写了工程字段(mcu= / firmware= / hardware=)的 conf 才算。
204
+ if (names.includes(CONF_FILE_NAME)) {
205
+ try {
206
+ const text = readFileSync(join(dir, CONF_FILE_NAME), "utf8");
207
+ if (/^(mcu|firmware|hardware)=/mu.test(text))
208
+ return true;
209
+ }
210
+ catch {
211
+ /* 读不了就按「不是工程」处理 */
212
+ }
213
+ }
214
+ // 约定式工程:根上没有标记,但程序与硬件各在一个子目录里。
215
+ try {
216
+ const dirs = readdirSync(dir, { withFileTypes: true })
217
+ .filter((item) => item.isDirectory())
218
+ .map((item) => item.name.toLowerCase());
219
+ return dirs.includes("program") || dirs.includes("firmware") || dirs.includes("hardware");
220
+ }
221
+ catch {
222
+ return false;
223
+ }
224
+ };
225
+ /** 往下扫时跳过的目录:构建产物、工具链源码、插件自有数据。 */
226
+ const skip = new Set(["build", "drivers", "node_modules", ".dsh-stm32", "cmake", "gerber", "bom", "core"]);
227
+ // 工作区根自己就是工程时只列它一个:再往下扫必然扫到工程内部构件(S84 的教训)。
228
+ if (isProjectDir(root))
229
+ return [{ name: basename(root), dir: root, exists: true }];
230
+ const walk = (dir, depth) => {
231
+ if (depth > maxDepth)
232
+ return;
233
+ let entries = [];
234
+ try {
235
+ entries = readdirSync(dir, { withFileTypes: true })
236
+ .filter((item) => item.isDirectory() && !item.name.startsWith(".") && !skip.has(item.name.toLowerCase()))
237
+ .map((item) => item.name);
238
+ }
239
+ catch {
240
+ return;
241
+ }
242
+ for (const name of entries) {
243
+ const child = join(dir, name);
244
+ if (isProjectDir(child)) {
245
+ found.push({ name, dir: child, exists: true });
246
+ // 工程内部不再下钻:里面的 program/、hardware/ 是它的组成部分,不是兄弟工程。
247
+ continue;
248
+ }
249
+ walk(child, depth + 1);
250
+ }
251
+ };
252
+ walk(root, 1);
253
+ return found;
254
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * 工程目录约定(S95)。
3
+ *
4
+ * 一个工程根下允许分成几块,各自独立演进:
5
+ *
6
+ * ```
7
+ * <project>/
8
+ * program/ STM32 程序:.ioc 与 CMakeLists.txt(缺省名,可用 conf 改)
9
+ * hardware/ KiCad 工程:.kicad_pro 与 .kicad_sch(缺省名,可用 conf 改)
10
+ * .dsh-stm32/ 插件自己的数据(证据、备份、快照),类似 .vscode
11
+ * dsh-stm32.conf
12
+ * ```
13
+ *
14
+ * 为什么不是「把所有东西都放根目录」:程序目录与硬件目录来自不同工具链,
15
+ * 版本节奏也不同(硬件改版比代码慢得多),混在一起时两边都会扫到对方的中间产物。
16
+ *
17
+ * 兼容:老工程把程序放在根目录(`.ioc` 就在根上)时 `firmwareDir` 等于根,
18
+ * 行为与改造前一致;`hardwareDir` 找不到时返回空串,由调用方给出「没有原理图」的提示。
19
+ */
20
+ import { existsSync, readdirSync } from "node:fs";
21
+ import { dirname, join, relative, resolve } from "node:path";
22
+ import { readProjectConf, readWorkspaceIndex } from "./project-conf.js";
23
+ /** 程序目录的候选名,按优先级排;`""` 表示根目录本身。 */
24
+ const FIRMWARE_CANDIDATES = ["program", "firmware", "app", "user", "fw", "code", ""];
25
+ /** KiCad 目录的候选名,按优先级排。 */
26
+ const HARDWARE_CANDIDATES = ["hardware", "kicad", "hw", "pcb"];
27
+ /** 扫描 KiCad 工程时跳过的目录名:历史版本、构建产物、插件自己的数据。 */
28
+ const SCAN_SKIP = [".history", "build", "node_modules", ".dsh-stm32", "Gerber", "bom"];
29
+ function isDir(path) {
30
+ try {
31
+ return existsSync(path) && readdirSync(path) !== null;
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ function hasFile(dir, predicate) {
38
+ try {
39
+ return readdirSync(dir, { withFileTypes: true }).some((item) => item.isFile() && predicate(item.name));
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ function hasFirmwareMarker(dir) {
46
+ return hasFile(dir, (name) => name.endsWith(".ioc") || name === "CMakeLists.txt");
47
+ }
48
+ function hasKicadMarker(dir) {
49
+ return hasFile(dir, (name) => name.endsWith(".kicad_pro") || name.endsWith(".kicad_sch"));
50
+ }
51
+ /** 在 root 下按深度找第一个含 KiCad 标记的目录(只在候选名都不命中时用)。 */
52
+ function findKicadDir(root, depth) {
53
+ if (depth > 2)
54
+ return "";
55
+ let entries = [];
56
+ try {
57
+ entries = readdirSync(root, { withFileTypes: true })
58
+ .filter((item) => item.isDirectory() &&
59
+ !item.name.startsWith(".") &&
60
+ !SCAN_SKIP.includes(item.name) &&
61
+ // 手绘层(S174)放在 hardware/schematic,它也有 .kicad_sch,但不能当 KiCad 工程目录。
62
+ item.name !== "schematic")
63
+ .map((item) => item.name);
64
+ }
65
+ catch {
66
+ return "";
67
+ }
68
+ for (const name of entries) {
69
+ const child = join(root, name);
70
+ if (hasKicadMarker(child))
71
+ return child;
72
+ }
73
+ for (const name of entries) {
74
+ const found = findKicadDir(join(root, name), depth + 1);
75
+ if (found !== "")
76
+ return found;
77
+ }
78
+ return "";
79
+ }
80
+ /** 在 root 下按深度找第一个含 `.ioc` 的目录(候选名都不命中时用)。 */
81
+ function findFirmwareDir(root, depth) {
82
+ if (depth > 2)
83
+ return "";
84
+ let entries = [];
85
+ try {
86
+ entries = readdirSync(root, { withFileTypes: true })
87
+ .filter((item) => item.isDirectory() && !item.name.startsWith(".") && !SCAN_SKIP.includes(item.name))
88
+ .map((item) => item.name);
89
+ }
90
+ catch {
91
+ return "";
92
+ }
93
+ for (const name of entries) {
94
+ const child = join(root, name);
95
+ if (hasFile(child, (entry) => entry.endsWith(".ioc")))
96
+ return child;
97
+ }
98
+ for (const name of entries) {
99
+ const found = findFirmwareDir(join(root, name), depth + 1);
100
+ if (found !== "")
101
+ return found;
102
+ }
103
+ return "";
104
+ }
105
+ /**
106
+ * 解析工程目录约定。
107
+ *
108
+ * 顺序:`dsh-stm32.conf` 里显式写的相对路径 → 候选名(含根)→ 深度 ≤2 的搜索。
109
+ * 不做缓存:工程目录可能在会话中途被用户重排,读一次目录比缓存失效逻辑便宜。
110
+ */
111
+ export function resolveProjectLayout(projectDir) {
112
+ const root = resolve(projectDir.trim() === "" ? "." : projectDir);
113
+ const conf = readProjectConf(root);
114
+ const notes = [];
115
+ let firmwareDir = "";
116
+ if (conf.ioc !== "") {
117
+ // conf 里点名了 .ioc:以它所在的目录为准,不再按约定猜(S127)。
118
+ const iocPath = resolve(root, conf.ioc);
119
+ if (existsSync(iocPath)) {
120
+ firmwareDir = dirname(iocPath);
121
+ const where = relative(root, firmwareDir);
122
+ notes.push("程序目录:conf 里的 .ioc 在 " + (where === "" ? "." : where));
123
+ }
124
+ }
125
+ if (firmwareDir === "" && conf.firmware !== "") {
126
+ firmwareDir = resolve(root, conf.firmware);
127
+ notes.push("程序目录:conf 里写的是 " + conf.firmware);
128
+ }
129
+ if (firmwareDir === "") {
130
+ for (const name of FIRMWARE_CANDIDATES) {
131
+ const candidate = name === "" ? root : join(root, name);
132
+ if (isDir(candidate) && hasFirmwareMarker(candidate)) {
133
+ firmwareDir = candidate;
134
+ notes.push(name === "" ? "程序目录:工程根(.ioc 或 CMakeLists.txt 在根上)" : "程序目录:" + name);
135
+ break;
136
+ }
137
+ }
138
+ }
139
+ if (firmwareDir === "") {
140
+ // 候选名都不命中时再扫一层:目录名可以叫 fw、code、firmware-app,用户不必改名(S127)。
141
+ const found = findFirmwareDir(root, 1);
142
+ if (found !== "") {
143
+ firmwareDir = found;
144
+ notes.push("程序目录:扫描找到 " + (relative(root, found) === "" ? "." : relative(root, found)));
145
+ }
146
+ }
147
+ if (firmwareDir === "") {
148
+ // 工程根上挂的是工作区索引(只有 project=)时,顺着索引进唯一子工程(S127)。
149
+ const index = readWorkspaceIndex(root);
150
+ const first = index.projects[0];
151
+ if (index.projects.length === 1 && first !== undefined && first.dir !== root && existsSync(first.dir)) {
152
+ firmwareDir = first.dir;
153
+ notes.push("程序目录:跟着工作区索引 " + relative(root, first.dir) + "(根上只有索引)");
154
+ }
155
+ }
156
+ if (firmwareDir === "") {
157
+ // 标记都不在根上时退回根目录:宁可让工具在根上找,也不猜一个不存在的目录。
158
+ firmwareDir = root;
159
+ notes.push("程序目录:没有找到 .ioc 或 CMakeLists.txt,按工程根处理");
160
+ }
161
+ let hardwareDir = "";
162
+ if (conf.hardware !== "") {
163
+ hardwareDir = resolve(root, conf.hardware);
164
+ notes.push("硬件目录:conf 里写的是 " + conf.hardware);
165
+ }
166
+ else {
167
+ for (const name of HARDWARE_CANDIDATES) {
168
+ const candidate = join(root, name);
169
+ if (isDir(candidate) && hasKicadMarker(candidate)) {
170
+ hardwareDir = candidate;
171
+ notes.push("硬件目录:" + name);
172
+ break;
173
+ }
174
+ }
175
+ if (hardwareDir === "" && hasKicadMarker(root)) {
176
+ hardwareDir = root;
177
+ notes.push("硬件目录:工程根(KiCad 工程与程序同级)");
178
+ }
179
+ if (hardwareDir === "") {
180
+ const found = findKicadDir(root, 1);
181
+ if (found !== "") {
182
+ hardwareDir = found;
183
+ notes.push("硬件目录:扫描找到 " + found);
184
+ }
185
+ }
186
+ }
187
+ return {
188
+ projectDir: root,
189
+ firmwareDir,
190
+ hardwareDir,
191
+ configDir: join(root, ".dsh-stm32"),
192
+ notes,
193
+ };
194
+ }
195
+ /** 原理图目录:没有硬件目录时返回空串,调用方据此给「把 KiCad 工程放 hardware/ 下」的提示。 */
196
+ export function hardwareDirOf(layout) {
197
+ return layout.hardwareDir;
198
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * 工程结构与配置文件归位(S128)。
3
+ *
4
+ * 同名 `dsh-stm32.conf` 存两种内容:工作区索引(`project=`)与工程描述(`name=`/`mcu=`/`ioc=`…)。
5
+ * 放在同一个文件里必然出现「这一行属于谁」的歧义,工程描述还常被写进 `fw/` 这类子目录。
6
+ * 规范位置:
7
+ *
8
+ * - 工作区索引:`<工作区>/.dsh-stm32/workspace.conf`
9
+ * - 工程描述: `<工程根>/dsh-stm32.conf`(`ioc=`/`build=` 一律相对工程根)
10
+ * - 插件状态: `<工程根>/.dsh-stm32/`
11
+ *
12
+ * 归位动作只有两类:子目录里的工程描述并回工程根;工程根里的索引行搬到上一级的工作区索引。
13
+ */
14
+ import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
15
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
16
+ import { CONF_FILE_NAME, WORKSPACE_CONF_REL, parseConf, writeProjectConf } from "./project-conf.js";
17
+ const SKIP = new Set(["node_modules", "build", "build_pc", "Drivers", "Core", "cmake", ".git", "__pycache__", "docs", "artifacts"]);
18
+ /** 工程根 = 含 `.ioc` 的目录;`fw/` 这类子目录不算工程根,它只是程序目录。 */
19
+ function projectRootOf(dir) {
20
+ try {
21
+ if (readdirSync(dir).some((name) => name.endsWith(".ioc")))
22
+ return dir;
23
+ }
24
+ catch {
25
+ return dir;
26
+ }
27
+ return dir;
28
+ }
29
+ /** 程序目录:优先 `fw` 等候选,其次深度 ≤2 扫 `*.ioc`;找不到返回空串。 */
30
+ export function firmwareDirOf(root) {
31
+ const candidates = ["program", "firmware", "app", "user", "fw", "code", ""];
32
+ for (const name of candidates) {
33
+ const dir = name === "" ? root : join(root, name);
34
+ try {
35
+ if (readdirSync(dir).some((entry) => entry.endsWith(".ioc")))
36
+ return dir;
37
+ }
38
+ catch {
39
+ /* 目录不存在则继续 */
40
+ }
41
+ }
42
+ let entries = [];
43
+ try {
44
+ entries = readdirSync(root, { withFileTypes: true })
45
+ .filter((item) => item.isDirectory() && !item.name.startsWith(".") && !SKIP.has(item.name))
46
+ .map((item) => item.name);
47
+ }
48
+ catch {
49
+ return "";
50
+ }
51
+ for (const name of entries) {
52
+ const child = join(root, name);
53
+ try {
54
+ if (readdirSync(child).some((entry) => entry.endsWith(".ioc")))
55
+ return child;
56
+ }
57
+ catch {
58
+ /* 忽略不可读目录 */
59
+ }
60
+ }
61
+ return "";
62
+ }
63
+ function projectKeys(confPath) {
64
+ if (!existsSync(confPath))
65
+ return {};
66
+ const doc = parseConf(readFileSync(confPath, "utf8"), confPath);
67
+ const out = {};
68
+ for (const key of ["name", "mcu", "ioc", "build", "firmware", "hardware"]) {
69
+ const value = doc.single.get(key);
70
+ if (value !== undefined && value !== "")
71
+ out[key] = value;
72
+ }
73
+ return out;
74
+ }
75
+ function indexPathOf(workspaceRoot) {
76
+ return join(workspaceRoot, WORKSPACE_CONF_REL);
77
+ }
78
+ /** 规划归位(只读)。 */
79
+ export function planLayoutFix(input) {
80
+ const root = resolve(input.trim() === "" ? "." : input);
81
+ const projectDir = projectRootOf(root);
82
+ const actions = [];
83
+ const notes = [];
84
+ const rootConf = join(projectDir, CONF_FILE_NAME);
85
+ // 1) 程序目录里的工程描述并回工程根。
86
+ const fw = firmwareDirOf(projectDir);
87
+ if (fw !== "" && fw !== projectDir && existsSync(join(fw, CONF_FILE_NAME))) {
88
+ const sub = join(fw, CONF_FILE_NAME);
89
+ const merged = { ...projectKeys(sub), ...projectKeys(rootConf) };
90
+ const ioc = merged["ioc"] ?? "";
91
+ const fwRel = relative(projectDir, fw).replace(/\\/gu, "/");
92
+ const iocRel = ioc === "" ? "" : relative(projectDir, resolve(fw, ioc)).replace(/\\/gu, "/");
93
+ actions.push({
94
+ kind: "project-conf-move",
95
+ from: sub,
96
+ to: rootConf,
97
+ note: "工程描述从 " + fwRel + "/ 并回工程根(ioc=" + (iocRel === "" ? "未写" : iocRel) + ",firmware=" + fwRel + ")",
98
+ });
99
+ }
100
+ // 2) 工程根里的索引行搬到上一级的工作区索引。
101
+ if (existsSync(rootConf)) {
102
+ const doc = parseConf(readFileSync(rootConf, "utf8"), rootConf);
103
+ const projects = doc.multi.get("project") ?? [];
104
+ if (projects.length > 0) {
105
+ const workspaceRoot = dirname(projectDir);
106
+ actions.push({
107
+ kind: "index-move",
108
+ from: rootConf,
109
+ to: indexPathOf(workspaceRoot),
110
+ note: "工作区索引从工程根挪到 " + basename(workspaceRoot) + "/.dsh-stm32/workspace.conf(" + String(projects.length) + " 项)",
111
+ });
112
+ for (const entry of projects) {
113
+ const abs = resolve(projectDir, entry);
114
+ if (abs === projectDir)
115
+ continue;
116
+ notes.push("索引项 " + entry + " 指向 " + abs + ",挪走后仍可用路径引用");
117
+ }
118
+ }
119
+ }
120
+ return { ok: true, error: "", workspaceRoot: dirname(projectDir), actions, notes };
121
+ }
122
+ /** 执行归位;被改写的文件先备份成 `<文件>.bak`。 */
123
+ export function applyLayoutFix(input) {
124
+ const plan = planLayoutFix(input);
125
+ if (!plan.ok)
126
+ return plan;
127
+ const root = resolve(input.trim() === "" ? "." : input);
128
+ const projectDir = projectRootOf(root);
129
+ const rootConf = join(projectDir, CONF_FILE_NAME);
130
+ const failed = [];
131
+ for (const action of plan.actions) {
132
+ try {
133
+ if (action.kind === "project-conf-move") {
134
+ const text = readFileSync(action.from, "utf8");
135
+ const sub = parseConf(text, action.from);
136
+ const merged = { ...projectKeys(action.from), ...projectKeys(rootConf) };
137
+ const fw = dirname(action.from);
138
+ const fwRel = relative(projectDir, fw).replace(/\\/gu, "/");
139
+ const iocRaw = merged["ioc"] ?? "";
140
+ const iocRel = iocRaw === "" ? "" : relative(projectDir, resolve(fw, iocRaw)).replace(/\\/gu, "/");
141
+ writeFileSync(action.from + ".bak", text, "utf8");
142
+ writeProjectConf(projectDir, {
143
+ name: merged["name"] ?? sub.single.get("name"),
144
+ mcu: merged["mcu"],
145
+ ioc: iocRel,
146
+ build: merged["build"],
147
+ firmware: merged["firmware"] ?? fwRel,
148
+ hardware: merged["hardware"],
149
+ });
150
+ unlinkSync(action.from);
151
+ }
152
+ else if (action.kind === "index-move") {
153
+ const text = readFileSync(action.from, "utf8");
154
+ const doc = parseConf(text, action.from);
155
+ const entries = doc.multi.get("project") ?? [];
156
+ const workspaceRoot = dirname(projectDir);
157
+ const target = action.to;
158
+ const header = "# dsh-stm32 工作区索引:由插件写入,手工增删也可。\n# 一行一个工程,写相对路径或目录名。\nversion=1\n";
159
+ const existing = existsSync(target) ? readFileSync(target, "utf8").replace(/\s*$/u, "\n") : header;
160
+ const projectRel = relative(workspaceRoot, projectDir).replace(/\\/gu, "/");
161
+ // 工程根里的 project= 指向的是它的子目录(如 fw),那些不是独立工程,挪走后丢弃。
162
+ const wanted = new Set();
163
+ for (const entry of entries) {
164
+ const abs = resolve(projectDir, entry);
165
+ if (abs === projectDir || abs.startsWith(projectDir + sep))
166
+ continue;
167
+ wanted.add(relative(workspaceRoot, abs).replace(/\\/gu, "/"));
168
+ }
169
+ wanted.add(projectRel);
170
+ let body = existing;
171
+ for (const rel of wanted) {
172
+ if (!body.includes("project=" + rel + "\n"))
173
+ body += "project=" + rel + "\n";
174
+ }
175
+ mkdirSync(dirname(target), { recursive: true });
176
+ writeFileSync(target, body, "utf8");
177
+ writeFileSync(action.from + ".bak", text, "utf8");
178
+ const keep = text
179
+ .split(/\r?\n/u)
180
+ .filter((line) => !line.trim().startsWith("project="))
181
+ .join("\n")
182
+ .trim();
183
+ if (keep === "" || keep === "version=1")
184
+ unlinkSync(action.from);
185
+ else
186
+ writeFileSync(action.from, keep + "\n", "utf8");
187
+ }
188
+ }
189
+ catch (error) {
190
+ failed.push(action.note + ":" + (error instanceof Error ? error.message : String(error)));
191
+ }
192
+ }
193
+ const after = planLayoutFix(input);
194
+ return {
195
+ ok: failed.length === 0 && after.actions.length === 0,
196
+ error: failed.join(";"),
197
+ workspaceRoot: plan.workspaceRoot,
198
+ actions: plan.actions,
199
+ notes: [...plan.notes, ...(after.actions.length === 0 ? ["归位后结构符合约定"] : ["仍有未归位项,请查看 actions"])],
200
+ };
201
+ }
202
+ /** 是否需要归位(doctor / 面板提示用)。 */
203
+ export function layoutNeedsFix(input) {
204
+ return planLayoutFix(input).actions.length > 0;
205
+ }