@tama-create/sf-tools 1.4.0-dev.12 → 1.4.0-dev.13

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.
@@ -33,14 +33,34 @@ export function withStartItem(items, box, startAgain, make) {
33
33
  const start = make(startAgain);
34
34
  return at < 0 ? [...items, start] : [...items.slice(0, at), start, ...items.slice(at)];
35
35
  }
36
- export async function openLauncher(commands, box, orgSwitched, startAgain) {
37
- const pr = commands.find((c) => c.name === "pr");
38
- // 画面に出さず、入力も受けない箱(裏の判定用)
39
- const quiet = {
36
+ /** 画面に出さず、入力も受けない箱(裏の判定用) */
37
+ function quietBox(box) {
38
+ return {
40
39
  ...box,
41
40
  output: { out: () => { }, err: () => { } },
42
41
  input: { readKey: async () => null, readLine: async () => null, readSecret: async () => null },
43
42
  };
43
+ }
44
+ /**
45
+ * ランチャーを開く前(組織への接続・doctor のあいだ)に、Branch の判定(sft pr --status)を始める。
46
+ * メニューが出るときには、判定が終わっているか、終わりかけにするため(Windows は 1 回に十数秒かかる)。sft pr がなければ null
47
+ */
48
+ export function startEarlyCheck(commands, box) {
49
+ const pr = commands.find((c) => c.name === "pr");
50
+ if (!pr)
51
+ return null;
52
+ let finished = false;
53
+ const promise = pr
54
+ .run(["--status"], quietBox(box))
55
+ .catch(() => undefined)
56
+ .finally(() => {
57
+ finished = true;
58
+ });
59
+ return { promise, done: () => finished };
60
+ }
61
+ export async function openLauncher(commands, box, orgSwitched, startAgain, early) {
62
+ const pr = commands.find((c) => c.name === "pr");
63
+ const quiet = quietBox(box);
44
64
  return runLauncher([], box, {
45
65
  items: withStartItem(launcherItems(commands, box, orgSwitched), box, startAgain, (run) => ({
46
66
  name: "start",
@@ -51,7 +71,9 @@ export async function openLauncher(commands, box, orgSwitched, startAgain) {
51
71
  })),
52
72
  folderName: basename(process.cwd()),
53
73
  color: process.stderr.isTTY === true && box.env("NO_COLOR") === undefined,
74
+ checkTimeout: () => new Promise((resolve) => setTimeout(resolve, 90000).unref()),
54
75
  tick: () => new Promise((resolve) => setTimeout(resolve, 5000).unref()),
55
76
  startPrStatus: pr ? () => pr.run(["--status"], quiet) : null,
77
+ earlyCheck: early ?? undefined,
56
78
  });
57
79
  }
@@ -17,7 +17,7 @@ export const pushCommand = {
17
17
  users: ["human", "ai"],
18
18
  exitCodes: [{ code: 20, summary: "確認待ち(AI 操作で、-m がない)" }],
19
19
  questions: ["push.message"],
20
- menu: { label: "Push", order: 4, description: "変更をコミット & プッシュ", group: 1 },
20
+ menu: { label: "Push & PR", order: 4, description: "変更をコミット・プッシュして、PR を出す", group: 1 },
21
21
  run: (args, box) => runPush(args, box, {
22
22
  ...realTempDeps("sf-push-"),
23
23
  capability: () => loadCapabilityTable(box.env),
@@ -11,7 +11,7 @@ import { runStart } from "../core/start.js";
11
11
  import { realSessionDeps } from "../io/log-deps.js";
12
12
  import { readVersion } from "../io/package-version.js";
13
13
  import { loginPrompts } from "../ui/prompt.js";
14
- import { openLauncher } from "./launcher.js";
14
+ import { openLauncher, startEarlyCheck } from "./launcher.js";
15
15
  /** 知らせを待つ上限(これを超えたら、先に進む) */
16
16
  const NOTICE_WAIT_MS = 2_000;
17
17
  export async function openStart(box, commands) {
@@ -45,6 +45,8 @@ export async function openStart(box, commands) {
45
45
  }
46
46
  /** 起動の本体(接続・doctor・ランチャー) */
47
47
  async function startMain(box, commands, doctor) {
48
+ // Branch の判定は、組織への接続・doctor より先に始める(メニューが出るときに、終わっているか、終わりかけにする)
49
+ const early = startEarlyCheck(commands, box);
48
50
  return runStart(box, {
49
51
  folderName: basename(process.cwd()),
50
52
  prompts: loginPrompts(box.input),
@@ -61,7 +63,7 @@ async function startMain(box, commands, doctor) {
61
63
  if (code === 0)
62
64
  await orgSwitched();
63
65
  return code;
64
- }),
66
+ }, early),
65
67
  log: (org) => beginLog(box, realSessionDeps(box), org),
66
68
  });
67
69
  }
@@ -7,7 +7,7 @@
7
7
  // SKIPPED= が今の対象のファイル(作業ツリー)の空・空でないと合うときだけ使う)。
8
8
  // 対象を書いたファイルにコミット前の変更があるときは「コミット前の変更があります」(次の PR 先は出さない・判定も頼まない)
9
9
  // 使えないときは、裏の判定(sft pr --status)を頼み、動いているあいだは「(確かめています…)」、
10
- // 終わった・頼めないときは「(Enter で確かめる)」
10
+ // 終わった・頼めないときは「(Enter で確かめる)」。判定が失敗した・終わらなかったときは、理由つきの「(確認できません: …)」
11
11
  // 表示する値は cleanText で掃除する(制御文字・幅のない文字・文字の向きを変える文字・BOM を除き、画面を崩させない)
12
12
  export function makePaint(color) {
13
13
  const wrap = (code) => (s) => (color ? `\u001b[${code}m${s}\u001b[0m` : s);
@@ -129,6 +129,16 @@ export function apexlogSummary(text, paint) {
129
129
  }
130
130
  }
131
131
  const NAME_RE = /^[A-Za-z0-9._/-]{1,40}$/;
132
+ /** next-status.txt の ERROR=(判断できなかった理由)。先端のコミットが今と同じときだけ。掃除して 100 文字で切る。なければ空 */
133
+ export function parseNextError(text, head) {
134
+ if (text === null || head === "")
135
+ return "";
136
+ const kv = keyValues(text);
137
+ if (kv.get("HEAD") !== head)
138
+ return "";
139
+ const t = cleanText(kv.get("ERROR") ?? "");
140
+ return t.length > 100 ? `${t.slice(0, 100)}…` : t;
141
+ }
132
142
  /** sf-tools/logs/next-status.txt を読む。先端のコミットと違う・形が違う(段階は 10 個まで・PR は 9 桁まで)ときは null */
133
143
  export function parseNextStatus(text, head) {
134
144
  if (text === null || head === "")
@@ -208,7 +218,12 @@ export function statusLines(input, paint) {
208
218
  }
209
219
  else {
210
220
  wantCheck = true;
211
- rel = input.checking ? paint.dim("(確かめています…)") : ask;
221
+ const why = input.error ?? "";
222
+ rel = input.checking
223
+ ? paint.dim("(確かめています…)")
224
+ : why !== ""
225
+ ? paint.yellow(`(確認できません: ${why})`) + paint.dim(" Enter で確かめ直す")
226
+ : ask;
212
227
  }
213
228
  if (st && input.checking)
214
229
  rel += ` ${paint.dim("(更新中…)")}`;
package/dist/core/pr.js CHANGED
@@ -96,11 +96,24 @@ export async function runPr(args, box, deps, ask) {
96
96
  if (isProtectedBranch(current, list.branches))
97
97
  return die(`${current} は保護ブランチ(${listFile})のため、実行できません。`);
98
98
  log("INFO", "どの段階まで出たかを確かめています(promote-check --plan)...");
99
- // --status は、前回の結果を、新しい結果が出るまで残す(ランチャーが、待つあいだ前回の結果を出せる)。判断できなかったときだけ消す
99
+ // --status は、前回の結果を、新しい結果が出るまで残す(ランチャーが、待つあいだ前回の結果を出せる)。判断できなかったときは、結果を消して、理由(ERROR=)を書く
100
100
  if (!status)
101
101
  box.files.removeFile(NEXT_STATUS_FILE);
102
- const dieStatus = (text) => {
102
+ // 判断できなかったとき: --status は、理由を ERROR= に書く(ランチャーが「確認できません: 理由」と出せるように。何も書かないと、確かめ直しても同じ表示のまま、理由が見えない)。対話の実行は、結果を消すだけ
103
+ const dieStatus = async (text) => {
103
104
  box.files.removeFile(NEXT_STATUS_FILE);
105
+ if (status) {
106
+ const h = await box.run("git", ["rev-parse", "-q", "--verify", "HEAD"]).catch(() => null);
107
+ if (h !== null && h.code === 0) {
108
+ try {
109
+ box.files.makeDir("./sf-tools/logs");
110
+ box.files.writeText(NEXT_STATUS_FILE, `HEAD=${h.stdout.trim()}\nERROR=${text.replace(/[\r\n]+/g, " ").slice(0, 300)}\n`);
111
+ }
112
+ catch {
113
+ // 表示用のため、書けなくても続ける
114
+ }
115
+ }
116
+ }
104
117
  return die(text);
105
118
  };
106
119
  const lines = [];
@@ -142,15 +142,29 @@ export async function runPromoteCheck(args, box, deps) {
142
142
  return got.stdout;
143
143
  };
144
144
  // --- R0 の前提: リポジトリ・段階 ---
145
- await must(git("rev-parse", "--is-inside-work-tree"), "Git リポジトリの中ではありません。");
146
- const origin = await originRepo(box);
145
+ // 互いに関係しない読み取りは、先に同時に動かす(Windows は、プロセスの起動に 1 回約 1 秒かかる。順に待たず、判定を速くする)
146
+ const insideP = git("rev-parse", "--is-inside-work-tree");
147
+ const originP = originRepo(box);
148
+ const headP = git("rev-parse", "HEAD");
149
+ const symP = mode === "plan" ? git("symbolic-ref", "--quiet", "--short", "HEAD") : null;
150
+ const fetchMainP = git("fetch", "--quiet", "origin", "main");
151
+ // 手元のブランチの取得も、同時に始める(環境ブランチのときは、使わずに捨てる)
152
+ const fetchBranchP = symP === null
153
+ ? null
154
+ : symP
155
+ .then((r) => (r.code === 0 ? git("fetch", "--quiet", "origin", r.stdout.trim()) : { code: 1, stdout: "" }))
156
+ .catch(() => ({ code: 1, stdout: "" }));
157
+ for (const q of [insideP, originP, headP, symP, fetchMainP, fetchBranchP])
158
+ q?.catch(() => undefined); // 待たないうちの失敗を、未処理にしない
159
+ await must(insideP, "Git リポジトリの中ではありません。");
160
+ const origin = await originP;
147
161
  if (origin.kind === "none")
148
162
  throw new CannotJudge("origin の URL を取得できません。");
149
163
  if (origin.kind === "notGithub")
150
164
  throw new CannotJudge("origin が GitHub のリポジトリではありません。");
151
165
  const repo = `${origin.owner}/${origin.repo}`;
152
166
  const repoLc = repo.toLowerCase();
153
- await must(git("fetch", "--quiet", "origin", "main"), "origin の main を取得できません。");
167
+ await must(fetchMainP, "origin の main を取得できません。");
154
168
  const branchesTxt = await must(git("show", `origin/main:${BRANCH_LIST_FILE}`), `origin/main の ${BRANCH_LIST_FILE} を読めません。`);
155
169
  const tiers = tierList(branchesTxt, { strict: true, fileName: BRANCH_LIST_FILE });
156
170
  if (!tiers.ok) {
@@ -276,7 +290,7 @@ export async function runPromoteCheck(args, box, deps) {
276
290
  }
277
291
  };
278
292
  // --- メイン ---
279
- const headNow = (await must(git("rev-parse", "HEAD"), "HEAD を読めません。")).trim();
293
+ const headNow = (await must(headP, "HEAD を読めません。")).trim();
280
294
  if (mode === "pr") {
281
295
  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})。`);
282
296
  let pr;
@@ -338,7 +352,7 @@ export async function runPromoteCheck(args, box, deps) {
338
352
  }
339
353
  else {
340
354
  // --plan: 手元のブランチ
341
- const sym = await git("symbolic-ref", "--quiet", "--short", "HEAD").catch(() => ({ code: 1, stdout: "" }));
355
+ const sym = await symP.catch(() => ({ code: 1, stdout: "" }));
342
356
  if (sym.code !== 0)
343
357
  throw new CannotJudge("ブランチの上にいません(detached HEAD)。");
344
358
  result.branch = sym.stdout.trim();
@@ -348,7 +362,10 @@ export async function runPromoteCheck(args, box, deps) {
348
362
  emit(false);
349
363
  return PROMOTE_EXIT.violated;
350
364
  }
351
- await must(git("fetch", "--quiet", "origin", result.branch), `origin の ${result.branch} を取得できません(push していない可能性があります)。`);
365
+ await must(fetchBranchP ?? git("fetch", "--quiet", "origin", result.branch), `origin の ${result.branch} を取得できません(push していない可能性があります)。`);
366
+ // 開いている PR は、全段階分を 1 回で取り、段階の判定(印の確認)と同時に動かす
367
+ const openP = gh("pr", "list", "--repo", repo, "--state", "open", "--head", result.branch, "--json", "number,baseRefName", "--jq", '.[] | [.baseRefName, (.number | tostring)] | join(" ")');
368
+ openP.catch(() => undefined);
352
369
  const remote = (await must(git("rev-parse", `origin/${result.branch}`), `origin/${result.branch} を読めません。`)).trim();
353
370
  if (remote !== headNow) {
354
371
  throw new CannotJudge(`手元(${headNow.slice(0, 7)})と origin/${result.branch}(${remote.slice(0, 7)})が違います(push していない変更があるか、取り込んでいない変更があります)。`);
@@ -368,8 +385,11 @@ export async function runPromoteCheck(args, box, deps) {
368
385
  result.nextTier = next.next;
369
386
  result.target = next.next;
370
387
  if (next.next !== "none") {
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 の一覧を取得できません。");
372
- result.prOpen = open.trim();
388
+ const open = (await must(openP, "PR の一覧を取得できません。"))
389
+ .split("\n")
390
+ .map((l) => l.trim().split(" "))
391
+ .find((f) => f[0] === next.next)?.[1] ?? "";
392
+ result.prOpen = open;
373
393
  if (!result.skipped && !quick)
374
394
  await checkR2Rule(result.branch, headNow, next.next);
375
395
  }
@@ -8,7 +8,7 @@
8
8
  // 結果は 1 行: 0 →「✓ <名前>: 終わりました(成功)」/ それ以外 →「✗ <名前>: 失敗、または中断しました(終了コード N)」。
9
9
  // なくしたもの: 自分のファイルの書き換わりを見て読み込み直す動き(版を固定するため: 設計 2.4.2)。
10
10
  // 組織への接続・doctor・デバッグログの取得は、開く前に src/core/start.ts が行う。項目 Start は、組織の接続・VS Code・doctor をやり直す(src/commands/start.ts。ランチャーは開き直さない)
11
- import { apexlogState, makePaint, parseGitStatus, statusLines, targetOrg, uncommittedTargets } from "../core/launcher-status.js";
11
+ import { apexlogState, makePaint, parseGitStatus, parseNextError, statusLines, targetOrg, uncommittedTargets, } from "../core/launcher-status.js";
12
12
  import { countTargets } from "../core/promote-check.js";
13
13
  const LINE = "──────────────────────────────────────────────────";
14
14
  const readOrNull = (box, path) => {
@@ -38,6 +38,9 @@ export async function runLauncher(args, box, deps) {
38
38
  let checkDone = false;
39
39
  /** Enter で頼まれた判定のやり直し(次に描くとき、保存した結果を使わずに判定する) */
40
40
  let recheck = false;
41
+ /** 裏の判定が時間切れで終わったか(次に判定を始めるまで) */
42
+ let timedOut = false;
43
+ let earlyUsed = false;
41
44
  const wantCheckFor = (head, key) => head !== "" && key !== checkedKey;
42
45
  const targetsEmpty = (branch) => {
43
46
  try {
@@ -61,6 +64,29 @@ export async function runLauncher(args, box, deps) {
61
64
  const git = parseGitStatus(statusText);
62
65
  const empty = targetsEmpty(git.branch);
63
66
  const key = `${git.head} ${empty}`;
67
+ const nextStatusText = readOrNull(box, "sf-tools/logs/next-status.txt");
68
+ // 開く前に始めた判定は、最初の描画で引き継ぐ(終わっていれば、結果のファイルをそのまま使う。動いていれば、終わりを待つ)
69
+ if (deps.earlyCheck && !earlyUsed) {
70
+ earlyUsed = true;
71
+ checkedKey = key;
72
+ if (!deps.earlyCheck.done()) {
73
+ checking = true;
74
+ const limit = deps.checkTimeout;
75
+ Promise.race([
76
+ deps.earlyCheck.promise,
77
+ ...(limit
78
+ ? [
79
+ limit().then(() => {
80
+ timedOut = true;
81
+ }),
82
+ ]
83
+ : []),
84
+ ]).finally(() => {
85
+ checking = false;
86
+ checkDone = true;
87
+ });
88
+ }
89
+ }
64
90
  const fresh = recheck && !checking && deps.startPrStatus !== null;
65
91
  if (fresh)
66
92
  checkedKey = "";
@@ -69,7 +95,8 @@ export async function runLauncher(args, box, deps) {
69
95
  git,
70
96
  org: targetOrg(readOrNull(box, ".sf/config.json")),
71
97
  apexlog: readOrNull(box, "logs/apex/.status"),
72
- nextStatus: readOrNull(box, "sf-tools/logs/next-status.txt"), // 判定し直すあいだも、前回の結果を出す(「更新中」を添える)
98
+ nextStatus: nextStatusText, // 判定し直すあいだも、前回の結果を出す(「更新中」を添える)
99
+ error: parseNextError(nextStatusText, git.head) || (timedOut ? "時間切れ(判定が終わりませんでした)" : ""),
73
100
  targetsEmpty: empty,
74
101
  uncommitted: uncommittedTargets(statusText, git.branch),
75
102
  envBranches: envBranches(),
@@ -80,8 +107,18 @@ export async function runLauncher(args, box, deps) {
80
107
  if (wantCheck && wantCheckFor(git.head, key) && deps.startPrStatus !== null) {
81
108
  checkedKey = key;
82
109
  checking = true;
83
- deps
84
- .startPrStatus()
110
+ timedOut = false;
111
+ const limit = deps.checkTimeout;
112
+ Promise.race([
113
+ deps.startPrStatus(),
114
+ ...(limit
115
+ ? [
116
+ limit().then(() => {
117
+ timedOut = true;
118
+ }),
119
+ ]
120
+ : []),
121
+ ])
85
122
  .catch(() => undefined)
86
123
  .finally(() => {
87
124
  checking = false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tama-create/sf-tools",
3
- "version": "1.4.0-dev.12",
3
+ "version": "1.4.0-dev.13",
4
4
  "description": "Salesforce 開発の環境構築と毎日の作業を自動化する(TypeScript 版・開発中)",
5
5
  "license": "Unlicense",
6
6
  "repository": {