@nathanstephenson/flow 0.1.10-beta.7 → 0.1.10-beta.8

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.
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- 8ab6f68e-a8d0-4e4f-a520-68e8a0b6b031
1
+ d55666c9-014a-4615-bc06-84cd0d47d46e
@@ -889,7 +889,7 @@ async function bootstrap() {
889
889
  if (!managed) throw new Error("Missing systemd update configuration");
890
890
  await assertSystemdOwner(managed, managed.updater, process.pid);
891
891
  }
892
- const lease = await install.register("8ab6f68e-a8d0-4e4f-a520-68e8a0b6b031", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
892
+ const lease = await install.register("d55666c9-014a-4615-bc06-84cd0d47d46e", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
893
893
  delete process.env.FLOW_UPDATE_CAPABILITY;
894
894
  process.on("exit", lease.release);
895
895
  if (args[0] === "update") {
@@ -117,6 +117,7 @@ function applyEvent(state, event, at) {
117
117
  ...(event.fromSessionId === undefined
118
118
  ? { text: event.text }
119
119
  : { text: event.text.slice(event.text.indexOf("\n") + 1), fromSessionId: event.fromSessionId }),
120
+ ...(event.note === undefined ? {} : { note: event.note }),
120
121
  ...(event.attachments === undefined ? {} : { attachments: event.attachments }),
121
122
  at,
122
123
  }),
@@ -7,7 +7,7 @@ import { copyFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
7
7
  import { isAbsolute, join, resolve } from "node:path";
8
8
  import { validateFilesystemScope } from "../isolation/filesystem.js";
9
9
  import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest, createPullRequest, editPullRequest, setPullRequestDraft, rerunPullRequestChecks, checkLog } from "./pull-request.js";
10
- import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
10
+ import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage, mergeableStack, stackMergeMethods } from "./stack.js";
11
11
  import { changes, changesText, commitContext, diff } from "./changes.js";
12
12
  import { commit } from "./commit.js";
13
13
  import { push, pushState } from "./push.js";
@@ -115,7 +115,7 @@ export class SessionHost {
115
115
  }
116
116
  }
