@tama-create/sf-tools 1.4.0-dev.1 → 1.4.0-dev.10

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 (83) hide show
  1. package/config/changeset-types.txt +350 -0
  2. package/config/install/gitmessage +6 -0
  3. package/config/install/release/README.md +26 -0
  4. package/config/install/release/deploy-target.txt +368 -0
  5. package/config/install/release/remove-target.txt +279 -0
  6. package/config/metadata-capability.txt +118 -0
  7. package/config/metadata-dirs.txt +79 -0
  8. package/config/metasync-detect.txt +52 -0
  9. package/config/metasync-extra.txt +30 -0
  10. package/config/metasync-fingerprint.txt +90 -0
  11. package/dist/commands/index.js +7 -6
  12. package/dist/commands/launcher.js +21 -4
  13. package/dist/commands/pr.js +1 -1
  14. package/dist/commands/project.js +15 -6
  15. package/dist/commands/push.js +1 -1
  16. package/dist/commands/start.js +50 -2
  17. package/dist/commands/switch-org.js +1 -1
  18. package/dist/core/ci-sequence-steps.js +2 -2
  19. package/dist/core/ci-validate-steps.js +1 -1
  20. package/dist/core/cli-update-notice.js +47 -0
  21. package/dist/core/create-setup.js +47 -3
  22. package/dist/core/diag.js +9 -9
  23. package/dist/core/launcher-status.js +33 -2
  24. package/dist/core/log-auto.js +1 -1
  25. package/dist/core/log-box.js +32 -8
  26. package/dist/core/log-pull.js +2 -2
  27. package/dist/core/log-select.js +1 -1
  28. package/dist/core/log-start.js +2 -2
  29. package/dist/core/log-status.js +2 -2
  30. package/dist/core/metasync.js +2 -2
  31. package/dist/core/new-version.js +93 -0
  32. package/dist/core/pr.js +24 -6
  33. package/dist/core/project-status.js +20 -9
  34. package/dist/core/project-tier.js +1 -1
  35. package/dist/core/project-upgrade.js +138 -0
  36. package/dist/core/promote-check.js +46 -13
  37. package/dist/core/push.js +16 -5
  38. package/dist/core/release.js +1 -1
  39. package/dist/core/start.js +2 -2
  40. package/dist/core/update-cli.js +1 -1
  41. package/dist/io/create-deps.js +1 -0
  42. package/dist/io/job-deps.js +21 -13
  43. package/dist/io/keys.js +15 -4
  44. package/dist/io/log-deps.js +2 -1
  45. package/dist/io/metasync-deps.js +3 -2
  46. package/dist/io/promote-deps.js +4 -3
  47. package/dist/io/temp-dir.js +15 -1
  48. package/dist/io/toolbox.js +1 -1
  49. package/dist/ui/launcher.js +43 -12
  50. package/lib/apexlog.js +819 -0
  51. package/lib/metasync.js +1364 -0
  52. package/lib/package.json +4 -0
  53. package/lib/typecheck.js +547 -0
  54. package/package.json +9 -2
  55. package/templates/.forceignore +12 -0
  56. package/templates/.gitattributes +58 -0
  57. package/templates/.github/workflows/wf-metasync.yml +177 -0
  58. package/templates/.github/workflows/wf-release.yml +454 -0
  59. package/templates/.github/workflows/wf-sequence.yml +292 -0
  60. package/templates/.github/workflows/wf-validate.yml +389 -0
  61. package/templates/.prettierignore +11 -0
  62. package/templates/.prettierrc +17 -0
  63. package/templates/.vscode/extensions.json +9 -0
  64. package/templates/.vscode/launch.json +16 -0
  65. package/templates/.vscode/settings.json +39 -0
  66. package/templates/AGENTS.md +3 -0
  67. package/templates/CLAUDE.md +4 -0
  68. package/templates/README.md +11 -0
  69. package/templates/config/project-scratch-def.json +13 -0
  70. package/templates/eslint.config.js +55 -0
  71. package/templates/force-app/main/default/.gitkeep +0 -0
  72. package/templates/gitignore.template +62 -0
  73. package/templates/jest.config.js +6 -0
  74. package/templates/package.json +29 -0
  75. package/templates/scripts/apex/hello.apex +10 -0
  76. package/templates/scripts/soql/account.soql +6 -0
  77. package/templates/sf-tools/config/branches.txt +24 -0
  78. package/templates/sf-tools/config/metadata.txt +576 -0
  79. package/templates/sfdx-project.json +12 -0
  80. package/templates-ts/.github/workflows/wf-metasync.yml +109 -0
  81. package/templates-ts/.github/workflows/wf-release.yml +263 -0
  82. package/templates-ts/.github/workflows/wf-sequence.yml +153 -0
  83. package/templates-ts/.github/workflows/wf-validate.yml +185 -0
