@seasb/metafab 0.0.1 → 2.0.0-next.1

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 (414) hide show
  1. package/README.md +46 -1
  2. package/dist/cli.d.ts +11 -0
  3. package/dist/cli.js +419 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/commands/build.d.ts +31 -0
  6. package/dist/commands/build.js +156 -0
  7. package/dist/commands/build.js.map +1 -0
  8. package/dist/commands/check.d.ts +2 -0
  9. package/dist/commands/check.js +52 -0
  10. package/dist/commands/check.js.map +1 -0
  11. package/dist/commands/create.d.ts +2 -0
  12. package/dist/commands/create.js +75 -0
  13. package/dist/commands/create.js.map +1 -0
  14. package/dist/commands/detach.d.ts +2 -0
  15. package/dist/commands/detach.js +24 -0
  16. package/dist/commands/detach.js.map +1 -0
  17. package/dist/commands/diff.d.ts +2 -0
  18. package/dist/commands/diff.js +35 -0
  19. package/dist/commands/diff.js.map +1 -0
  20. package/dist/commands/env.d.ts +4 -0
  21. package/dist/commands/env.js +362 -0
  22. package/dist/commands/env.js.map +1 -0
  23. package/dist/commands/import.d.ts +2 -0
  24. package/dist/commands/import.js +107 -0
  25. package/dist/commands/import.js.map +1 -0
  26. package/dist/commands/init.d.ts +2 -0
  27. package/dist/commands/init.js +77 -0
  28. package/dist/commands/init.js.map +1 -0
  29. package/dist/commands/map.d.ts +2 -0
  30. package/dist/commands/map.js +42 -0
  31. package/dist/commands/map.js.map +1 -0
  32. package/dist/commands/pipeline-add.d.ts +2 -0
  33. package/dist/commands/pipeline-add.js +68 -0
  34. package/dist/commands/pipeline-add.js.map +1 -0
  35. package/dist/commands/pipeline-remove.d.ts +2 -0
  36. package/dist/commands/pipeline-remove.js +45 -0
  37. package/dist/commands/pipeline-remove.js.map +1 -0
  38. package/dist/commands/publish.d.ts +2 -0
  39. package/dist/commands/publish.js +153 -0
  40. package/dist/commands/publish.js.map +1 -0
  41. package/dist/commands/types.d.ts +45 -0
  42. package/dist/commands/types.js +2 -0
  43. package/dist/commands/types.js.map +1 -0
  44. package/dist/commands/update.d.ts +2 -0
  45. package/dist/commands/update.js +97 -0
  46. package/dist/commands/update.js.map +1 -0
  47. package/dist/core/adopt.d.ts +53 -0
  48. package/dist/core/adopt.js +676 -0
  49. package/dist/core/adopt.js.map +1 -0
  50. package/dist/core/build/agents.d.ts +26 -0
  51. package/dist/core/build/agents.js +67 -0
  52. package/dist/core/build/agents.js.map +1 -0
  53. package/dist/core/build/index.d.ts +5 -0
  54. package/dist/core/build/index.js +6 -0
  55. package/dist/core/build/index.js.map +1 -0
  56. package/dist/core/build/markers.d.ts +34 -0
  57. package/dist/core/build/markers.js +97 -0
  58. package/dist/core/build/markers.js.map +1 -0
  59. package/dist/core/build/plan.d.ts +82 -0
  60. package/dist/core/build/plan.js +912 -0
  61. package/dist/core/build/plan.js.map +1 -0
  62. package/dist/core/build/preview.d.ts +39 -0
  63. package/dist/core/build/preview.js +344 -0
  64. package/dist/core/build/preview.js.map +1 -0
  65. package/dist/core/build/skill.d.ts +99 -0
  66. package/dist/core/build/skill.js +354 -0
  67. package/dist/core/build/skill.js.map +1 -0
  68. package/dist/core/check/drift.d.ts +13 -0
  69. package/dist/core/check/drift.js +205 -0
  70. package/dist/core/check/drift.js.map +1 -0
  71. package/dist/core/check/index.d.ts +16 -0
  72. package/dist/core/check/index.js +84 -0
  73. package/dist/core/check/index.js.map +1 -0
  74. package/dist/core/check/markers.d.ts +9 -0
  75. package/dist/core/check/markers.js +220 -0
  76. package/dist/core/check/markers.js.map +1 -0
  77. package/dist/core/config/destinations.d.ts +5 -0
  78. package/dist/core/config/destinations.js +20 -0
  79. package/dist/core/config/destinations.js.map +1 -0
  80. package/dist/core/config/load.d.ts +4 -0
  81. package/dist/core/config/load.js +41 -0
  82. package/dist/core/config/load.js.map +1 -0
  83. package/dist/core/config/parse.d.ts +8 -0
  84. package/dist/core/config/parse.js +201 -0
  85. package/dist/core/config/parse.js.map +1 -0
  86. package/dist/core/config/source.d.ts +25 -0
  87. package/dist/core/config/source.js +67 -0
  88. package/dist/core/config/source.js.map +1 -0
  89. package/dist/core/config/types.d.ts +48 -0
  90. package/dist/core/config/types.js +2 -0
  91. package/dist/core/config/types.js.map +1 -0
  92. package/dist/core/config/validate.d.ts +11 -0
  93. package/dist/core/config/validate.js +389 -0
  94. package/dist/core/config/validate.js.map +1 -0
  95. package/dist/core/config/writers.d.ts +14 -0
  96. package/dist/core/config/writers.js +269 -0
  97. package/dist/core/config/writers.js.map +1 -0
  98. package/dist/core/config.d.ts +7 -0
  99. package/dist/core/config.js +8 -0
  100. package/dist/core/config.js.map +1 -0
  101. package/dist/core/discovery.d.ts +34 -0
  102. package/dist/core/discovery.js +272 -0
  103. package/dist/core/discovery.js.map +1 -0
  104. package/dist/core/edit/create.d.ts +18 -0
  105. package/dist/core/edit/create.js +190 -0
  106. package/dist/core/edit/create.js.map +1 -0
  107. package/dist/core/edit/document.d.ts +4 -0
  108. package/dist/core/edit/document.js +16 -0
  109. package/dist/core/edit/document.js.map +1 -0
  110. package/dist/core/edit/factory-yaml.d.ts +17 -0
  111. package/dist/core/edit/factory-yaml.js +213 -0
  112. package/dist/core/edit/factory-yaml.js.map +1 -0
  113. package/dist/core/edit/files.d.ts +6 -0
  114. package/dist/core/edit/files.js +47 -0
  115. package/dist/core/edit/files.js.map +1 -0
  116. package/dist/core/edit/index.d.ts +9 -0
  117. package/dist/core/edit/index.js +10 -0
  118. package/dist/core/edit/index.js.map +1 -0
  119. package/dist/core/edit/map.d.ts +24 -0
  120. package/dist/core/edit/map.js +82 -0
  121. package/dist/core/edit/map.js.map +1 -0
  122. package/dist/core/edit/names.d.ts +2 -0
  123. package/dist/core/edit/names.js +17 -0
  124. package/dist/core/edit/names.js.map +1 -0
  125. package/dist/core/edit/paths.d.ts +8 -0
  126. package/dist/core/edit/paths.js +81 -0
  127. package/dist/core/edit/paths.js.map +1 -0
  128. package/dist/core/edit/pipeline.d.ts +19 -0
  129. package/dist/core/edit/pipeline.js +152 -0
  130. package/dist/core/edit/pipeline.js.map +1 -0
  131. package/dist/core/edit/skill.d.ts +1 -0
  132. package/dist/core/edit/skill.js +10 -0
  133. package/dist/core/edit/skill.js.map +1 -0
  134. package/dist/core/env/condition.d.ts +40 -0
  135. package/dist/core/env/condition.js +283 -0
  136. package/dist/core/env/condition.js.map +1 -0
  137. package/dist/core/env/declarations.d.ts +16 -0
  138. package/dist/core/env/declarations.js +328 -0
  139. package/dist/core/env/declarations.js.map +1 -0
  140. package/dist/core/env/directives.d.ts +75 -0
  141. package/dist/core/env/directives.js +429 -0
  142. package/dist/core/env/directives.js.map +1 -0
  143. package/dist/core/env/git-config.d.ts +15 -0
  144. package/dist/core/env/git-config.js +110 -0
  145. package/dist/core/env/git-config.js.map +1 -0
  146. package/dist/core/env/imports.d.ts +60 -0
  147. package/dist/core/env/imports.js +217 -0
  148. package/dist/core/env/imports.js.map +1 -0
  149. package/dist/core/env/index.d.ts +6 -0
  150. package/dist/core/env/index.js +7 -0
  151. package/dist/core/env/index.js.map +1 -0
  152. package/dist/core/env/markdown.d.ts +22 -0
  153. package/dist/core/env/markdown.js +33 -0
  154. package/dist/core/env/markdown.js.map +1 -0
  155. package/dist/core/env/render.d.ts +13 -0
  156. package/dist/core/env/render.js +65 -0
  157. package/dist/core/env/render.js.map +1 -0
  158. package/dist/core/env/report.d.ts +29 -0
  159. package/dist/core/env/report.js +39 -0
  160. package/dist/core/env/report.js.map +1 -0
  161. package/dist/core/env/scenarios.d.ts +40 -0
  162. package/dist/core/env/scenarios.js +124 -0
  163. package/dist/core/env/scenarios.js.map +1 -0
  164. package/dist/core/env/select.d.ts +30 -0
  165. package/dist/core/env/select.js +191 -0
  166. package/dist/core/env/select.js.map +1 -0
  167. package/dist/core/env/types.d.ts +38 -0
  168. package/dist/core/env/types.js +2 -0
  169. package/dist/core/env/types.js.map +1 -0
  170. package/dist/core/env/validate.d.ts +25 -0
  171. package/dist/core/env/validate.js +212 -0
  172. package/dist/core/env/validate.js.map +1 -0
  173. package/dist/core/factory/discovery.d.ts +9 -0
  174. package/dist/core/factory/discovery.js +139 -0
  175. package/dist/core/factory/discovery.js.map +1 -0
  176. package/dist/core/factory/factory-yaml.d.ts +29 -0
  177. package/dist/core/factory/factory-yaml.js +538 -0
  178. package/dist/core/factory/factory-yaml.js.map +1 -0
  179. package/dist/core/factory/index.d.ts +5 -0
  180. package/dist/core/factory/index.js +6 -0
  181. package/dist/core/factory/index.js.map +1 -0
  182. package/dist/core/factory/lines.d.ts +8 -0
  183. package/dist/core/factory/lines.js +11 -0
  184. package/dist/core/factory/lines.js.map +1 -0
  185. package/dist/core/factory/load.d.ts +4 -0
  186. package/dist/core/factory/load.js +83 -0
  187. package/dist/core/factory/load.js.map +1 -0
  188. package/dist/core/factory/requires.d.ts +9 -0
  189. package/dist/core/factory/requires.js +123 -0
  190. package/dist/core/factory/requires.js.map +1 -0
  191. package/dist/core/factory/types.d.ts +58 -0
  192. package/dist/core/factory/types.js +2 -0
  193. package/dist/core/factory/types.js.map +1 -0
  194. package/dist/core/factory/validate.d.ts +44 -0
  195. package/dist/core/factory/validate.js +460 -0
  196. package/dist/core/factory/validate.js.map +1 -0
  197. package/dist/core/hooks/index.d.ts +8 -0
  198. package/dist/core/hooks/index.js +15 -0
  199. package/dist/core/hooks/index.js.map +1 -0
  200. package/dist/core/hooks/script.d.ts +21 -0
  201. package/dist/core/hooks/script.js +34 -0
  202. package/dist/core/hooks/script.js.map +1 -0
  203. package/dist/core/hooks/sync.d.ts +17 -0
  204. package/dist/core/hooks/sync.js +262 -0
  205. package/dist/core/hooks/sync.js.map +1 -0
  206. package/dist/core/import/conflicts.d.ts +82 -0
  207. package/dist/core/import/conflicts.js +256 -0
  208. package/dist/core/import/conflicts.js.map +1 -0
  209. package/dist/core/import/copy.d.ts +10 -0
  210. package/dist/core/import/copy.js +76 -0
  211. package/dist/core/import/copy.js.map +1 -0
  212. package/dist/core/import/file-tree.d.ts +43 -0
  213. package/dist/core/import/file-tree.js +107 -0
  214. package/dist/core/import/file-tree.js.map +1 -0
  215. package/dist/core/import/index.d.ts +5 -0
  216. package/dist/core/import/index.js +6 -0
  217. package/dist/core/import/index.js.map +1 -0
  218. package/dist/core/import/pipeline-changes.d.ts +8 -0
  219. package/dist/core/import/pipeline-changes.js +89 -0
  220. package/dist/core/import/pipeline-changes.js.map +1 -0
  221. package/dist/core/import/run.d.ts +76 -0
  222. package/dist/core/import/run.js +275 -0
  223. package/dist/core/import/run.js.map +1 -0
  224. package/dist/core/init/gitattributes.d.ts +20 -0
  225. package/dist/core/init/gitattributes.js +89 -0
  226. package/dist/core/init/gitattributes.js.map +1 -0
  227. package/dist/core/init/index.d.ts +4 -0
  228. package/dist/core/init/index.js +5 -0
  229. package/dist/core/init/index.js.map +1 -0
  230. package/dist/core/init/name.d.ts +1 -0
  231. package/dist/core/init/name.js +4 -0
  232. package/dist/core/init/name.js.map +1 -0
  233. package/dist/core/init/run.d.ts +51 -0
  234. package/dist/core/init/run.js +261 -0
  235. package/dist/core/init/run.js.map +1 -0
  236. package/dist/core/init/targets.d.ts +17 -0
  237. package/dist/core/init/targets.js +87 -0
  238. package/dist/core/init/targets.js.map +1 -0
  239. package/dist/core/merge.d.ts +88 -0
  240. package/dist/core/merge.js +239 -0
  241. package/dist/core/merge.js.map +1 -0
  242. package/dist/core/publish/exclude.d.ts +9 -0
  243. package/dist/core/publish/exclude.js +32 -0
  244. package/dist/core/publish/exclude.js.map +1 -0
  245. package/dist/core/publish/git-target.d.ts +32 -0
  246. package/dist/core/publish/git-target.js +460 -0
  247. package/dist/core/publish/git-target.js.map +1 -0
  248. package/dist/core/publish/index.d.ts +10 -0
  249. package/dist/core/publish/index.js +11 -0
  250. package/dist/core/publish/index.js.map +1 -0
  251. package/dist/core/publish/npm-target.d.ts +15 -0
  252. package/dist/core/publish/npm-target.js +177 -0
  253. package/dist/core/publish/npm-target.js.map +1 -0
  254. package/dist/core/publish/package-json.d.ts +31 -0
  255. package/dist/core/publish/package-json.js +74 -0
  256. package/dist/core/publish/package-json.js.map +1 -0
  257. package/dist/core/publish/prepare.d.ts +35 -0
  258. package/dist/core/publish/prepare.js +102 -0
  259. package/dist/core/publish/prepare.js.map +1 -0
  260. package/dist/core/publish/provenance.d.ts +1 -0
  261. package/dist/core/publish/provenance.js +20 -0
  262. package/dist/core/publish/provenance.js.map +1 -0
  263. package/dist/core/publish/publish.d.ts +13 -0
  264. package/dist/core/publish/publish.js +143 -0
  265. package/dist/core/publish/publish.js.map +1 -0
  266. package/dist/core/publish/readme.d.ts +22 -0
  267. package/dist/core/publish/readme.js +109 -0
  268. package/dist/core/publish/readme.js.map +1 -0
  269. package/dist/core/publish/stage.d.ts +19 -0
  270. package/dist/core/publish/stage.js +333 -0
  271. package/dist/core/publish/stage.js.map +1 -0
  272. package/dist/core/publish/types.d.ts +71 -0
  273. package/dist/core/publish/types.js +2 -0
  274. package/dist/core/publish/types.js.map +1 -0
  275. package/dist/core/requires/check.d.ts +15 -0
  276. package/dist/core/requires/check.js +83 -0
  277. package/dist/core/requires/check.js.map +1 -0
  278. package/dist/core/requires/index.d.ts +4 -0
  279. package/dist/core/requires/index.js +5 -0
  280. package/dist/core/requires/index.js.map +1 -0
  281. package/dist/core/requires/inspect.d.ts +44 -0
  282. package/dist/core/requires/inspect.js +114 -0
  283. package/dist/core/requires/inspect.js.map +1 -0
  284. package/dist/core/requires/paths.d.ts +29 -0
  285. package/dist/core/requires/paths.js +83 -0
  286. package/dist/core/requires/paths.js.map +1 -0
  287. package/dist/core/requires/setup.d.ts +37 -0
  288. package/dist/core/requires/setup.js +147 -0
  289. package/dist/core/requires/setup.js.map +1 -0
  290. package/dist/core/setup.d.ts +27 -0
  291. package/dist/core/setup.js +84 -0
  292. package/dist/core/setup.js.map +1 -0
  293. package/dist/core/sources/cache.d.ts +38 -0
  294. package/dist/core/sources/cache.js +264 -0
  295. package/dist/core/sources/cache.js.map +1 -0
  296. package/dist/core/sources/containment.d.ts +21 -0
  297. package/dist/core/sources/containment.js +50 -0
  298. package/dist/core/sources/containment.js.map +1 -0
  299. package/dist/core/sources/env.d.ts +12 -0
  300. package/dist/core/sources/env.js +28 -0
  301. package/dist/core/sources/env.js.map +1 -0
  302. package/dist/core/sources/extract.d.ts +25 -0
  303. package/dist/core/sources/extract.js +639 -0
  304. package/dist/core/sources/extract.js.map +1 -0
  305. package/dist/core/sources/git-process.d.ts +26 -0
  306. package/dist/core/sources/git-process.js +51 -0
  307. package/dist/core/sources/git-process.js.map +1 -0
  308. package/dist/core/sources/git.d.ts +41 -0
  309. package/dist/core/sources/git.js +525 -0
  310. package/dist/core/sources/git.js.map +1 -0
  311. package/dist/core/sources/https.d.ts +21 -0
  312. package/dist/core/sources/https.js +218 -0
  313. package/dist/core/sources/https.js.map +1 -0
  314. package/dist/core/sources/index.d.ts +13 -0
  315. package/dist/core/sources/index.js +14 -0
  316. package/dist/core/sources/index.js.map +1 -0
  317. package/dist/core/sources/npm-cli.d.ts +19 -0
  318. package/dist/core/sources/npm-cli.js +51 -0
  319. package/dist/core/sources/npm-cli.js.map +1 -0
  320. package/dist/core/sources/npm.d.ts +29 -0
  321. package/dist/core/sources/npm.js +411 -0
  322. package/dist/core/sources/npm.js.map +1 -0
  323. package/dist/core/sources/parse.d.ts +46 -0
  324. package/dist/core/sources/parse.js +446 -0
  325. package/dist/core/sources/parse.js.map +1 -0
  326. package/dist/core/sources/path.d.ts +10 -0
  327. package/dist/core/sources/path.js +331 -0
  328. package/dist/core/sources/path.js.map +1 -0
  329. package/dist/core/sources/problems.d.ts +29 -0
  330. package/dist/core/sources/problems.js +36 -0
  331. package/dist/core/sources/problems.js.map +1 -0
  332. package/dist/core/sources/redact.d.ts +2 -0
  333. package/dist/core/sources/redact.js +70 -0
  334. package/dist/core/sources/redact.js.map +1 -0
  335. package/dist/core/sources/resolve.d.ts +9 -0
  336. package/dist/core/sources/resolve.js +29 -0
  337. package/dist/core/sources/resolve.js.map +1 -0
  338. package/dist/core/sources/types.d.ts +86 -0
  339. package/dist/core/sources/types.js +2 -0
  340. package/dist/core/sources/types.js.map +1 -0
  341. package/dist/core/sources/validate.d.ts +9 -0
  342. package/dist/core/sources/validate.js +116 -0
  343. package/dist/core/sources/validate.js.map +1 -0
  344. package/dist/core/summary.d.ts +79 -0
  345. package/dist/core/summary.js +411 -0
  346. package/dist/core/summary.js.map +1 -0
  347. package/dist/core/update/clashes.d.ts +63 -0
  348. package/dist/core/update/clashes.js +192 -0
  349. package/dist/core/update/clashes.js.map +1 -0
  350. package/dist/core/update/detach.d.ts +21 -0
  351. package/dist/core/update/detach.js +38 -0
  352. package/dist/core/update/detach.js.map +1 -0
  353. package/dist/core/update/diff.d.ts +58 -0
  354. package/dist/core/update/diff.js +180 -0
  355. package/dist/core/update/diff.js.map +1 -0
  356. package/dist/core/update/fetch.d.ts +34 -0
  357. package/dist/core/update/fetch.js +73 -0
  358. package/dist/core/update/fetch.js.map +1 -0
  359. package/dist/core/update/index.d.ts +6 -0
  360. package/dist/core/update/index.js +7 -0
  361. package/dist/core/update/index.js.map +1 -0
  362. package/dist/core/update/restore.d.ts +20 -0
  363. package/dist/core/update/restore.js +195 -0
  364. package/dist/core/update/restore.js.map +1 -0
  365. package/dist/core/update/run.d.ts +113 -0
  366. package/dist/core/update/run.js +1135 -0
  367. package/dist/core/update/run.js.map +1 -0
  368. package/dist/core/update/select.d.ts +39 -0
  369. package/dist/core/update/select.js +157 -0
  370. package/dist/core/update/select.js.map +1 -0
  371. package/dist/core/update/spelling.d.ts +51 -0
  372. package/dist/core/update/spelling.js +185 -0
  373. package/dist/core/update/spelling.js.map +1 -0
  374. package/dist/core/update/trees.d.ts +24 -0
  375. package/dist/core/update/trees.js +72 -0
  376. package/dist/core/update/trees.js.map +1 -0
  377. package/dist/errors.d.ts +39 -0
  378. package/dist/errors.js +24 -0
  379. package/dist/errors.js.map +1 -0
  380. package/dist/help.d.ts +51 -0
  381. package/dist/help.js +117 -0
  382. package/dist/help.js.map +1 -0
  383. package/dist/input.d.ts +25 -0
  384. package/dist/input.js +174 -0
  385. package/dist/input.js.map +1 -0
  386. package/dist/output.d.ts +21 -0
  387. package/dist/output.js +37 -0
  388. package/dist/output.js.map +1 -0
  389. package/dist/util/frontmatter.d.ts +12 -0
  390. package/dist/util/frontmatter.js +58 -0
  391. package/dist/util/frontmatter.js.map +1 -0
  392. package/dist/util/fs.d.ts +38 -0
  393. package/dist/util/fs.js +135 -0
  394. package/dist/util/fs.js.map +1 -0
  395. package/dist/util/git-names.d.ts +8 -0
  396. package/dist/util/git-names.js +25 -0
  397. package/dist/util/git-names.js.map +1 -0
  398. package/dist/util/git.d.ts +12 -0
  399. package/dist/util/git.js +33 -0
  400. package/dist/util/git.js.map +1 -0
  401. package/dist/util/suggest.d.ts +6 -0
  402. package/dist/util/suggest.js +48 -0
  403. package/dist/util/suggest.js.map +1 -0
  404. package/dist/util/text.d.ts +8 -0
  405. package/dist/util/text.js +19 -0
  406. package/dist/util/text.js.map +1 -0
  407. package/dist/util/version.d.ts +7 -0
  408. package/dist/util/version.js +13 -0
  409. package/dist/util/version.js.map +1 -0
  410. package/dist/util/yaml.d.ts +30 -0
  411. package/dist/util/yaml.js +201 -0
  412. package/dist/util/yaml.js.map +1 -0
  413. package/package.json +51 -3
  414. package/resources/metafab-skill/SKILL.md +173 -0