117
117
  async prepareStack(sessionId, action) {
118
- if (action !== "submit" && action !== "sync")
118
+ if (action !== "submit" && action !== "sync" && action !== "merge")
119
119
  throw new CommandRefused("Invalid Stack review action.");
120
120
  const record = this.record(sessionId);
121
121
  return this.withGitOperation(record.scope, async () => {
@@ -124,19 +124,28 @@ export class SessionHost {
124
124
  const status = await stackStatus(record.scope);
125
125
  if (!status.view)
126
126
  throw new Error(status.notice ?? "This branch is not in a stack.");
127
+ const fingerprint = await stackFingerprint(record.scope, status.view, action === "sync");
127
128
  const review = { token: randomUUID(), action, view: status.view };
128
- this.stackReviews.set(sessionId, { review, fingerprint: await stackFingerprint(record.scope, status.view, action === "sync"), expires: Date.now() + 15 * 60_000 });
129
+ if (action === "merge") {
130
+ review.view = await mergeableStack(record.scope);
131
+ review.mergeMethods = await stackMergeMethods(record.scope, review.view);
132
+ if (!review.mergeMethods.length)
133
+ throw new Error("You cannot merge pull requests in this repository.");
134
+ }
135
+ this.stackReviews.set(sessionId, { review, fingerprint, expires: Date.now() + 15 * 60_000 });
129
136
  return review;
130
137
  });
131
138
  }
132
139
  async changeStack(sessionId, input) {
133
140
  const record = this.record(sessionId);
134
141
  return this.withGitOperation(record.scope, async () => {
135
- if (input.action === "submit" || input.action === "sync") {
142
+ if (input.action === "submit" || input.action === "sync" || input.action === "merge") {
136
143
  const saved = this.stackReviews.get(sessionId);
137
144
  this.stackReviews.delete(sessionId);
138
145
  if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
139
146
  throw new Error("This Stack review expired. Review again.");
147
+ if (input.action === "merge" && !saved.review.mergeMethods?.includes(input.method))
148
+ throw new Error("This repository does not permit that merge method.");
140
149
  await cleanStack(record.scope);
141
150
  const status = await stackStatus(record.scope);
142
151
  if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
@@ -2949,7 +2958,8 @@ export class SessionHost {
2949
2958
  record.log.append({
2950
2959
  type: "user_message",
2951
2960
  id: messageId,
2952
- text: sent,
2961
+ text,
2962
+ ...(note === undefined ? {} : { note }),
2953
2963
  ...(attachments.length > 0 ? { attachments } : {}),
2954
2964
  ...(fromSessionId === undefined ? {} : { fromSessionId }),
2955
2965
  });
@@ -1,5 +1,5 @@
1
1
  import { api, connection, gh, page } from "./github.js";
2
- import { githubRepository, localRepository, resolvePullRequest, resolveRepository } from "./repository.js";
2
+ import { githubRepository, localRepository, mergeMethods, mergeSettingsFields, resolvePullRequest, resolveRepository, writers } from "./repository.js";
3
3
  import { cleanStack } from "./stack.js";
4
4
  import { pushTarget, remoteHead } from "./push.js";
5
5
  import { localStack, stackParent } from "./stack-metadata.js";
@@ -8,8 +8,7 @@ const commentFields = "id author{login} body url createdAt";
8
8
  const threadFields = "id path line isOutdated isResolved viewerCanReply viewerCanResolve viewerCanUnresolve";
9
9
  const threadCommentFields = `${commentFields} diffHunk`;
10
10
  const checkFields = "... on CheckRun{name status conclusion detailsUrl} ... on StatusContext{context state targetUrl}";
11
- const detailsQuery = `query($id:ID!){node(id:$id){... on PullRequest{id number url title body state isDraft reviewDecision updatedAt author{login} headRefName headRefOid headRepository{id nameWithOwner} baseRefName mergeable mergeStateStatus locked repository{isArchived viewerPermission mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed} comments(first:100){nodes{${commentFields}} ${page}} reviews(first:100){nodes{${commentFields} state} ${page}} reviewThreads(first:100){nodes{${threadFields} comments(first:100){nodes{${threadCommentFields}} ${page}}} ${page}} commits(last:1){nodes{commit{statusCheckRollup{id contexts(first:100){nodes{${checkFields}} ${page}}}}}}}}}`;
12
- const writers = ["ADMIN", "MAINTAIN", "WRITE"];
11
+ const detailsQuery = `query($id:ID!){node(id:$id){... on PullRequest{id number url title body state isDraft reviewDecision updatedAt author{login} headRefName headRefOid headRepository{id nameWithOwner} baseRefName mergeable mergeStateStatus locked repository{${mergeSettingsFields}} comments(first:100){nodes{${commentFields}} ${page}} reviews(first:100){nodes{${commentFields} state} ${page}} reviewThreads(first:100){nodes{${threadFields} comments(first:100){nodes{${threadCommentFields}} ${page}}} ${page}} commits(last:1){nodes{commit{statusCheckRollup{id contexts(first:100){nodes{${checkFields}} ${page}}}}}}}}}`;
13
12
  const comment = (value) => ({ ...value, author: value.author?.login ?? "[deleted]" });
14
13
  function check(node) {
15
14
  const url = node.detailsUrl || node.targetUrl || "";
@@ -28,14 +27,8 @@ async function details(scope, ref, github) {
28
27
  threads.push({ ...thread, diffHunk: all[0]?.diffHunk ?? "", comments: all.map(comment) });
29
28
  }
30
29
  const rollup = commits.nodes[0]?.commit.statusCheckRollup;
31
- const writer = !repository.isArchived && writers.includes(repository.viewerPermission ?? "");
32
- const mergeMethods = !writer ? [] : [
33
- ...(repository.mergeCommitAllowed ? ["MERGE"] : []),
34
- ...(repository.squashMergeAllowed ? ["SQUASH"] : []),
35
- ...(repository.rebaseMergeAllowed ? ["REBASE"] : []),
36
- ];
37
30
  return { headRepositoryId: headRepository?.id, pr: {
38
- ...fields, repo: ref.repo, author: author?.login ?? "[deleted]", mergeMethods,
31
+ ...fields, repo: ref.repo, author: author?.login ?? "[deleted]", mergeMethods: mergeMethods(repository),
39
32
  ...(headRepository ? { headRepository: headRepository.nameWithOwner } : {}),
40
33
  viewerCanComment: !repository.isArchived && (!locked || writers.includes(repository.viewerPermission ?? "")),
41
34
  comments: (await connection(scope, github, comments, id, "PullRequest", "comments", commentFields)).map(comment),
@@ -104,3 +104,14 @@ export async function resolvePullRequest(scope, repository, branch, github = gh)
104
104
  unresolvedThreads: pr.reviewThreads.nodes.filter(thread => !thread.isResolved).length, updatedAt: pr.updatedAt,
105
105
  };
106
106
  }
107
+ export const writers = ["ADMIN", "MAINTAIN", "WRITE"];
108
+ export const mergeSettingsFields = "isArchived viewerPermission mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed";
109
+ export function mergeMethods(repository) {
110
+ if (repository.isArchived || !writers.includes(repository.viewerPermission ?? ""))
111
+ return [];
112
+ return [
113
+ ...(repository.mergeCommitAllowed ? ["MERGE"] : []),
114
+ ...(repository.squashMergeAllowed ? ["SQUASH"] : []),
115
+ ...(repository.rebaseMergeAllowed ? ["REBASE"] : []),
116
+ ];
117
+ }
@@ -2,9 +2,10 @@ import { commonGitPath, localStack, localStacks } from "./stack-metadata.js";
2
2
  import { access } from "node:fs/promises";
3
3
  import { resolve } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
- import { localRepository, resolveRepository } from "./repository.js";
5
+ import { localRepository, mergeMethods, mergeSettingsFields, resolveRepository } from "./repository.js";
6
6
  import { api, gh } from "./github.js";
7
7
  import { head, localBranches, run, GIT_READ_TIMEOUT_MS, GIT_WRITE_TIMEOUT_MS } from "./git.js";
8
+ import { stackMergeBlock } from "../protocol/stack.js";
8
9
  async function git(scope, args, write = false) {
9
10
  const result = await run(scope, args, write ? GIT_WRITE_TIMEOUT_MS : GIT_READ_TIMEOUT_MS);
10
11
  if (!result.ok)
@@ -67,7 +68,7 @@ export async function stackStatus(scope, github = gh) {
67
68
  if (stacks.some(stack => stack.trunk.branch === branch))
68
69
  return { ...status, notice: trunkNotice };
69
70
  try {
70
- return { ...status, view: parseStack(await runStack(scope, ["view", "--json"], github)) };
71
+ return { ...status, view: await withTracking(scope, parseStack(await runStack(scope, ["view", "--json"], github))) };
71
72
  }
72
73
  catch (error) {
73
74
  if (!notInStack.test(String(error)))
@@ -79,6 +80,33 @@ export async function stackStatus(scope, github = gh) {
79
80
  const stacked = new Set(stacks.flatMap(stack => stack.branches.map(member => member.branch)));
80
81
  return { ...status, create: { current: branch, ...(trunk ? { trunk } : {}), branches: listed.value, unstacked: listed.value.filter(name => !stacked.has(name)) } };
81
82
  }
83
+ async function withTracking(scope, view) {
84
+ const tracking = new Map((await git(scope, ["for-each-ref", "--format=%(refname:short)%00%(upstream)%00%(upstream:track,nobracket)", "refs/heads"])).split("\n").map(line => line.split("\0")).map(([name, upstream, track]) => [name, upstream ? track ?? "" : undefined]));
85
+ for (const branch of view.branches) {
86
+ const track = tracking.get(branch.name);
87
+ if (track === undefined || track === "gone")
88
+ continue;
89
+ branch.ahead = Number(/ahead (\d+)/.exec(track)?.[1] ?? 0);
90
+ branch.behind = Number(/behind (\d+)/.exec(track)?.[1] ?? 0);
91
+ }
92
+ return view;
93
+ }
94
+ export async function stackMergeMethods(scope, view, github = gh) {
95
+ const [owner, name] = (await resolveRepository(scope, view.currentBranch, github)).base.repo.split("/");
96
+ const { repository } = await api(scope, github, `query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${mergeSettingsFields}}}`, { owner: owner, name: name });
97
+ return mergeMethods(repository);
98
+ }
99
+ const mergeFlags = { MERGE: "--merge", SQUASH: "--squash", REBASE: "--rebase" };
100
+ export async function mergeableStack(scope, github = gh) {
101
+ const { view, notice } = await stackStatus(scope, github);
102
+ if (!view)
103
+ throw new Error(notice ?? "This branch is not in a stack.");
104
+ await stackTitles(scope, view, github);
105
+ const block = stackMergeBlock(view);
106
+ if (block)
107
+ throw new Error(block);
108
+ return view;
109
+ }
82
110
  const titles = new Map();
83
111
  async function readTitles(scope, branch, numbers, github) {
84
112
  const [owner, name] = (await resolveRepository(scope, branch, github)).base.repo.split("/");
@@ -171,7 +199,7 @@ async function validateInit(scope, trunk, branches, github) {
171
199
  }
172
200
  export async function changeStack(scope, input, github = gh) {
173
201
  const { action } = input;
174
- if (!["init", "add", "checkout", "rebase", "continue", "abort", "submit", "sync"].includes(action))
202
+ if (!["init", "add", "checkout", "rebase", "continue", "abort", "submit", "sync", "merge"].includes(action))
175
203
  throw new Error("Unknown Stack action.");
176
204
  if (action === "continue" || action === "abort") {
177
205
  const state = await stackStatus(scope, github);
@@ -209,6 +237,12 @@ export async function changeStack(scope, input, github = gh) {
209
237
  args.splice(0, 1, "rebase", `--${action}`);
210
238
  if (action === "submit")
211
239
  args.push("--auto");
240
+ if (action === "merge") {
241
+ if (!input.method || !Object.hasOwn(mergeFlags, input.method))
242
+ throw new Error("Invalid merge method.");
243
+ await mergeableStack(scope, github);
244
+ args.push("--yes", mergeFlags[input.method]);
245
+ }
212
246
  return runStack(scope, args, github);
213
247
  }
214
248
  export const stackConflictMessage = "Resolve the current gh stack rebase conflicts in this Scope. Inspect the Stack rebase state and conflict files first. Preserve the intended changes and stage only resolved files. Run gh stack rebase --continue only after git diff --name-only --diff-filter=U is empty and all conflicts are resolved. Repeat for further conflicts; stop and report if the intended resolution is unclear. This request permits local conflict repair and Stack rebase continuation only. Do not push, submit, sync, merge, or restructure the stack. Report the result so I can review it before any separate Sync confirmation.";
@@ -1 +1,14 @@
1
- export {};
1
+ export function stackMergeBlock(view) {
2
+ const open = view.branches.filter(branch => !branch.isMerged);
3
+ if (!open.length)
4
+ return "All pull requests of this stack are merged.";
5
+ for (const { name, pr } of open) {
6
+ if (!pr)
7
+ return `${name} has no pull request. Submit the stack first.`;
8
+ if (pr.state !== "OPEN")
9
+ return `#${pr.number} is ${pr.state.toLowerCase()}.`;
10
+ if (pr.isDraft)
11
+ return `#${pr.number} is a draft. Mark it ready for review first.`;
12
+ }
13
+ return undefined;
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathanstephenson/flow",
3
- "version": "0.1.10-beta.7",
3
+ "version": "0.1.10-beta.8",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",