@@ -57,22 +57,33 @@ async function showOriginMain(box, path) {
57
57
  * origin/main の workflow が、段階の切り替えに対応していないファイル名(init-common.sh の tier_switch_wf_problems と同じ判定)。
58
58
  * wf-release.yml・wf-validate.yml: 判定の部分が雛形と同じで、# sf-tools: tier-check の印がある。
59
59
  * wf-propagate.yml: 残っていれば、対応していない扱い(廃止)。wf-metasync.yml: sf-metasync.sh を呼び、コメント以外に git push がない
60
+ * sft 版(templates-ts/)のワークフローは、段階の判定を sft の中(sft ci check-branch)に持つため、yml に印はない:
61
+ * wf-release.yml・wf-validate.yml は `ci check-branch` を呼んでいれば、対応している扱い。wf-metasync.yml は `sft metasync`(`$SFT metasync`)を呼び、
62
+ * コメント以外に git push がなければ、対応している扱い。シェル版(印のある雛形)も、これまでどおり対応している扱い
60
63
  */
61
- export async function tierSwitchWfProblems(box, templateDir) {
64
+ export async function tierSwitchWfProblems(box, templateDir, shellTemplateDir) {
62
65
  const bad = [];
63
66
  for (const wf of ["wf-release.yml", "wf-validate.yml"]) {
64
67
  const remote = (await showOriginMain(box, `.github/workflows/${wf}`)) ?? "";
65
- const tmplPath = `${templateDir}/${wf}`;
68
+ const tmplPath = `${shellTemplateDir ?? templateDir}/${wf}`;
66
69
  const tmpl = box.files.exists(tmplPath) ? box.files.readText(tmplPath) : "";
67
70
  const rb = tierWfBlock(remote);
68
- if (rb === "" || rb !== tierWfBlock(tmpl) || !remote.includes("# sf-tools: tier-check"))
71
+ const shellOk = rb !== "" && rb === tierWfBlock(tmpl) && remote.includes("# sf-tools: tier-check");
72
+ // sft 版: 対象の確認のステップ(run: の行)が、sft ci check-branch を呼んでいる
73
+ const sftOk = remote.split("\n").some((l) => /^\s*(-\s+)?run:.*\bci check-branch\b/.test(l));
74
+ if (!shellOk && !sftOk)
69
75
  bad.push(wf);
70
76
  }
71
77
  if ((await showOriginMain(box, ".github/workflows/wf-propagate.yml")) !== null)
72
78
  bad.push("wf-propagate.yml");
73
79
  const ms = (await showOriginMain(box, ".github/workflows/wf-metasync.yml")) ?? "";
74
80
  const pushes = ms.split("\n").some((l) => !/^\s*#/.test(l) && l.includes("git push"));
75
- if (!ms.includes("sf-metasync.sh") || pushes)
81
+ const msCode = ms
82
+ .split("\n")
83
+ .filter((l) => !/^\s*#/.test(l))
84
+ .join("\n");
85
+ const callsMetasync = ms.includes("sf-metasync.sh") || /\bSFT metasync\b|\bsft(\.js)? metasync\b/.test(msCode);
86
+ if (!callsMetasync || pushes)
76
87
  bad.push("wf-metasync.yml");
77
88
  return bad;
78
89
  }
@@ -155,7 +166,7 @@ export async function runProjectStatus(args, box, deps) {
155
166
  }
156
167
  err("");
157
168
  if (!found)
158
- err("[WARNING] 接続情報が、見つかりませんでした(sf-project.sh が、完了していない可能性があります)。");
169
+ err("[WARNING] 接続情報が、見つかりませんでした(sft project create が、完了していない可能性があります)。");
159
170
  // 4. 段階の切り替え(origin/main の branches.txt)
160
171
  err("");
161
172
  err(" 【段階の切り替え(origin/main の branches.txt)】");
@@ -203,7 +214,7 @@ export async function runProjectStatus(args, box, deps) {
203
214
  err(`[INFO] ${t} ブランチは残っていますが、段階としては無効です(branches.txt にない)。`);
204
215
  const keys = [`SF_CONSUMER_KEY_${sfx}`, `SF_USERNAME_${sfx}`, `SF_INSTANCE_URL_${sfx}`];
205
216
  if ([...secretNames, ...varNames].some((n) => keys.includes(n))) {
206
- err(`[INFO] ${t} の接続情報が残っています(使われません。消すには sf-project.sh --remove-tier ${t} --purge-secrets)。`);
217
+ err(`[INFO] ${t} の接続情報が残っています(使われません。消すには sft project remove-tier ${t} --purge-secrets)。`);
207
218
  }
208
219
  for (const r of rulesets) {
209
220
  const sp = r.indexOf(" ");
@@ -219,10 +230,10 @@ export async function runProjectStatus(args, box, deps) {
219
230
  else {
220
231
  err("[WARNING] origin/main に sf-tools/config/branches.txt がありません(workflow は、段階の切り替えを使わず、今までの動きになります)。");
221
232
  }
222
- const bad = await tierSwitchWfProblems(box, deps.templateDir);
233
+ const bad = await tierSwitchWfProblems(box, deps.templateDir, deps.shellTemplateDir);
223
234
  if (bad.length > 0) {
224
235
  err(`[WARNING] workflow が、段階の切り替えに対応していません(または、雛形と違います): ${bad.join(" ")}`);
225
- err("[WARNING] branches.txt から行を消しても、リリース・検証は止まりません。作業用のブランチで sf-update-workflows.sh を実行し、main まで入れてください(廃止した wf-propagate.yml は、sf-update-workflows.sh --remove wf-propagate.yml で消します)。");
236
+ err("[WARNING] branches.txt から行を消しても、リリース・検証は止まりません。作業用のブランチで sft project update-workflows を実行し、main まで入れてください(廃止した wf-propagate.yml は、sft project update-workflows --remove wf-propagate.yml で消します)。");
226
237
  }
227
238
  const stb = await variable("SF_TOOLS_BRANCH");
228
239
  if (stb !== "" && stb !== "main" && stb !== "development") {
@@ -230,6 +241,6 @@ export async function runProjectStatus(args, box, deps) {
230
241
  }
231
242
  }
232
243
  err("");
233
- err("[INFO] 接続先を変えるとき: sf-project.sh --reconnect <main|staging|develop>");
244
+ err("[INFO] 接続先を変えるとき: sft project reconnect <main|staging|develop>");
234
245
  return violation || diagNg > 0 ? 1 : 0;
235
246
  }
@@ -268,7 +268,7 @@ async function removeTier(args, box, deps, ask) {
268
268
  if (t.tier === "staging" && tierTextHasLine(c.main, "develop"))
269
269
  throw new Stop(1, "staging を外すには、先に develop を外す必要があります(origin/main の branches.txt に develop があります)。");
270
270
  // origin/main の workflow が、段階の切り替えに対応しているか
271
- const wf = await tierSwitchWfProblems(box, deps.templateDir);
271
+ const wf = await tierSwitchWfProblems(box, deps.templateDir, deps.shellTemplateDir);
272
272
  if (wf.length > 0) {
273
273
  err(`[INFO] origin/main の workflow が、段階の切り替えに対応していません(または、雛形と違います): ${wf.join(" ")}`);
274
274
  err("[INFO] sf-tools を更新し、作業用のブランチで sft project update-workflows を実行して、workflow を main まで入れてから、実行してください。");
@@ -0,0 +1,138 @@
1
+ import { branchList, isProtectedBranch } from "./branches.js";
2
+ import { isNewer } from "./new-version.js";
3
+ const PACKAGE = "@tama-create/sf-tools";
4
+ const PKG = "sf-tools/package.json";
5
+ const LOCK = "sf-tools/package-lock.json";
6
+ const VERSION_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
7
+ class Stop extends Error {
8
+ code;
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.code = code;
12
+ }
13
+ }
14
+ async function npmVersionExists(box, version) {
15
+ const r = await box.run("npm", ["view", `${PACKAGE}@${version}`, "version"], { timeoutMs: 30_000 }).catch(() => null);
16
+ return r !== null && r.code === 0 && r.stdout.trim() === version;
17
+ }
18
+ async function upgrade(args, box, deps, ask) {
19
+ const { files, output } = box;
20
+ const err = (l) => output.err(l);
21
+ let version = "";
22
+ let check = false;
23
+ for (const a of args) {
24
+ if (a === "--check")
25
+ check = true;
26
+ else if (a === "-v" || a === "--verbose")
27
+ continue;
28
+ else if (a.startsWith("-"))
29
+ throw new Stop(1, `不明なオプションです: ${a}`);
30
+ else if (version === "")
31
+ version = a;
32
+ else
33
+ throw new Stop(1, "版は 1 つだけ指定してください。");
34
+ }
35
+ if (!check && version === "")
36
+ throw new Stop(1, "版を指定してください(例: sft project upgrade 1.4.0)。");
37
+ if (version !== "" && !VERSION_RE.test(version))
38
+ throw new Stop(1, `版の形が正しくありません(1.2.3 または 1.2.3-dev.4): ${version}`);
39
+ if (!deps.folderName.startsWith("force-"))
40
+ throw new Stop(1, "force-* ディレクトリの中ではありません。");
41
+ if (!files.exists(PKG))
42
+ throw new Stop(1, `${PKG} がありません(sft の版を固定していないプロジェクトです)。`);
43
+ let pkg;
44
+ try {
45
+ pkg = JSON.parse(files.readText(PKG));
46
+ }
47
+ catch {
48
+ throw new Stop(1, `${PKG} を読めません(JSON の形が正しくありません)。`);
49
+ }
50
+ if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg))
51
+ throw new Stop(1, `${PKG} を読めません(JSON の形が正しくありません)。`);
52
+ const now = pkg.dependencies?.[PACKAGE];
53
+ if (typeof now !== "string" || !VERSION_RE.test(now))
54
+ throw new Stop(1, `${PKG} に、${PACKAGE} の固定した版(1.2.3 の形)がありません。`);
55
+ if (check) {
56
+ const r = await box.run("npm", ["view", PACKAGE, "dist-tags", "--json"], { timeoutMs: 30_000 }).catch(() => null);
57
+ err(`[INFO] 固定している版: ${now}`);
58
+ if (r === null || r.code !== 0)
59
+ throw new Stop(2, "npm の札の一覧を取得できません。");
60
+ err(`[INFO] npm の札: ${r.stdout.replace(/\s+/g, " ").trim()}`);
61
+ return 0;
62
+ }
63
+ if (version === now) {
64
+ err(`[SUCCESS] すでに ${now} に固定しています。`);
65
+ return 0;
66
+ }
67
+ const head = await box.run("git", ["symbolic-ref", "--short", "HEAD"]).catch(() => null);
68
+ const branch = head !== null && head.code === 0 ? head.stdout.trim() : "";
69
+ if (branch === "")
70
+ throw new Stop(1, "現在のブランチを取得できません。");
71
+ const cfg = "sf-tools/config/branches.txt";
72
+ const list = branchList(files.exists(cfg) ? files.readText(cfg) : null);
73
+ for (const w of list.warnings)
74
+ err(`[WARNING] ${w}`);
75
+ if (isProtectedBranch(branch, list.branches))
76
+ throw new Stop(1, `${branch} ブランチでは実行できません(環境ブランチです。作業用のブランチを切ってください)。`);
77
+ const st = await box.run("git", ["status", "--porcelain", "--untracked-files=no"]).catch(() => null);
78
+ if (st === null || st.code !== 0)
79
+ throw new Stop(1, "git status を取得できません。");
80
+ if (st.stdout.trim() !== "")
81
+ throw new Stop(1, "追跡しているファイルに、未コミットの変更があります。コミットするか退避してから、実行してください。");
82
+ // 存在の確認は読み取りのみ。質問の前に済ませる(ない版で、確認だけさせない)
83
+ if (!(await npmVersionExists(box, version)))
84
+ throw new Stop(1, `${PACKAGE}@${version} が、npm に見つかりません。`);
85
+ for (const l of [
86
+ "!! force-* に固定した sf-tools の版を上げます",
87
+ ` ${now} → ${version}(package.json・package-lock.json を書き換えます)`,
88
+ ...(isNewer(now, version) ? [" 注意: 今より古い版に下げます。段階ごとの版がそろわなくなるおそれがあります"] : []),
89
+ " CI/CD(リリース・検証)の動作が変わります。管理者以外は、実行しないでください",
90
+ ])
91
+ err(l);
92
+ const a = await ask("", "続行しますか?");
93
+ if (a === "need")
94
+ throw new Stop(20, "");
95
+ if (a !== "yes")
96
+ throw new Stop(1, "中断しました。");
97
+ const before = files.readText(PKG);
98
+ const hadLock = files.exists(LOCK);
99
+ const beforeLock = hadLock ? files.readText(LOCK) : "";
100
+ const next = { ...pkg, dependencies: { ...pkg.dependencies, [PACKAGE]: version } };
101
+ // 失敗でも中断でも、書き換え前に戻す(ロックが元からなければ、作りかけを消す)
102
+ let r = null;
103
+ try {
104
+ files.writeText(PKG, `${JSON.stringify(next, null, 2)}\n`);
105
+ r = await box
106
+ .run("npm", ["install", "--package-lock-only", "--ignore-scripts", "--prefix", "sf-tools"], { timeoutMs: 300_000 })
107
+ .catch(() => null);
108
+ }
109
+ finally {
110
+ if (r === null || r.code !== 0) {
111
+ files.writeText(PKG, before);
112
+ if (hadLock)
113
+ files.writeText(LOCK, beforeLock);
114
+ else if (files.exists(LOCK))
115
+ files.removeFile(LOCK);
116
+ }
117
+ }
118
+ if (r === null || r.code !== 0)
119
+ throw new Stop(1, "ロックファイルの作成に失敗したため、元に戻しました(npm install --package-lock-only --prefix sf-tools)。");
120
+ err(`[SUCCESS] ${PACKAGE} の固定を ${now} → ${version} に書き換えました(${PKG}・${LOCK})。`);
121
+ err("[INFO] 続きの手順(ワークフローは、新しい版の雛形で書き換えます。コミット・プッシュは、行いません):");
122
+ err("[INFO] 1. npm ci --prefix sf-tools --ignore-scripts");
123
+ err("[INFO] 2. sft project update-workflows(新しい版の雛形と合わせる)");
124
+ err("[INFO] 3. sft push → PR(develop → staging → main の順に、同じコミットを出す。一方通行の規則)");
125
+ return 0;
126
+ }
127
+ export async function runProjectUpgrade(args, box, deps, ask) {
128
+ try {
129
+ return await upgrade(args, box, deps, ask);
130
+ }
131
+ catch (e) {
132
+ if (!(e instanceof Stop))
133
+ throw e;
134
+ if (e.message !== "")
135
+ box.output.err(`[ERROR] ${e.message}`);
136
+ return e.code;
137
+ }
138
+ }
@@ -1,7 +1,8 @@
1
1
  // sft ci promote-check: 一方通行のリリース(develop → staging → main)の確認。シェル版の bin/sf-promote-check.sh の移し先
2
2
  // (doc/rebuild-design.md 11.2 の段階 2。規則の正本は doc/one-way-promotion-design.md 3.2)。読み取りのみ(組織・GitHub を変えない)。
3
3
  // 判定は promote.ts。ここは、gh・git から事実を集めて、判定に渡す(外との出入りは、道具の箱だけを通す: 7.2)。
4
- // 用法: --pr <番号> [--only sequence|stack] [--tooling] [--json] / --plan [--json]
4
+ // 用法: --pr <番号> [--only sequence|stack] [--tooling] [--json] / --plan [--json] [--quick]
5
+ // --quick: 表示用。R2(積み重ね。マージ済みの PR ごとに gh・git を呼ぶため遅い)を省く。次の段階・PR の有無・対象が空かだけを求める
5
6
  // --tooling: 対象が空でも、版・ワークフローを変える PR として、前の段階の印(R1)を求める(R2 は、対象が空のため見ない)。
6
7
  // マージ後の「印だけ付ける」ジョブ用: マージ後は PR の先端が出し先の祖先になり、差分で変更を読めないため、呼ぶ側が API で確かめた結果として受け取る。確認は増える側にだけ働く
7
8
  // 終了コード: 0 = すべて満たす(またはスキップ)/ 1 = 破った/ 2 = 判断できない(R0)。--json の形は、シェル版と同じ(凍結: 4.7)
@@ -17,7 +18,8 @@ function succeeded(r) {
17
18
  class CannotJudge extends Error {
18
19
  }
19
20
  /** deploy-target.txt・remove-target.txt の、実質的な行の数。ファイルがなければ null */
20
- function countTargets(box, path) {
21
+ /** 対象のファイル(deploy-target.txt・remove-target.txt)の実質的な行の数。ファイルがなければ null(ランチャーも使う) */
22
+ export function countTargets(box, path) {
21
23
  if (!box.files.exists(path))
22
24
  return null;
23
25
  let n = 0;
@@ -42,6 +44,7 @@ export async function runPromoteCheck(args, box, deps) {
42
44
  let onlySet = false;
43
45
  let json = false;
44
46
  let tooling = false;
47
+ let quick = false;
45
48
  for (let i = 0; i < args.length; i++) {
46
49
  const a = args[i];
47
50
  if (a === "--pr") {
@@ -73,6 +76,10 @@ export async function runPromoteCheck(args, box, deps) {
73
76
  // マージ後(印だけ付けるジョブ)は、先端がマージ先の祖先になり、差分で版・ワークフローの変更を読めない。呼ぶ側が API で確かめた結果として受け取る
74
77
  tooling = true;
75
78
  }
79
+ else if (a === "--quick") {
80
+ // 表示用(ランチャーの見出し): 次の段階と PR の有無だけを求め、時間のかかる R2(積み重ね)の確認は省く
81
+ quick = true;
82
+ }
76
83
  else if (a === "--json") {
77
84
  json = true;
78
85
  }
@@ -87,6 +94,8 @@ export async function runPromoteCheck(args, box, deps) {
87
94
  return fail2("--pr <番号> か --plan を指定してください。");
88
95
  if (mode !== "pr" && onlySet)
89
96
  return fail2("--only は --pr と一緒に使います。");
97
+ if (mode !== "plan" && quick)
98
+ return fail2("--quick は --plan と一緒に使います。");
90
99
  if (mode !== "pr" && tooling)
91
100
  return fail2("--tooling は --pr と一緒に使います。");
92
101
  const checkR1 = only !== "stack";
@@ -199,14 +208,22 @@ export async function runPromoteCheck(args, box, deps) {
199
208
  throw new CannotJudge(`${sha.slice(0, 7)} の ${tier} の印を確かめられません。`);
200
209
  return m === 0;
201
210
  };
202
- const targetsEmpty = (branch) => {
211
+ // 対象のファイルが両方とも「実質的な行なし」なら true。ファイルがないときは null(check-branch は、ないものを「対象なし」として通すため、
212
+ // 版・ワークフローだけを変える PR は、ないままマージされる。呼ぶ側が、その場合だけ「空」として扱う)
213
+ const targetsState = (branch) => {
203
214
  const dir = `sf-tools/release/${branch}`;
204
215
  const a = countTargets(box, `${dir}/deploy-target.txt`);
205
- const b = a === null ? null : countTargets(box, `${dir}/remove-target.txt`);
206
- if (a === null || b === null) {
207
- throw new CannotJudge(`${dir}/ の deploy-target.txt・remove-target.txt がありません。`);
208
- }
209
- return a + b === 0;
216
+ const b = countTargets(box, `${dir}/remove-target.txt`);
217
+ // 両方ないときだけ null。片方だけないときは、ないほうを 0 件として数える(ci-check-branch の hasContent と同じ意味)
218
+ if (a === null && b === null)
219
+ return null;
220
+ return (a ?? 0) + (b ?? 0) === 0;
221
+ };
222
+ const targetsEmpty = (branch) => {
223
+ const st = targetsState(branch);
224
+ if (st === null)
225
+ throw new CannotJudge(`sf-tools/release/${branch}/ の deploy-target.txt・remove-target.txt がありません。`);
226
+ return st;
210
227
  };
211
228
  // --- R2: 積み重ね ---
212
229
  const checkR2Rule = async (branch, head, tier) => {
@@ -262,7 +279,13 @@ export async function runPromoteCheck(args, box, deps) {
262
279
  const headNow = (await must(git("rev-parse", "HEAD"), "HEAD を読めません。")).trim();
263
280
  if (mode === "pr") {
264
281
  const view = await must(gh("pr", "view", prNumber, "--repo", repo, "--json", "headRefOid,headRefName,baseRefName,isCrossRepository,url", "--jq", "{head: .headRefOid, branch: .headRefName, target: .baseRefName, cross: .isCrossRepository, url}"), `PR #${prNumber} を取得できません(${repo})。`);
265
- const pr = JSON.parse(view);
282
+ let pr;
283
+ try {
284
+ pr = JSON.parse(view);
285
+ }
286
+ catch {
287
+ throw new CannotJudge(`PR #${prNumber} の情報を読めません(${repo})。`);
288
+ }
266
289
  result.head = pr.head;
267
290
  result.branch = pr.branch;
268
291
  result.target = pr.target;
@@ -284,12 +307,17 @@ export async function runPromoteCheck(args, box, deps) {
284
307
  }
285
308
  if (!isEnvBranch(pr.branch)) {
286
309
  // 対象が空でも、sf-tools の版・ワークフローを変える PR は、前の段階の印を求める(R1 だけ。部品がないため R2 は要らない)
287
- const empty = targetsEmpty(pr.branch);
310
+ // ファイルがないときは、版・ワークフローを変える PR(--tooling か、差分に含まれる)に限り、「空」として扱う。ほかは、判断できない(2)
311
+ const state = targetsState(pr.branch);
312
+ const empty = state ?? true;
288
313
  // 移動(rename)は、削除と追加の 2 行にして、移動前のパスも見る(ci-check-branch の API の判定と同じ)
289
314
  if (empty && !tooling) {
290
315
  await must(git("fetch", "--quiet", "origin", pr.target), `origin の ${pr.target} を取得できません。`);
291
316
  const changed = await must(git("diff", "--name-only", "--no-renames", `origin/${pr.target}...HEAD`), `${pr.target} との差分の一覧を取得できません。`);
292
317
  const toolingFiles = changed.split("\n").filter((f) => isToolingPath(f.trim()));
318
+ if (toolingFiles.length === 0 && state === null) {
319
+ throw new CannotJudge(`sf-tools/release/${pr.branch}/ の deploy-target.txt・remove-target.txt がありません。`);
320
+ }
293
321
  if (toolingFiles.length === 0) {
294
322
  log("INFO", "対象が空です(deploy-target.txt・remove-target.txt)。リリースしないため、確かめません。");
295
323
  result.skipped = true;
@@ -327,8 +355,13 @@ export async function runPromoteCheck(args, box, deps) {
327
355
  }
328
356
  result.skipped = targetsEmpty(result.branch);
329
357
  const marks = [];
330
- for (const t of tiersUp)
331
- marks.push(await markOrStop(headNow, t));
358
+ // 段階ごとの印の確認は、互いに関係がないので、同時に問い合わせる(gh の往復を待つ時間を、1 回分にする)
359
+ const got = await Promise.allSettled(tiersUp.map((t) => markOrStop(headNow, t)));
360
+ for (const g of got) {
361
+ if (g.status === "rejected")
362
+ throw g.reason;
363
+ marks.push(g.value);
364
+ }
332
365
  const next = nextTier(tiersUp, marks, headNow.slice(0, 7));
333
366
  if (!next.ok)
334
367
  throw new CannotJudge(next.error);
@@ -337,7 +370,7 @@ export async function runPromoteCheck(args, box, deps) {
337
370
  if (next.next !== "none") {
338
371
  const open = await must(gh("pr", "list", "--repo", repo, "--state", "open", "--head", result.branch, "--base", next.next, "--json", "number", "--jq", ".[0].number // empty"), "PR の一覧を取得できません。");
339
372
  result.prOpen = open.trim();
340
- if (!result.skipped)
373
+ if (!result.skipped && !quick)
341
374
  await checkR2Rule(result.branch, headNow, next.next);
342
375
  }
343
376
  log("INFO", `次に出してよい段階: ${next.next}${result.prOpen ? `(開いている PR: #${result.prOpen})` : ""}`);
package/dist/core/push.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // sft push: カレント配下をコミットしてプッシュする(シェル版の sf-push.sh の移し先)。
2
- // origin/main を取り込み(main 以外のとき)・カレント配下だけをステージ・ターゲットファイルを検証・コミットメッセージを VS Code で入力(-m で省く)→ commit → push。
2
+ // origin/main を取り込み(main 以外のとき)・カレント配下だけをステージ・ターゲットファイルを検証・コミットメッセージを VS Code で入力(-m で省く)→ commit → push(上流のない新しいブランチは、git push -u origin <ブランチ> で上流を設定。失敗したら、git の出力を見せて 1)。
3
3
  // カレント配下に変更がなく、未プッシュのコミットがあれば、push だけ行う。AI 操作(SF_TOOLS_AI=1)で -m がなければ、確認待ち(終了コード 20)で、取り込みの前に止める。
4
4
  // 終了コード: 0 = 正常(何もせず終了した場合を含む)/ 1 = エラー/ 20 = 確認待ち
5
5
  import { branchList, isProtectedBranch } from "./branches.js";
@@ -85,6 +85,16 @@ export async function runPush(args, box, deps) {
85
85
  return die(`${branch} は保護ブランチです(ここでは、コミットもプッシュも行いません)。`);
86
86
  const prefix = ((await box.run("git", ["rev-parse", "--show-prefix"]).catch(() => null))?.stdout ?? "").trim();
87
87
  const pathspec = prefix === "" ? "." : prefix.replace(/\/$/, "");
88
+ // push: 上流のない新しいブランチは、上流を設定して送る(-u)。失敗したら、git の出力(理由)を見せる
89
+ const hasUpstream = async () => (await gitIn(root, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}").catch(() => null))?.code === 0;
90
+ const pushNow = async () => {
91
+ const r = (await hasUpstream()) ? await gitIn(root, "push") : await gitIn(root, "push", "-u", "origin", branch);
92
+ if (r.code === 0)
93
+ return true;
94
+ if (r.output !== "")
95
+ box.output.err(r.output.trimEnd());
96
+ return false;
97
+ };
88
98
  log("HEADER", "カレント配下のコミット・プッシュを開始します (sf-push)");
89
99
  log("INFO", `対象: ${branch}`);
90
100
  if (branch !== "main") {
@@ -102,11 +112,12 @@ export async function runPush(args, box, deps) {
102
112
  if ((await gitIn(root, "add", "--all", "--", pathspec)).code !== 0)
103
113
  return die("git add に失敗しました。");
104
114
  if ((await gitIn(root, "diff", "--cached", "--quiet", "--", pathspec)).code === 0) {
105
- const counted = await gitIn(root, "rev-list", "--count", "@{u}..HEAD").catch(() => null);
115
+ // 上流がなければ(新しいブランチ)、origin/main より進んだ分を、未プッシュとみなす(送っていない失敗の、やり直しのため)
116
+ const counted = await gitIn(root, "rev-list", "--count", (await hasUpstream()) ? "@{u}..HEAD" : "origin/main..HEAD").catch(() => null);
106
117
  const unpushed = counted !== null && counted.code === 0 ? Number(counted.stdout.trim()) : 0;
107
118
  if (Number.isInteger(unpushed) && unpushed > 0) {
108
119
  log("INFO", `未プッシュのコミットが ${unpushed} 件あります。コミットはせず、プッシュだけ行います。`);
109
- if ((await gitIn(root, "push")).code !== 0)
120
+ if (!(await pushNow()))
110
121
  return die("git push に失敗しました。");
111
122
  log("SUCCESS", "未プッシュのコミットのプッシュが完了しました。");
112
123
  return EXIT.ok;
@@ -141,8 +152,8 @@ export async function runPush(args, box, deps) {
141
152
  if ((await gitIn(root, "commit", "-F", file)).code !== 0)
142
153
  return die("git commit に失敗しました。");
143
154
  log("INFO", "git push を実行します。");
144
- if ((await gitIn(root, "push")).code !== 0)
145
- return die("git push に失敗しました。");
155
+ if (!(await pushNow()))
156
+ return die("git push に失敗しました(コミットは済んでいます。直したら、もう一度 sft push で送れます)。");
146
157
  log("SUCCESS", "カレント配下のコミット・プッシュが完了しました。");
147
158
  return EXIT.ok;
148
159
  }
@@ -194,7 +194,7 @@ export async function runRelease(args, box, deps) {
194
194
  for (const type of new Set(manifestPairs(destructive).map((p) => p.slice(0, p.indexOf(":"))))) {
195
195
  if (FOLDERED_TYPES.has(type))
196
196
  continue;
197
- log("CMD", `[sf-release.sh] sf org list metadata --metadata-type ${type} --target-org ${org} --json`);
197
+ log("CMD", `[sft release] sf org list metadata --metadata-type ${type} --target-org ${org} --json`);
198
198
  const list = await listOrgNames(box, org, type);
199
199
  if (list === null)
200
200
  log("WARNING", ` ${type}: 組織にあるかを確かめられませんでした(一覧が取れません)。削除の対象から外しません。`);
@@ -12,7 +12,7 @@
12
12
  // 5. デバッグログの自動の取り始め(log-session.ts の beginLog。答えがなければ聞く。取るなら、ランチャーの裏で取り続ける)
13
13
  // 6. ランチャーを開く。中で組織を切り替えたら、デバッグログを新しい組織に移す(前の組織は leave、新しい組織で取り始め)。
14
14
  // 閉じたら、デバッグログの後始末(leave)。終了コードは、ランチャーによらず 0(中断・ログインの失敗は 1)
15
- // なくしたもの: sf-tools の git pull と、24 時間ごとの CLI の更新(版の固定・人が sft update-cli を動かす: 設計 1.2 の 5・2.4)。
15
+ // なくしたもの: sf-tools の git pull と、24 時間ごとの CLI の自動の更新(版の固定・人が sft update-cli を動かす: 設計 1.2 の 5・2.4)。更新の「知らせ」だけは、src/commands/start.ts が起動時に出す。
16
16
  // WSL の wslview の補い(WSL は force-* の対象外: CLAUDE.md 4.1)。
17
17
  // sf の確認は、シェル版の sf-refresh.sh と同じく、doctor が毎回確かめる(Java は 24 時間省く)
18
18
  import { chooseLoginUrl } from "./login-url.js";
@@ -141,7 +141,7 @@ export async function runStart(box, deps) {
141
141
  const next = await connectedAlias(box);
142
142
  if (next === null || next === alias || !deps.log)
143
143
  return;
144
- await session?.leave();
144
+ await session?.leave().catch((e) => box.output.err(`[WARNING] 前の組織のデバッグログの後始末に失敗しました: ${String(e)}`));
145
145
  alias = next;
146
146
  session = await deps.log(next).catch(() => null);
147
147
  };
@@ -25,7 +25,7 @@ export async function runUpdateCli(args, box, deps) {
25
25
  const warn = (s) => box.output.err(`[WARNING] ${s}`);
26
26
  const lock = deps.acquireLock();
27
27
  if (lock.kind === "busy") {
28
- info(`ほかの sft update-cli・sf-update-cli.sh(PID ${lock.pid})が動いているため、何もせずに終わります。`);
28
+ info(`ほかの sft update-cli(PID ${lock.pid})が動いているため、何もせずに終わります。`);
29
29
  return 0;
30
30
  }
31
31
  if (lock.kind === "unwritable")
@@ -45,6 +45,7 @@ export function realCreateDeps(box, workflowTemplateDir) {
45
45
  },
46
46
  cwd: process.cwd(),
47
47
  templatesDir: fileURLToPath(new URL("../../templates", import.meta.url)),
48
+ workflowsDir: workflowTemplateDir,
48
49
  gitmessageFile: fileURLToPath(new URL("../../config/install/gitmessage", import.meta.url)),
49
50
  workflowTemplateDir,
50
51
  doctor: realDoctorDeps(box),
@@ -1,7 +1,25 @@
1
- // sft job の外の部品の本物。クローンのあとは、そのフォルダへ移って、sft(引数なし)と同じ起動の準備とランチャーを動かす
2
- // (src/commands/start.ts。サブコマンドの表は、循環を避けるため、動かすときに読み込む)
1
+ // sft job の外の部品の本物。クローンのあとは、そのフォルダへ移って、そこで sft(引数なし)を打ったのと同じ手順
2
+ // (版の固定の確認・中の版への受け渡し → 起動の準備とランチャー)を動かす(src/launch.ts。循環を避けるため、動かすときに読み込む)。
3
+ // 自分の版のまま起動すると、版を固定したプロジェクトで、固定と違う版が動き、中の版もフックも入らない(設計 4.2 の 4)
4
+ import { realpathSync } from "node:fs";
3
5
  import { basename, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
4
7
  import { chooseNumber, readOrQuit } from "../ui/prompt.js";
8
+ /** クローン先に移って、引数なしの sft を起動する。戻り値は終了コード。移れなければ null */
9
+ export async function launchInClone(box, repoDir, load) {
10
+ try {
11
+ process.chdir(resolve(repoDir));
12
+ }
13
+ catch {
14
+ box.output.err(`[ERROR] クローン先に移れません: ${repoDir}`);
15
+ return null;
16
+ }
17
+ const { launch } = await import("../launch.js");
18
+ // 中の版は、process.argv の引数で動く(受け渡しの約束: src/launch.ts)。job の引数を残すと、中の版で job がもう一度動く
19
+ process.argv.splice(2);
20
+ const selfEntry = realpathSync(fileURLToPath(new URL("../../bin/sft.js", import.meta.url)));
21
+ return launch({ argv: [], selfEntry, cwd: process.cwd(), env: process.env, box, load });
22
+ }
5
23
  export function realJobDeps(box) {
6
24
  return {
7
25
  prompts: {
@@ -16,16 +34,6 @@ export function realJobDeps(box) {
16
34
  },
17
35
  folderName: basename(process.cwd()),
18
36
  cwd: process.cwd(),
19
- startLauncher: async (repoDir) => {
20
- try {
21
- process.chdir(resolve(repoDir));
22
- }
23
- catch {
24
- box.output.err(`[ERROR] クローン先に移れません: ${repoDir}`);
25
- return null;
26
- }
27
- const [{ commands }, { openStart }] = await Promise.all([import("../commands/index.js"), import("../commands/start.js")]);
28
- return openStart(box, commands);
29
- },
37
+ startLauncher: (repoDir) => launchInClone(box, repoDir),
30
38
  };
31
39
  }
package/dist/io/keys.js CHANGED
@@ -2,11 +2,16 @@
2
2
  // - 端末のとき: キー 1 つ(Enter は要らない)。↑ などは、まとまった 1 回分の文字になる
3
3
  // - 端末でないとき(Node から端末に見えない端末・パイプ): 打って Enter の 1 行を、1 回分にする
4
4
  // - 1 行の入力(readLine): 端末でも、Enter までの 1 行
5
- // - 秘密の入力(readSecret): 端末のときだけ。Enter まで raw モードのまま読み、打った文字の代わりに * を出す(設計 5.5)
5
+ // - 秘密の入力(readSecret): 端末のときだけ(SFT_SECRET_STDIN=1 なら、標準入力の 1 行も受け取る)。Enter まで raw モードのまま読み、打った文字の代わりに * を出す(設計 5.5)
6
6
  // 読むときだけ標準入力を開き、読み終えたら閉じる(プロセスが終われるように。子のプロセスに入力が渡るように)
7
7
  import { StringDecoder } from "node:string_decoder";
8
8
  export const CTRL_C = String.fromCharCode(3);
9
- export function terminalInput(source = process.stdin, sink = process.stderr) {
9
+ /**
10
+ * stdinSecret: 端末でなくても、標準入力の 1 行を、秘密の値として受け取る(SFT_SECRET_STDIN=1 のときだけ。e2e・自動化用。設計 5.5)。
11
+ * 打った文字は、端末にも出ない(パイプには表示がない)が、Node から端末に見えない端末(mintty など)では、画面に出るおそれがあるため、
12
+ * 印がないときは、受け付けない
13
+ */
14
+ export function terminalInput(source = process.stdin, sink = process.stderr, options = {}) {
10
15
  const decoder = new StringDecoder("utf8");
11
16
  /** 行で読むときの、読み残し */
12
17
  let buffered = "";
@@ -143,8 +148,14 @@ export function terminalInput(source = process.stdin, sink = process.stderr) {
143
148
  return next(false);
144
149
  },
145
150
  readSecret: async (prompt) => {
146
- if (!(source.isTTY === true && typeof source.setRawMode === "function"))
147
- return "no-tty";
151
+ if (!(source.isTTY === true && typeof source.setRawMode === "function")) {
152
+ if (options.stdinSecret !== true)
153
+ return "no-tty";
154
+ sink.write(prompt);
155
+ const line = await next(false); // 標準入力の 1 行(値は、画面に出さない)
156
+ sink.write("\n");
157
+ return line;
158
+ }
148
159
  sink.write(prompt);
149
160
  return secret();
150
161
  },
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { RUNTIME_SELF } from "../core/log-pull.js";
7
+ import { removeTree } from "./temp-dir.js";
7
8
  import { upgradeRunning } from "./update-cli-deps.js";
8
9
  /** 別の環境のロックは、10 分で古いとみなす(シェル版の FOREIGN_LOCK_AGE と同じ) */
9
10
  const FOREIGN_LOCK_AGE = 600;
@@ -78,7 +79,7 @@ export function realLogPullDeps(box) {
78
79
  ...realLogSummarizeDeps(box),
79
80
  lock: folderLock(),
80
81
  makeTempDir: () => mkdtempSync(join(tmpdir(), "sft-log-")),
81
- removeDir: (path) => rmSync(path, { recursive: true, force: true }),
82
+ removeDir: removeTree,
82
83
  pidAlive,
83
84
  };
84
85
  }
@@ -1,14 +1,15 @@
1
1
  // sft metasync の外の部品の本物(一時フォルダ・lib/metasync.js と config/ の場所・今日の日付)。テストは、偽物を渡す(src/core/metasync.ts)
2
- import { mkdtempSync, rmSync } from "node:fs";
2
+ import { mkdtempSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { askYesNo } from "../ui/confirm.js";
7
+ import { removeTree } from "./temp-dir.js";
7
8
  export function realMetasyncDeps(box) {
8
9
  const here = (rel) => fileURLToPath(new URL(rel, import.meta.url));
9
10
  return {
10
11
  makeTempDir: () => mkdtempSync(join(process.env.TMPDIR || tmpdir(), "sf-metasync-")),
11
- removeDir: (path) => rmSync(path, { recursive: true, force: true }),
12
+ removeDir: removeTree,
12
13
  confirm: (q) => askYesNo(box.input, q),
13
14
  metasyncJs: box.env("SF_METASYNC_JS") || here("../../lib/metasync.js"),
14
15
  configDir: box.env("SF_METASYNC_CONFIG_DIR") || here("../../config"),
@@ -1,18 +1,19 @@
1
1
  // promote-check の外の部品の本物(一時フォルダ・マニフェストの作成)。テストは、偽物を渡す(src/core/promote-check.ts)
2
- import { mkdtempSync, rmSync } from "node:fs";
2
+ import { mkdtempSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { buildManifest } from "../core/manifest-build.js";
6
6
  import { pairsAll } from "../core/promote.js";
7
+ import { removeTree } from "./temp-dir.js";
7
8
  export function realPromoteDeps(box) {
8
9
  let count = 0;
9
10
  let base = null;
10
11
  return {
11
12
  makeTempDir: () => mkdtempSync(join(tmpdir(), "sf-promote-check-")),
12
13
  removeDir: (path) => {
13
- rmSync(path, { recursive: true, force: true });
14
+ removeTree(path);
14
15
  if (base)
15
- rmSync(base, { recursive: true, force: true });
16
+ removeTree(base);
16
17
  },
17
18
  buildPairs: async (dir, branch) => {
18
19
  base ??= mkdtempSync(join(tmpdir(), "sf-promote-manifest-"));
@@ -2,9 +2,23 @@
2
2
  import { mkdtempSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ /**
6
+ * フォルダを消す。Windows では、ウイルス対策・インデクサー・終わったばかりの子プロセスが、フォルダをつかんでいて、EPERM・EBUSY で
7
+ * 消せないことがある(ときどき起きる)ため、再試行する(maxRetries・retryDelay)。それでも消せなければ、止めずに、消せなかった場所を
8
+ * 警告に出す(中に、アクセストークンなどが残ることがある。手で消してもらう)。呼ぶ側の処理を、後始末の失敗で、失敗にしない
9
+ */
10
+ export function removeTree(path) {
11
+ try {
12
+ rmSync(path, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
13
+ }
14
+ catch (e) {
15
+ const code = e.code ?? "";
16
+ process.stderr.write(`[WARNING] 一時フォルダを消せませんでした(${code})。中に、秘密の値が残っているかもしれません。手で消してください: ${path}\n`);
17
+ }
18
+ }
5
19
  export function realTempDeps(prefix) {
6
20
  return {
7
21
  makeTempDir: () => mkdtempSync(join(process.env.TMPDIR || tmpdir(), prefix)),
8
- removeDir: (path) => rmSync(path, { recursive: true, force: true }),
22
+ removeDir: removeTree,
9
23
  };
10
24
  }