@@ -0,0 +1,1135 @@
1
+ import { chmod, lstat, mkdir, rm, symlink, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { ExitCode, MetafabError } from "../../errors.js";
4
+ import { readdirTyped } from "../../util/fs.js";
5
+ import { cliVersion } from "../../util/version.js";
6
+ import { toLF } from "../../util/text.js";
7
+ import { NeedsInput } from "../../input.js";
8
+ import { applyBuild, planBuild } from "../build/index.js";
9
+ import { scanFactoryFiles } from "../check/index.js";
10
+ import { loadConfig } from "../config/load.js";
11
+ import { CONFIG_FILE } from "../config/parse.js";
12
+ import { setUpstream } from "../config/writers.js";
13
+ import { parseFactoryYaml } from "../factory/factory-yaml.js";
14
+ import { loadFactory } from "../factory/load.js";
15
+ import { hookChangeLines } from "../hooks/index.js";
16
+ import { localFilesForImport } from "../import/conflicts.js";
17
+ import { emptyTree, snapshotDirectories } from "../import/file-tree.js";
18
+ import { copyFactoryTree } from "../import/copy.js";
19
+ import { mergePath } from "../merge.js";
20
+ import { factoryRelative } from "../requires/paths.js";
21
+ import { inspectRequirement } from "../requires/inspect.js";
22
+ import { createRequirements, decideSetup, declineRequirements, setupRequired, } from "../requires/setup.js";
23
+ import { fetchFab, resolve } from "../sources/index.js";
24
+ import { parseSource } from "../sources/parse.js";
25
+ import { renderSummary, summarise, modeMatters } from "../summary.js";
26
+ import { findPathClashes } from "./clashes.js";
27
+ import { fetchRecordedBase, recordedBaseGone } from "./fetch.js";
28
+ import { captureFactory } from "./restore.js";
29
+ import { alignFactorySpelling, alignPathSpelling, alignTreeSpelling } from "./spelling.js";
30
+ import { recordedLabel, sameVersion, selectVersion, versionLabel, } from "./select.js";
31
+ import { entryContent, entryFromContent, factoryPath, factoryTree, localFactoryTree, mergeInputOf, sameEntry, } from "./trees.js";
32
+ function noUpstream() {
33
+ return new MetafabError("This factory has no upstream", {
34
+ exitCode: ExitCode.Failed,
35
+ code: "no-upstream",
36
+ problems: [
37
+ {
38
+ level: "error",
39
+ file: CONFIG_FILE,
40
+ message: "This factory has no upstream to update",
41
+ fix: "Run metafab import <source>",
42
+ },
43
+ ],
44
+ });
45
+ }
46
+ function configInvalid(problems) {
47
+ return new MetafabError("The factory configuration has problems.", {
48
+ exitCode: ExitCode.Failed,
49
+ code: "config-invalid",
50
+ problems,
51
+ });
52
+ }
53
+ function toWithUnversionedSource(to) {
54
+ return new MetafabError("--to is not accepted for an unversioned source", {
55
+ exitCode: ExitCode.Failed,
56
+ code: "to-unversioned",
57
+ problems: [
58
+ {
59
+ level: "error",
60
+ file: CONFIG_FILE,
61
+ message: `--to ${to} cannot select a version from an unversioned upstream`,
62
+ fix: "Run metafab update without --to",
63
+ },
64
+ ],
65
+ });
66
+ }
67
+ function unresolvedConflicts(problems) {
68
+ return new MetafabError("Update stopped: resolve the conflicts from an earlier update first.", {
69
+ exitCode: ExitCode.Failed,
70
+ code: "update-unresolved",
71
+ problems,
72
+ });
73
+ }
74
+ /**
75
+ * The error an update that failed while writing reports. The original message
76
+ * is kept, so the cause of the failure is not lost, and the summary says
77
+ * whether `.factory/` was put back. When the restore itself failed, the fix
78
+ * points at Git: the files on disk are the only reliable record of what
79
+ * changed.
80
+ */
81
+ function updateWriteFailed(error, restored) {
82
+ const original = error instanceof Error && error.message !== "" ? error.message : String(error);
83
+ const stopped = `Update stopped: ${original.replace(/\.$/, "")}.`;
84
+ const state = restored ? ".factory/ was restored." : ".factory/ may be partly updated.";
85
+ return new MetafabError(`${stopped} ${state}`, {
86
+ exitCode: ExitCode.Failed,
87
+ code: "update-write-failed",
88
+ cause: error,
89
+ problems: [
90
+ restored
91
+ ? {
92
+ level: "error",
93
+ file: ".factory",
94
+ message: "The update stopped before it finished; .factory/ was restored",
95
+ fix: "Fix the cause, then run metafab update again",
96
+ }
97
+ : {
98
+ level: "error",
99
+ file: ".factory",
100
+ message: "The update stopped before it finished and could not restore .factory/",
101
+ fix: "Restore .factory/ from Git (git status shows what changed), then run metafab update again",
102
+ },
103
+ ],
104
+ });
105
+ }
106
+ /** Restores the capture, reporting whether the directory is known to be back. */
107
+ async function restoreCapture(capture) {
108
+ try {
109
+ await capture.restore();
110
+ return true;
111
+ }
112
+ catch {
113
+ return false;
114
+ }
115
+ }
116
+ /**
117
+ * Refuses an update whose incoming paths would replace local content rather
118
+ * than merge with it. The refusal happens before anything is written, for a dry
119
+ * run too, so the reported plan can never claim a file was preserved after it
120
+ * was deleted.
121
+ */
122
+ function pathClashes(problems) {
123
+ return new MetafabError("Update stopped because the incoming fab would replace local content.", {
124
+ exitCode: ExitCode.Failed,
125
+ code: "update-path-conflict",
126
+ problems,
127
+ });
128
+ }
129
+ function buildConflict(result, warnings) {
130
+ return new MetafabError("Build stopped because the repository contains output that Metafab does not own.", {
131
+ exitCode: ExitCode.NotOwned,
132
+ code: "build-conflict",
133
+ problems: [...result.conflicts, ...result.errors, ...warnings, ...result.warnings],
134
+ });
135
+ }
136
+ function buildFailed(result, warnings) {
137
+ return new MetafabError("Build failed after update.", {
138
+ exitCode: ExitCode.Failed,
139
+ code: "build-failed",
140
+ problems: [...result.errors, ...warnings, ...result.warnings],
141
+ });
142
+ }
143
+ /**
144
+ * Refuses an update while a marker or `.upstream` file from the last one
145
+ * remains. It reuses the `metafab check` scanner, so update and check can never
146
+ * disagree about what counts as unresolved: markers are found in any encoding
147
+ * the check scanner reads, and `.upstream` files are found the same way.
148
+ */
149
+ async function assertResolved(root) {
150
+ const problems = await scanFactoryFiles(root);
151
+ if (problems.length > 0)
152
+ throw unresolvedConflicts(problems);
153
+ }
154
+ /** Builds the factory and returns what changed, or throws with the problems. */
155
+ async function buildFactory(root, factoryDir) {
156
+ const factory = await loadFactory(root);
157
+ const config = await loadConfig(factoryDir);
158
+ const warnings = [...factory.problems, ...config.problems].filter((problem) => problem.level === "warning");
159
+ const plan = await planBuild(factory, config, cliVersion());
160
+ if (plan.conflicts.length > 0)
161
+ throw buildConflict(plan, warnings);
162
+ if (plan.errors.length > 0)
163
+ throw buildFailed(plan, warnings);
164
+ const report = await applyBuild(plan);
165
+ return {
166
+ changed: report.changed,
167
+ hooks: report.hooks,
168
+ problems: [...warnings, ...plan.warnings, ...report.hookWarnings],
169
+ };
170
+ }
171
+ async function lstatIfExists(target) {
172
+ try {
173
+ return await lstat(target);
174
+ }
175
+ catch (error) {
176
+ if (error.code === "ENOENT")
177
+ return undefined;
178
+ throw error;
179
+ }
180
+ }
181
+ /** True when anything beneath `directory` is not itself a directory. */
182
+ async function containsFile(directory) {
183
+ for (const entry of await readdirTyped(directory)) {
184
+ if (!entry.isDirectory())
185
+ return true;
186
+ if (await containsFile(path.join(directory, entry.name)))
187
+ return true;
188
+ }
189
+ return false;
190
+ }
191
+ /**
192
+ * Resolves the target of a planned write, removing a file, link, or emptied
193
+ * directory in its way.
194
+ *
195
+ * The clash preflight refuses a write over a directory that still holds local
196
+ * content, so the directory branch below is a defensive invariant: it fires
197
+ * only if the preflight and this write disagree, and it leaves the repository
198
+ * untouched rather than deleting content the summary called preserved. A
199
+ * directory the plan emptied is removed and replaced, which is how an upstream
200
+ * directory collapses into a file.
201
+ */
202
+ async function prepareWrite(factoryDir, relativePath) {
203
+ const target = factoryPath(factoryDir, relativePath);
204
+ await mkdir(path.dirname(target), { recursive: true });
205
+ const existing = await lstatIfExists(target);
206
+ if (existing?.isDirectory() === true) {
207
+ if (!(await containsFile(target))) {
208
+ await rm(target, { recursive: true, force: true });
209
+ }
210
+ else {
211
+ const file = `.factory/${relativePath}`;
212
+ throw new MetafabError(`Refusing to replace the directory ${file} with a file`, {
213
+ exitCode: ExitCode.Failed,
214
+ code: "update-path-conflict",
215
+ problems: [
216
+ {
217
+ level: "error",
218
+ file,
219
+ message: `Refusing to replace the directory ${file} with a file`,
220
+ fix: "Move the local directory away, then run metafab update again",
221
+ },
222
+ ],
223
+ });
224
+ }
225
+ }
226
+ else if (existing !== undefined) {
227
+ await rm(target, { force: true });
228
+ }
229
+ return target;
230
+ }
231
+ /**
232
+ * The bytes a planned write puts on disk.
233
+ *
234
+ * A merged file keeps the line ending its local copy had, so a CRLF file stays
235
+ * CRLF. An added file is written as upstream had it, original bytes included.
236
+ * A binary file is never converted.
237
+ */
238
+ function writeContentFor(entry) {
239
+ if (entry.link !== undefined || entry.binary)
240
+ return entryContent(entry);
241
+ if (entry.crlf === true) {
242
+ return Buffer.from(toLF(entry.text ?? "").replace(/\n/g, "\r\n"), "utf8");
243
+ }
244
+ return entry.raw ?? entryContent(entry);
245
+ }
246
+ /** Writes one planned path, replacing whatever local file or link it lands on. */
247
+ async function writeEntry(factoryDir, relativePath, entry) {
248
+ const target = await prepareWrite(factoryDir, relativePath);
249
+ if (entry.link !== undefined) {
250
+ await symlink(entry.link, target);
251
+ return;
252
+ }
253
+ await writeFile(target, writeContentFor(entry), { mode: entry.mode });
254
+ await chmod(target, entry.mode);
255
+ }
256
+ /** Writes a side file from upstream's bytes, which are already final. */
257
+ async function writeRawEntry(factoryDir, relativePath, content, mode) {
258
+ const target = await prepareWrite(factoryDir, relativePath);
259
+ await writeFile(target, content, { mode });
260
+ await chmod(target, mode);
261
+ }
262
+ async function applyWrites(factoryDir, writes) {
263
+ for (const write of writes) {
264
+ if (write.kind === "remove") {
265
+ // A planned removal names a local file or link, never a directory.
266
+ await rm(factoryPath(factoryDir, write.path), { force: true });
267
+ }
268
+ else if (write.kind === "side-file") {
269
+ await writeRawEntry(factoryDir, `${write.path}.upstream`, write.content, write.mode);
270
+ }
271
+ else {
272
+ await writeEntry(factoryDir, write.path, write.entry);
273
+ }
274
+ }
275
+ }
276
+ /** Every path in a tree, keyed by its lowercase spelling. */
277
+ function foldedPaths(tree) {
278
+ const folded = new Map();
279
+ for (const relativePath of Object.keys(tree)) {
280
+ const key = relativePath.toLowerCase();
281
+ const paths = folded.get(key);
282
+ if (paths === undefined)
283
+ folded.set(key, [relativePath]);
284
+ else
285
+ paths.push(relativePath);
286
+ }
287
+ return folded;
288
+ }
289
+ /**
290
+ * The path a kept local entry has after realignment.
291
+ *
292
+ * Realignment only changes the case of path components, so a preserved path
293
+ * that no longer exists at its old spelling moved to the single path that folds
294
+ * to it. Without this the summary names a directory the update just renamed
295
+ * away. Any other path keeps its spelling.
296
+ */
297
+ function movedSpelling(after, folded, relativePath) {
298
+ if (after[relativePath] !== undefined)
299
+ return relativePath;
300
+ const matches = folded.get(relativePath.toLowerCase());
301
+ return matches !== undefined && matches.length === 1 ? matches[0] : relativePath;
302
+ }
303
+ /** True when two entries describe different content or executable bit. */
304
+ function entriesDiffer(left, right) {
305
+ if (left === undefined || right === undefined)
306
+ return left !== right;
307
+ if (left.hash !== right.hash)
308
+ return true;
309
+ return modeMatters(left, right);
310
+ }
311
+ /**
312
+ * The files the update changed, comparing the realigned before tree with the
313
+ * tree it leaves behind.
314
+ *
315
+ * Both trees use the spelling the update leaves on disk, so a path renamed only
316
+ * by case is compared with itself: a file that still exists is never reported
317
+ * as removed, and its content change is reported at its new spelling. A path
318
+ * with conflict markers is listed under `conflicts` and is not repeated here,
319
+ * which keeps these lists and the review groups complementary.
320
+ */
321
+ function changedPaths(before, after, conflicts) {
322
+ const conflicted = new Set(conflicts);
323
+ const added = [];
324
+ const updated = [];
325
+ const removed = [];
326
+ const paths = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort();
327
+ for (const relativePath of paths) {
328
+ if (conflicted.has(relativePath))
329
+ continue;
330
+ const previous = before[relativePath];
331
+ const next = after[relativePath];
332
+ if (previous === undefined && next === undefined)
333
+ continue;
334
+ if (previous === undefined)
335
+ added.push(relativePath);
336
+ else if (next === undefined)
337
+ removed.push(relativePath);
338
+ else if (entriesDiffer(previous, next))
339
+ updated.push(relativePath);
340
+ }
341
+ return { added, updated, removed };
342
+ }
343
+ /**
344
+ * The shared sentence for a path the merge cannot place without a base.
345
+ * `difference` names the two cases Metafab cannot tell apart; the caller says
346
+ * what it did with the path.
347
+ */
348
+ function withoutBase(difference) {
349
+ return `the base is unavailable, so Metafab cannot tell ${difference}`;
350
+ }
351
+ function conflictNote(path, result) {
352
+ if (result.reason === "link") {
353
+ if (result.upstreamLink !== undefined) {
354
+ return `Conflict in ${path}: upstream is a link to ${result.upstreamLink}; its target is in ${path}.upstream.`;
355
+ }
356
+ return `Conflict in ${path}: your entry is a link to ${result.yoursLink ?? ""}; upstream's file is in ${path}.upstream.`;
357
+ }
358
+ if (result.reason === "new-local") {
359
+ return `Conflict in ${path}: the local entry differs from the new upstream file, which was written to ${path}.upstream.`;
360
+ }
361
+ if (result.reason === "base-unavailable") {
362
+ return `Conflict in ${path}: ${withoutBase("a local removal from an upstream addition")}. The path stays absent, and upstream was written to ${path}.upstream.`;
363
+ }
364
+ return `Binary conflict in ${path}: upstream was written to ${path}.upstream.`;
365
+ }
366
+ /**
367
+ * Upstream's bytes as a side file holds them: a link's target, or a file's
368
+ * original bytes when they differ from its LF text.
369
+ */
370
+ function sideFileContent(entry) {
371
+ if (entry.link !== undefined)
372
+ return Buffer.from(entry.link, "utf8");
373
+ if (entry.binary)
374
+ return Buffer.from(entry.data ?? new Uint8Array());
375
+ return entry.raw ?? Buffer.from(entry.text ?? "", "utf8");
376
+ }
377
+ /**
378
+ * Base paths that upstream renamed by case alone: base has `from`, theirs has
379
+ * `to` with the same folded spelling, and neither base has `to` nor theirs has
380
+ * `from`. The two spellings name one logical file, so the merge compares the
381
+ * three sides at `to`. Without this the rename reads as a removal plus an
382
+ * addition, and a local edit inside the renamed path refuses the update as a
383
+ * case-only clash.
384
+ *
385
+ * Every other case-only pair — both spellings on one side, or several folded
386
+ * candidates — is left alone, so the clash preflight still refuses it.
387
+ */
388
+ function caseOnlyRenames(base, theirs) {
389
+ const theirsByFold = foldedPaths(theirs);
390
+ const renames = [];
391
+ for (const from of Object.keys(base)) {
392
+ if (theirs[from] !== undefined)
393
+ continue;
394
+ const matches = theirsByFold.get(from.toLowerCase()) ?? [];
395
+ if (matches.length !== 1)
396
+ continue;
397
+ const to = matches[0];
398
+ if (to === from || base[to] !== undefined)
399
+ continue;
400
+ renames.push({ from, to });
401
+ }
402
+ return renames;
403
+ }
404
+ /**
405
+ * Renames one side's paths to the spelling upstream now uses, matching a local
406
+ * entry by its folded path so a file the user re-cased still merges.
407
+ *
408
+ * A path that already exists at the new spelling, or a folded group with more
409
+ * than one local entry, is left where it is: the merge does not guess, and the
410
+ * clash preflight refuses the update. Every path moved here must also reach the
411
+ * realignment in `runVersioned`, so the file on disk moves even when the merge
412
+ * keeps its content.
413
+ */
414
+ function realignRenames(tree, renames) {
415
+ const byFold = foldedPaths(tree);
416
+ const realigned = { ...tree };
417
+ const moved = [];
418
+ for (const { from, to } of renames) {
419
+ const candidates = byFold.get(from.toLowerCase()) ?? [];
420
+ if (candidates.length !== 1)
421
+ continue;
422
+ const current = candidates[0];
423
+ const entry = realigned[current];
424
+ if (entry === undefined || realigned[to] !== undefined)
425
+ continue;
426
+ delete realigned[current];
427
+ realigned[to] = entry;
428
+ moved.push(to);
429
+ }
430
+ return { tree: realigned, moved };
431
+ }
432
+ /**
433
+ * True when yours and theirs made the same change to a path that exists in all
434
+ * three versions. The shared result needs no local maintenance, so it is not a
435
+ * preserved local edit: the file now matches upstream.
436
+ */
437
+ function sameChangeAsYours(base, yours, theirs, baseUnavailable) {
438
+ if (baseUnavailable || base === undefined || yours === undefined || theirs === undefined) {
439
+ return false;
440
+ }
441
+ return !sameEntry(base, yours) && sameEntry(yours, theirs);
442
+ }
443
+ /**
444
+ * Applies the merge table to every path in base, yours, or theirs.
445
+ *
446
+ * The returned `after` tree is the planned state of `.factory/` before the
447
+ * spelling realignment: the caller aligns it the way the writes realign the
448
+ * filesystem, so the review matches the files a real run leaves behind.
449
+ */
450
+ export function planMerge(base, yours, theirs, labels, options = {}) {
451
+ const baseUnavailable = options.baseUnavailable === true;
452
+ // Upstream renames that change only case are one logical path per file, so
453
+ // the three sides are compared at the new spelling instead of reading the
454
+ // rename as a removal plus an addition.
455
+ const renames = caseOnlyRenames(base, theirs);
456
+ const mergedBase = renames.length === 0 ? base : realignRenames(base, renames).tree;
457
+ const mergedYours = renames.length === 0 ? { tree: yours, moved: [] } : realignRenames(yours, renames);
458
+ const after = { ...mergedYours.tree };
459
+ const writes = [];
460
+ const preserved = [];
461
+ const modeOnly = [];
462
+ const conflicts = [];
463
+ const sideFiles = [];
464
+ const notes = [];
465
+ const paths = [
466
+ ...new Set([
467
+ ...Object.keys(mergedBase),
468
+ ...Object.keys(mergedYours.tree),
469
+ ...Object.keys(theirs),
470
+ ]),
471
+ ].sort();
472
+ for (const relativePath of paths) {
473
+ const baseEntry = baseUnavailable ? undefined : mergedBase[relativePath];
474
+ const yoursEntry = mergedYours.tree[relativePath];
475
+ const theirsEntry = theirs[relativePath];
476
+ const result = mergePath(mergeInputOf(baseEntry), mergeInputOf(yoursEntry), mergeInputOf(theirsEntry), labels, { baseUnavailable });
477
+ switch (result.action) {
478
+ case "keep": {
479
+ if (result.note === "base-unavailable") {
480
+ // Without a base, a path upstream no longer has may be a local
481
+ // addition rather than an upstream removal. Keeping it is the only
482
+ // safe outcome, but it is not a conflict: nothing is left to resolve,
483
+ // so it is reported like the upstream-removed row.
484
+ preserved.push(relativePath);
485
+ notes.push(`${relativePath}: ${withoutBase("a local addition from an upstream removal")}; kept your file.`);
486
+ }
487
+ else if (result.note === "base-unavailable-mode") {
488
+ // Same content, different executable bit: yours stays as it is and
489
+ // the difference is reported, but it is not a local edit to keep.
490
+ // Without a base there is no way to tell which side changed the mode,
491
+ // and a mode is not a conflict.
492
+ modeOnly.push(relativePath);
493
+ notes.push(`${relativePath}: ${withoutBase("which side changed the permission bits")}; kept your permission bits.`);
494
+ }
495
+ else if (result.note === "upstream-removed") {
496
+ preserved.push(relativePath);
497
+ notes.push(`Upstream removed ${relativePath}; your local version was kept.`);
498
+ }
499
+ else if (sameChangeAsYours(baseEntry, yoursEntry, theirsEntry, baseUnavailable)) {
500
+ // Row 4: the local edit and the upstream change agree, so the path
501
+ // needs no local maintenance. Reporting it as preserved would imply
502
+ // an edit to keep; the note says upstream caught up instead.
503
+ notes.push(`Upstream made the same change as your local edit to ${relativePath}; the file now matches upstream.`);
504
+ }
505
+ else if (!baseUnavailable &&
506
+ yoursEntry !== undefined &&
507
+ !sameEntry(baseEntry, yoursEntry)) {
508
+ preserved.push(relativePath);
509
+ }
510
+ break;
511
+ }
512
+ case "remove": {
513
+ if (yoursEntry !== undefined) {
514
+ delete after[relativePath];
515
+ writes.push({ kind: "remove", path: relativePath });
516
+ }
517
+ if (result.note === "upstream-changed-removed") {
518
+ notes.push(`Upstream changed ${relativePath}, which you removed; it stays removed.`);
519
+ }
520
+ break;
521
+ }
522
+ case "add": {
523
+ if (theirsEntry !== undefined) {
524
+ after[relativePath] = theirsEntry;
525
+ writes.push({ kind: "write", path: relativePath, entry: theirsEntry });
526
+ }
527
+ break;
528
+ }
529
+ case "take-theirs": {
530
+ if (theirsEntry !== undefined) {
531
+ // The write follows the local copy's line endings, so drop upstream's
532
+ // CRLF flag and original bytes and let the local `crlf` decide for a
533
+ // file both sides have. The mode is the one the merge chose, which is
534
+ // the local mode when only non-executable bits differ.
535
+ const entry = {
536
+ ...theirsEntry,
537
+ mode: result.mode,
538
+ raw: undefined,
539
+ };
540
+ delete entry.crlf;
541
+ if (yoursEntry?.crlf === true)
542
+ entry.crlf = true;
543
+ after[relativePath] = entry;
544
+ writes.push({ kind: "write", path: relativePath, entry });
545
+ }
546
+ break;
547
+ }
548
+ case "write":
549
+ case "conflict": {
550
+ const entry = entryFromContent(result.content, result.mode);
551
+ if (yoursEntry?.crlf === true)
552
+ entry.crlf = true;
553
+ after[relativePath] = entry;
554
+ writes.push({ kind: "write", path: relativePath, entry });
555
+ if (result.action === "conflict")
556
+ conflicts.push(relativePath);
557
+ break;
558
+ }
559
+ case "side-file": {
560
+ sideFiles.push(relativePath);
561
+ conflicts.push(relativePath);
562
+ notes.push(conflictNote(relativePath, result));
563
+ writes.push({
564
+ kind: "side-file",
565
+ path: relativePath,
566
+ content: theirsEntry === undefined ? result.upstream : sideFileContent(theirsEntry),
567
+ mode: result.upstreamMode,
568
+ });
569
+ break;
570
+ }
571
+ }
572
+ }
573
+ return {
574
+ after,
575
+ // Removals first: a case-only rename, or a directory turned into a file,
576
+ // writes a path that a removal frees. The clash preflight and applyWrites
577
+ // both rely on the freed path being gone before the write lands.
578
+ writes: [
579
+ ...writes.filter((write) => write.kind === "remove"),
580
+ ...writes.filter((write) => write.kind !== "remove"),
581
+ ],
582
+ preserved: [...new Set(preserved)].sort(),
583
+ modeOnly: [...new Set(modeOnly)].sort(),
584
+ conflicts: [...new Set(conflicts)].sort(),
585
+ sideFiles: sideFiles.sort(),
586
+ notes,
587
+ realigned: [...new Set(mergedYours.moved)].sort(),
588
+ };
589
+ }
590
+ function baseReport(root, previous, versioned) {
591
+ return {
592
+ root,
593
+ status: "updated",
594
+ versioned,
595
+ previous,
596
+ upstream: previous,
597
+ replaced: [],
598
+ preserved: [],
599
+ modeOnly: [],
600
+ conflicts: [],
601
+ sideFiles: [],
602
+ added: [],
603
+ updated: [],
604
+ removed: [],
605
+ requires: [],
606
+ notes: [],
607
+ problems: [],
608
+ built: false,
609
+ changed: [],
610
+ hooks: [],
611
+ };
612
+ }
613
+ function deprecationWarning(upstream, message) {
614
+ const version = upstream.kind === "npm" ? upstream.version : recordedLabel(upstream);
615
+ return {
616
+ level: "warning",
617
+ file: CONFIG_FILE,
618
+ message: `${version} is deprecated: ${message}`,
619
+ fix: "Use metafab update --to to select another version",
620
+ };
621
+ }
622
+ function sourceOptionsOf(options) {
623
+ return {
624
+ ...options.sourceOptions,
625
+ ...(options.interactive === true ? { interactive: true } : {}),
626
+ };
627
+ }
628
+ function titleFor(upstream, selected) {
629
+ return `${upstream.source} ${recordedLabel(upstream)} -> ${recordedLabel(selected)}`;
630
+ }
631
+ function requestLabel(upstream) {
632
+ if (upstream.kind === "npm")
633
+ return upstream.requested;
634
+ return upstream.requested ?? upstream.commit.slice(0, 7);
635
+ }
636
+ /** True when two upstream entries record the same request and revision. */
637
+ function sameUpstream(left, right) {
638
+ return JSON.stringify(left) === JSON.stringify(right);
639
+ }
640
+ /** The requirements a `factory.yaml` text lists, or none when it has no text. */
641
+ function requirementsIn(text) {
642
+ if (text === undefined)
643
+ return [];
644
+ return parseFactoryYaml(text, ".factory/factory.yaml").requires ?? [];
645
+ }
646
+ /** The requirements whose folded path the previous `factory.yaml` did not list. */
647
+ function newRequirements(previous, merged) {
648
+ const known = new Set(previous.map((requirement) => requirement.path.toLowerCase()));
649
+ return merged.filter((requirement) => !known.has(requirement.path.toLowerCase()));
650
+ }
651
+ /**
652
+ * Inspects each requirement new upstream. A template the merge left in conflict
653
+ * is blocked instead: its file cannot be created from a conflicted template.
654
+ */
655
+ async function inspectNewRequirements(root, previous, merged, conflicted) {
656
+ const results = [];
657
+ for (const requirement of newRequirements(previous, merged)) {
658
+ const relative = requirement.template === undefined ? undefined : factoryRelative(requirement.template);
659
+ if (relative !== undefined && conflicted.has(relative)) {
660
+ results.push({
661
+ path: requirement.path,
662
+ description: requirement.description,
663
+ template: requirement.template,
664
+ state: "blocked",
665
+ reason: `its template ${requirement.template} has a conflict`,
666
+ clash: relative,
667
+ });
668
+ continue;
669
+ }
670
+ results.push(await inspectRequirement(root, requirement));
671
+ }
672
+ return results;
673
+ }
674
+ /**
675
+ * The upstream entry that records a selected version. It keeps the source as
676
+ * recorded and writes the request the selection resolved, so a later update
677
+ * follows a new `--to` range even when it selected the version already
678
+ * installed.
679
+ *
680
+ * `upstreamEntry` in `src/core/sources/git.ts` and `npm.ts` rebuilds the
681
+ * recorded source from the source spec instead. This function must not use it:
682
+ * it keeps the recorded `source` spelling, which a rebuilt entry would change.
683
+ */
684
+ function upstreamFor(previous, selected) {
685
+ if (previous.kind === "npm") {
686
+ return selected.kind === "npm"
687
+ ? {
688
+ kind: "npm",
689
+ source: previous.source,
690
+ requested: selected.requested,
691
+ version: selected.version,
692
+ }
693
+ : previous;
694
+ }
695
+ if (selected.kind === "npm")
696
+ return previous;
697
+ return {
698
+ kind: "git",
699
+ source: previous.source,
700
+ ...(selected.requested === undefined ? {} : { requested: selected.requested }),
701
+ ...(selected.version === undefined ? {} : { version: selected.version }),
702
+ commit: selected.commit,
703
+ };
704
+ }
705
+ async function runVersioned(root, factoryDir, previous, options, sourceOptions) {
706
+ const report = baseReport(root, previous, true);
707
+ const outcome = await selectVersion(previous, {
708
+ ...sourceOptions,
709
+ cwd: root,
710
+ ...(options.to === undefined ? {} : { to: options.to }),
711
+ });
712
+ if (outcome.kind === "pinned") {
713
+ return { ...report, status: "pinned", message: `Pinned to ${outcome.ref}. Use --to.` };
714
+ }
715
+ const selected = outcome.resolved;
716
+ if (sameVersion(previous, selected)) {
717
+ if (options.to === undefined) {
718
+ return { ...report, status: "up-to-date", message: "Already up to date." };
719
+ }
720
+ // `--to` can select the installed version and still change the recorded
721
+ // request, so record it: the next update follows the new range. Nothing
722
+ // else changes, and the summary says what was recorded.
723
+ const upstream = upstreamFor(previous, selected);
724
+ if (sameUpstream(previous, upstream)) {
725
+ return { ...report, status: "up-to-date", message: "Already up to date." };
726
+ }
727
+ const range = requestLabel(upstream);
728
+ if (options.dryRun === true) {
729
+ return {
730
+ ...report,
731
+ status: "up-to-date",
732
+ message: `Already up to date. Dry run: would record requested range ${range}.`,
733
+ requested: range,
734
+ };
735
+ }
736
+ await setUpstream(factoryDir, upstream);
737
+ return {
738
+ ...report,
739
+ status: "up-to-date",
740
+ message: `Already up to date. Recorded requested range ${range}.`,
741
+ upstream,
742
+ requested: range,
743
+ };
744
+ }
745
+ let theirs;
746
+ let base;
747
+ try {
748
+ theirs = await fetchFab(selected, sourceOptions);
749
+ const selectedEntry = theirs.upstream;
750
+ let baseUnavailable = false;
751
+ try {
752
+ base = await fetchRecordedBase(previous, { ...sourceOptions, cwd: root });
753
+ }
754
+ catch (error) {
755
+ // Merging without a base is only correct when the base is gone: a force
756
+ // push removed its commit, or npm unpublished its version. Any other
757
+ // failure (network, credentials, cache or filesystem) must abort the
758
+ // update before it writes, with its own problem and exit code.
759
+ if (!(error instanceof MetafabError) || !recordedBaseGone(error))
760
+ throw error;
761
+ baseUnavailable = true;
762
+ }
763
+ const baseTree = base === undefined ? emptyTree() : await factoryTree(base.factoryDir);
764
+ const theirsTree = await factoryTree(theirs.factoryDir);
765
+ const before = await localFactoryTree(root);
766
+ const plan = planMerge(baseTree, before, theirsTree, { base: recordedLabel(previous), upstream: recordedLabel(selectedEntry) }, { baseUnavailable });
767
+ // Check before writing anything, and before a dry run reports the plan: a
768
+ // write at a path a local directory or case variant occupies would delete
769
+ // local content, which the summary would then wrongly call preserved.
770
+ // Paths the plan removes are not obstacles: a rename or a restructure
771
+ // removes a local path and writes its replacement.
772
+ const local = await localFilesForImport(root, factoryDir, [], true);
773
+ const clashes = findPathClashes(local, {
774
+ files: [
775
+ ...plan.writes.flatMap((write) => write.kind === "remove"
776
+ ? []
777
+ : [write.kind === "side-file" ? `${write.path}.upstream` : write.path]),
778
+ // A case-only rename the merge resolved moves its file even when it
779
+ // writes nothing, and the realignment still walks every ancestor of the
780
+ // new spelling. Feed those paths to the preflight too, so a refusal
781
+ // happens before the removals that run ahead of the realignment.
782
+ ...plan.realigned,
783
+ ],
784
+ directories: [],
785
+ removed: plan.writes.flatMap((write) => (write.kind === "remove" ? [write.path] : [])),
786
+ renameCaseOnlyDirectories: true,
787
+ mergedCaseOnlyFiles: plan.realigned,
788
+ });
789
+ if (clashes.length > 0)
790
+ throw pathClashes(clashes);
791
+ const notes = [...plan.notes];
792
+ const problems = [];
793
+ const io = options.io ?? {};
794
+ const tty = io.tty ?? process.stdin.isTTY === true;
795
+ // A requirement new upstream is offered before the first write, so a
796
+ // missing terminal or a refusal leaves the repository exactly as it was.
797
+ // An old requirement that is still missing is check's to report, not a
798
+ // question the person already answered.
799
+ let mergedRequires = [];
800
+ let requirements = [];
801
+ let setupAgreed = false;
802
+ if (plan.conflicts.includes("factory.yaml")) {
803
+ notes.push("Required repository files not checked: resolve the conflict in factory.yaml first.");
804
+ }
805
+ else {
806
+ mergedRequires = requirementsIn(plan.after["factory.yaml"]?.text);
807
+ requirements = await inspectNewRequirements(root, requirementsIn(before["factory.yaml"]?.text), mergedRequires,
808
+ // Every side file is also pushed to `plan.conflicts`, so this one set
809
+ // covers a conflicted `factory.yaml` and a conflicted template alike.
810
+ new Set(plan.conflicts));
811
+ if (options.dryRun !== true) {
812
+ const decision = await decideSetup(requirements, options.setup, io, tty);
813
+ if (decision === "needs-input")
814
+ throw new NeedsInput([setupRequired(requirements)]);
815
+ setupAgreed = decision;
816
+ }
817
+ }
818
+ if (baseUnavailable) {
819
+ const label = recordedLabel(previous);
820
+ notes.push(`Recorded base ${label} no longer exists upstream, so every path where yours and theirs differ is treated as a conflict.`);
821
+ }
822
+ if (theirs.deprecated !== undefined) {
823
+ problems.push(deprecationWarning(selectedEntry, theirs.deprecated));
824
+ notes.push(`npm version ${versionLabel(selected)} is deprecated: ${theirs.deprecated}`);
825
+ }
826
+ const built = !options.dryRun && options.noBuild !== true && plan.conflicts.length === 0;
827
+ let changed = [];
828
+ let hooks = [];
829
+ // The paths the update writes, in the source's spelling. The realignment
830
+ // uses them on disk and the review uses them on the planned tree. A side
831
+ // file holds local content, so its own name stays local: only the
832
+ // directories above it follow the source, and `targets` realigns them.
833
+ // A case-only rename the merge resolved moves its file even when it writes
834
+ // nothing, so its new spelling realigns the directory and the review too.
835
+ const writes = plan.writes.filter((write) => write.kind !== "remove");
836
+ const incoming = {
837
+ files: [
838
+ ...writes.flatMap((write) => (write.kind === "write" ? [write.path] : [])),
839
+ ...plan.realigned,
840
+ ],
841
+ directories: [],
842
+ };
843
+ const targets = writes.map((write) => write.kind === "side-file"
844
+ ? { ...write, path: alignPathSpelling(write.path, incoming) }
845
+ : write);
846
+ if (options.dryRun === true) {
847
+ notes.push("Dry run: nothing was written.");
848
+ }
849
+ else {
850
+ // planMerge already orders removals before writes. The split here exists
851
+ // only to run the realignment between them: the removals free an old
852
+ // spelling, then alignFactorySpelling moves a directory renamed only in
853
+ // case (and any local-only files inside it), so the writes land at the
854
+ // source's spelling instead of recreating the old directory.
855
+ //
856
+ // The capture above the first write makes the block atomic in practice: a
857
+ // failure partway puts `.factory/` back, so the old version stays the base
858
+ // of the next update instead of half-applied upstream content.
859
+ const capture = await captureFactory(factoryDir);
860
+ try {
861
+ await applyWrites(factoryDir, plan.writes.filter((write) => write.kind === "remove"));
862
+ await alignFactorySpelling(factoryDir, incoming);
863
+ await applyWrites(factoryDir, targets);
864
+ // The selected upstream becomes the base of the next update, even when
865
+ // conflict markers were written: resolving them is local work against
866
+ // this version.
867
+ await setUpstream(factoryDir, theirs.upstream);
868
+ }
869
+ catch (error) {
870
+ throw updateWriteFailed(error, await restoreCapture(capture));
871
+ }
872
+ finally {
873
+ await capture.discard();
874
+ }
875
+ }
876
+ // Creation happens outside the captured block: it writes outside
877
+ // `.factory/`, and a restore must not undo a file the person agreed to.
878
+ // Each entry's state before that says whether the file was already there.
879
+ const statesBeforeCreation = new Map(requirements.map((result) => [result.path.toLowerCase(), result.state]));
880
+ if (options.dryRun !== true && requirements.length > 0) {
881
+ requirements = setupAgreed
882
+ ? await createRequirements(root, requirements, problems)
883
+ : declineRequirements(requirements);
884
+ }
885
+ // The build runs outside the captured block: a build failure never rolls
886
+ // back an update that is already complete.
887
+ if (built) {
888
+ const build = await buildFactory(root, factoryDir);
889
+ changed = build.changed;
890
+ hooks = build.hooks;
891
+ problems.push(...build.problems);
892
+ }
893
+ // The realignment moves a local-only file that lives inside a case-only
894
+ // renamed directory, so the reviewed tree and the preserved paths must move
895
+ // with it. Mirror the writes on disk: take the source's entries out of the
896
+ // planned tree, realign what is left, then put them back at the source's
897
+ // spelling. Aligning the tree as planned would already hold both spellings
898
+ // and prefer the exact one the write added, leaving the local-only file at
899
+ // the old spelling. A side file is local content and is not put back: the
900
+ // realignment already moved it with its directory, as the write does. A dry
901
+ // run computes the same tree, so both report what a real run writes.
902
+ const written = new Map();
903
+ for (const write of writes) {
904
+ if (write.kind !== "write")
905
+ continue;
906
+ const entry = plan.after[write.path];
907
+ if (entry !== undefined)
908
+ written.set(write.path, entry);
909
+ }
910
+ const unaligned = Object.fromEntries(Object.entries(plan.after).filter(([relativePath]) => !written.has(relativePath)));
911
+ const after = { ...alignTreeSpelling(unaligned, incoming) };
912
+ for (const [relativePath, entry] of written)
913
+ after[relativePath] = entry;
914
+ // The before tree realigns the same way, so the report compares the same
915
+ // files: a path renamed only by case is not a change, and a removal is
916
+ // never reported for a file the update leaves on disk.
917
+ const alignedBefore = alignTreeSpelling(before, incoming);
918
+ const folded = foldedPaths(after);
919
+ const preserved = [
920
+ ...new Set(plan.preserved.map((relativePath) => movedSpelling(after, folded, relativePath))),
921
+ ].sort();
922
+ const changes = changedPaths(alignedBefore, after, plan.conflicts);
923
+ // A template that changed upstream never changes the file it created: it is
924
+ // the person's file now. Say so, so the change is not mistaken for a no-op.
925
+ // A file this update created from the changed template is not one of those:
926
+ // it did not exist before the run, so nothing local was left alone.
927
+ for (const requirement of mergedRequires) {
928
+ if (requirement.template === undefined)
929
+ continue;
930
+ if (!changes.updated.includes(factoryRelative(requirement.template)))
931
+ continue;
932
+ const state = statesBeforeCreation.get(requirement.path.toLowerCase()) ??
933
+ (await inspectRequirement(root, requirement)).state;
934
+ if (state !== "present")
935
+ continue;
936
+ notes.push(`Upstream changed ${requirement.template}, the template for ${requirement.path}; ${requirement.path} was not changed.`);
937
+ }
938
+ const review = summarise(alignedBefore, after, {
939
+ title: titleFor(previous, selectedEntry),
940
+ ...(preserved.length === 0 ? {} : { preserved }),
941
+ ...(plan.conflicts.length === 0 ? {} : { conflicts: plan.conflicts }),
942
+ ...(notes.length === 0 ? {} : { notes }),
943
+ requirements,
944
+ });
945
+ return {
946
+ ...report,
947
+ status: "updated",
948
+ upstream: theirs.upstream,
949
+ from: recordedLabel(previous),
950
+ to: recordedLabel(selectedEntry),
951
+ preserved,
952
+ modeOnly: plan.modeOnly,
953
+ conflicts: plan.conflicts,
954
+ sideFiles: plan.sideFiles,
955
+ added: changes.added,
956
+ updated: changes.updated,
957
+ removed: changes.removed,
958
+ requires: requirements,
959
+ notes,
960
+ problems,
961
+ built,
962
+ changed,
963
+ hooks,
964
+ review,
965
+ };
966
+ }
967
+ finally {
968
+ await theirs?.cleanup?.();
969
+ await base?.cleanup?.();
970
+ }
971
+ }
972
+ async function runUnversioned(root, factoryDir, previous, options, sourceOptions) {
973
+ const report = baseReport(root, previous, false);
974
+ // A recorded source is relative to the project root, not to the directory the
975
+ // command was run from: `update` also runs from a subdirectory.
976
+ const spec = parseSource(previous.source, { cwd: root });
977
+ const resolved = await resolve(spec, sourceOptions);
978
+ let fetched;
979
+ try {
980
+ fetched = await fetchFab(resolved, sourceOptions);
981
+ const before = await localFactoryTree(root);
982
+ const theirs = await factoryTree(fetched.factoryDir);
983
+ const replaced = Object.keys(theirs)
984
+ .filter((relativePath) => !sameEntry(before[relativePath], theirs[relativePath]))
985
+ .sort();
986
+ const added = replaced.filter((relativePath) => before[relativePath] === undefined);
987
+ const updated = replaced.filter((relativePath) => before[relativePath] !== undefined);
988
+ // The copy replaces upstream-owned paths and keeps the rest. Refuse a path
989
+ // where it would delete a local directory or collide with a case variant,
990
+ // before anything is written and for a dry run too. A file the source
991
+ // replaces may differ only in case: the copy writes it with the source's
992
+ // spelling, so the path on disk matches the fab.
993
+ const [local, incomingDirectories] = await Promise.all([
994
+ localFilesForImport(root, factoryDir, [], true),
995
+ snapshotDirectories(fetched.factoryDir),
996
+ ]);
997
+ const clashes = findPathClashes(local, {
998
+ files: Object.keys(theirs),
999
+ directories: incomingDirectories,
1000
+ replaceCaseOnlyFiles: true,
1001
+ });
1002
+ if (clashes.length > 0)
1003
+ throw pathClashes(clashes);
1004
+ const notes = ["Replaced local edits can be restored from Git."];
1005
+ const problems = [];
1006
+ const io = options.io ?? {};
1007
+ const tty = io.tty ?? process.stdin.isTTY === true;
1008
+ let changed = [];
1009
+ let hooks = [];
1010
+ const built = options.dryRun !== true && options.noBuild !== true;
1011
+ // The copy replaces `.factory/` and keeps everything else, so a requirement
1012
+ // new upstream is offered before the first write: a missing terminal or a
1013
+ // refusal leaves `.factory/` unchanged. There are no conflicts here, so
1014
+ // nothing can block an entry.
1015
+ const mergedRequires = requirementsIn(theirs["factory.yaml"]?.text);
1016
+ let requirements = await inspectNewRequirements(root, requirementsIn(before["factory.yaml"]?.text), mergedRequires, new Set());
1017
+ let setupAgreed = false;
1018
+ if (options.dryRun !== true) {
1019
+ const decision = await decideSetup(requirements, options.setup, io, tty);
1020
+ if (decision === "needs-input")
1021
+ throw new NeedsInput([setupRequired(requirements)]);
1022
+ setupAgreed = decision;
1023
+ }
1024
+ if (options.dryRun === true) {
1025
+ notes.push("Dry run: nothing was written.");
1026
+ }
1027
+ else {
1028
+ // The copy replaces upstream-owned paths and keeps the rest; a failure
1029
+ // partway puts `.factory/` back rather than leaving a mixed tree.
1030
+ const capture = await captureFactory(factoryDir);
1031
+ try {
1032
+ await alignFactorySpelling(factoryDir, {
1033
+ files: Object.keys(theirs),
1034
+ directories: incomingDirectories,
1035
+ });
1036
+ await copyFactoryTree(fetched.factoryDir, factoryDir);
1037
+ }
1038
+ catch (error) {
1039
+ throw updateWriteFailed(error, await restoreCapture(capture));
1040
+ }
1041
+ finally {
1042
+ await capture.discard();
1043
+ }
1044
+ }
1045
+ // Creation happens outside the captured block, after the copy: a missing
1046
+ // parent is made first, and an existing file is never replaced.
1047
+ if (options.dryRun !== true && requirements.length > 0) {
1048
+ requirements = setupAgreed
1049
+ ? await createRequirements(root, requirements, problems)
1050
+ : declineRequirements(requirements);
1051
+ }
1052
+ // The build runs outside the captured block: a build failure never rolls
1053
+ // back an update that is already complete.
1054
+ if (built) {
1055
+ const build = await buildFactory(root, factoryDir);
1056
+ changed = build.changed;
1057
+ hooks = build.hooks;
1058
+ problems.push(...build.problems);
1059
+ }
1060
+ // A dry run cannot write, so it aligns the snapshot the same way the copy
1061
+ // will align the filesystem: a case-only replacement removes the old
1062
+ // spelling and adds the new one, so the summary matches the real run.
1063
+ const after = options.dryRun === true
1064
+ ? {
1065
+ ...alignTreeSpelling(before, {
1066
+ files: Object.keys(theirs),
1067
+ directories: incomingDirectories,
1068
+ }),
1069
+ ...theirs,
1070
+ }
1071
+ : await localFactoryTree(root);
1072
+ const review = summarise(before, after, {
1073
+ title: `${previous.source} (unversioned)`,
1074
+ notes,
1075
+ requirements,
1076
+ });
1077
+ return {
1078
+ ...report,
1079
+ upstream: fetched.upstream,
1080
+ replaced,
1081
+ added,
1082
+ updated,
1083
+ requires: requirements,
1084
+ notes,
1085
+ problems,
1086
+ built,
1087
+ changed,
1088
+ hooks,
1089
+ review,
1090
+ };
1091
+ }
1092
+ finally {
1093
+ await fetched?.cleanup?.();
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Runs `metafab update`.
1098
+ *
1099
+ * A versioned upstream is merged three-way: the recorded version is the base,
1100
+ * the working `.factory/` is yours, and the selected newer version is theirs.
1101
+ * An unversioned upstream is copied over the local files instead. A dry run
1102
+ * computes the same plan and writes nothing.
1103
+ */
1104
+ export async function runUpdate(options) {
1105
+ const root = path.resolve(options.root);
1106
+ const factoryDir = path.join(root, ".factory");
1107
+ const config = await loadConfig(factoryDir);
1108
+ const configErrors = config.problems.filter((problem) => problem.level === "error");
1109
+ if (configErrors.length > 0)
1110
+ throw configInvalid(configErrors);
1111
+ const previous = config.upstream;
1112
+ if (previous === undefined)
1113
+ throw noUpstream();
1114
+ await assertResolved(root);
1115
+ const sourceOptions = sourceOptionsOf(options);
1116
+ if (previous.kind === "unversioned") {
1117
+ if (options.to !== undefined)
1118
+ throw toWithUnversionedSource(options.to);
1119
+ return runUnversioned(root, factoryDir, previous, options, sourceOptions);
1120
+ }
1121
+ return runVersioned(root, factoryDir, previous, options, sourceOptions);
1122
+ }
1123
+ /** Human-readable report for `update`. */
1124
+ export function describeUpdate(report) {
1125
+ const body = report.message !== undefined
1126
+ ? report.message
1127
+ : report.review === undefined
1128
+ ? ""
1129
+ : renderSummary(report.review);
1130
+ const hookLines = hookChangeLines(report.hooks);
1131
+ if (hookLines.length === 0)
1132
+ return body;
1133
+ return body === "" ? hookLines.join("\n") : [body, ...hookLines].join("\n");
1134
+ }
1135
+ //# sourceMappingURL=run.js.map