Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
185 changes: 106 additions & 79 deletions cli/src/plan/commands.ts

Large diffs are not rendered by default.

229 changes: 151 additions & 78 deletions cli/src/plan/github.ts

Large diffs are not rendered by default.

17 changes: 9 additions & 8 deletions cli/src/plan/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,16 +148,17 @@ export interface PlanIssue {
readonly assignees: ReadonlyArray<Actor>;
readonly comments: ReadonlyArray<IssueComment>;
readonly history: ReadonlyArray<NamedLabel>;
readonly closer: Closer | null | undefined;
readonly closedEventAt: string | undefined;
/** No event and an event whose closer is unknown have different meanings. */
readonly closeEvent: { readonly createdAt: string; readonly closer: Closer | null } | undefined;
readonly children: ReadonlyArray<IssueSummary>;
readonly parent: ParentLink | null | undefined;
/** The viewer id that a write claims an unassigned plan for. */
claimantId: string | undefined;
/** The acting login of a write read, which a write accepts as an owner of the plan. */
actingLogin?: string;
/** The owner that a write of the command claimed and confirmed; a later write requires it. */
confirmedOwner?: string;
}

/** An issue prepared for mutation after the command checks its contract, labels and owners. */
export interface WritablePlanIssue extends PlanIssue {
readonly viewer: { readonly id: string; readonly login: string };
/** A pending claim sends the viewer ID; confirmation requires the viewer login on later writes. */
claim: "assigned" | "pending" | "confirmed";
}

/** The fields that the status derivation reads; a plan issue and an issue summary both have them. */
Expand Down
20 changes: 19 additions & 1 deletion cli/test/fixtures/gh-stub/ghStub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1338,7 +1338,25 @@ if (group === "issue" && command === "view") {
// Real gh reads `labels(first:100)` for `issue view` (cli/cli api/query_builder.go), so it never
// returns a label past the first 100.
const view = issueJson(issue);
emit(JSON.stringify(select({ ...view, labels: view.labels.slice(0, 100) }, value("--json"))));
const selected = select({ ...view, labels: view.labels.slice(0, 100) }, value("--json"));
// `issueViewOmitsViewerLoginOnce` shows the viewer assignee of one view with its node id alone, as an actor reply
// whose login is missing.
const viewer = state.viewerLogin;
const omitsLogin =
state.issueViewOmitsViewerLoginOnce === number &&
Object.hasOwn(selected, "assignees") &&
viewer !== undefined &&
(issue.assignees ?? []).includes(viewer);
if (omitsLogin) delete state.issueViewOmitsViewerLoginOnce;
const shown = omitsLogin
? {
...selected,
assignees: (issue.assignees ?? []).map((login) =>
login === viewer ? { id: userNodeId(login) } : { id: userNodeId(login), login },
),
}
: selected;
emit(JSON.stringify(shown));
// `afterIssueViewOnce` lands its change right after the view, such as a change between a pre-write read and a later
// GraphQL read.
const viewChange = state.afterIssueViewOnce;
Expand Down
5 changes: 5 additions & 0 deletions cli/test/fixtures/gh-stub/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ export type StubState = {
* view once the issue has served `afterReads` GraphQL reads. The view shows the issue before the change.
*/
afterIssueViewOnce?: StubChange & { issue: number };
/**
* The issue whose next `gh issue view` that lists the viewer as an assignee shows that assignee with its node id and
* without its login.
*/
issueViewOmitsViewerLoginOnce?: number;
/** A change, in the form of a scheduled change, that lands right after one GraphQL request that lists issues. */
afterListOnce?: StubChange & { issue: number };
ghLacksParentFlag?: boolean;
Expand Down
24 changes: 21 additions & 3 deletions cli/test/unit/plan/children.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,35 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan child plans", () => {
);

it(
"new writes the v5 marker",
"new without --parent writes the v5 marker and links the plan to no parent",
() => {
const context = planCliContext();
// An open plan of the acting login that `new --parent` would accept, so a stray link has a parent to land on.
const possibleParent = context.createPlan("possible parent");
const expected = context.loadState().nextIssue;
const result = context.run("new", "--title", "plain plan", "--goal", "Fix the parser");
expectSuccess(result, "new");
const number = Number(/^plan created: #(\d+) /m.exec(result.stdout)?.[1]);
expect(number, "new prints the created plan").toBe(expected);
expect(context.issue(number).body).toMatch(/^<!-- plan-contract: v5 -->\n/);
expect(creates(context).at(-1), "the create names no parent").not.toContain("--parent");
expect(
context.issue(number).subIssues,
"a plan without --parent gets no parent",
context.issue(possibleParent).subIssues,
"the possible parent stores no sub-issue",
).toBeUndefined();
expect(
context
.loadState()
.issues.filter((entry) => entry.subIssues?.includes(number))
.map((entry) => entry.number),
"no issue stores the plan as its sub-issue",
).toStrictEqual([]);
expect(
context
.loadState()
.calls.filter(([group, command]) => group === "api" && command !== "graphql"),
"no REST sub-issue link",
).toStrictEqual([]);
},
SPAWN_TIMEOUT_MS,
);
Expand Down
125 changes: 125 additions & 0 deletions cli/test/unit/plan/reopen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,43 @@ function stored({ issue }: PlanCliContext, number: number) {
};
}

// The data of a pull request read for an unmerged `plan.pr` that closes the plan, as GitHub answers it, with the
// `pullRequest` fields of `replaced` in place of its own. `graphqlMissingData` serves it for the next page read.
function unmergedRead(plan: PartialMerge, replaced: Readonly<Record<string, unknown>>) {
return {
repository: {
nameWithOwner: "DocksDocks/fixture",
pullRequest: {
url: `https://github.com/DocksDocks/fixture/pull/${plan.pr}`,
merged: false,
mergedAt: null,
baseRefName: "main",
body: null,
headRefOid: `head${plan.pr}`,
mergeCommit: null,
closingIssuesReferences: {
nodes: [{ number: plan.number, repository: { nameWithOwner: "DocksDocks/fixture" } }],
pageInfo: { hasNextPage: false, endCursor: null },
},
...replaced,
},
},
};
}

// A closing reference whose issue number is a string.
function malformedReferences(plan: PartialMerge) {
return {
closingIssuesReferences: {
nodes: [{ number: String(plan.number), repository: { nameWithOwner: "DocksDocks/fixture" } }],
pageInfo: { hasNextPage: false, endCursor: null },
},
};
}

const MALFORMED_REFERENCES = "gh api graphql returned malformed closing issue references";
const MALFORMED_PULL_REQUEST = "gh api graphql returned malformed pull request";

describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => {
it(
"reopen waits for the close by the pull request, then reopens with the contract comment and a claim",
Expand Down Expand Up @@ -234,6 +271,52 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => {
SPAWN_TIMEOUT_MS,
);

// The pull request read checks its closing references, then its merge fields, before it decides that the pull request
// has not merged; an unmerged pull request is no reason to skip a malformed field.
for (const [name, replaced, message] of [
["well-formed fields", () => ({}), (plan) => `pull request #${plan.pr} is not merged`],
["malformed closing references", malformedReferences, () => MALFORMED_REFERENCES],
["a head commit without an oid", () => ({ headRefOid: null }), () => MALFORMED_PULL_REQUEST],
[
"a merge commit without an oid",
() => ({ mergeCommit: { oid: "", associatedPullRequests: null } }),
() => MALFORMED_PULL_REQUEST,
],
[
"malformed closing references and a head commit without an oid",
(plan) => ({ ...malformedReferences(plan), headRefOid: null }),
() => MALFORMED_REFERENCES,
],
] as const satisfies ReadonlyArray<
readonly [
string,
(plan: PartialMerge) => Readonly<Record<string, unknown>>,
(plan: PartialMerge) => string,
]
>) {
it(
`reopen answers an unmerged pull request read with ${name} from that read alone and writes nothing`,
() => {
const context = planCliContext();
const plan = context.partialMerge(`unmerged pull request with ${name}`, { merged: false });
context.updateState((state) => {
state.graphqlMissingData = { on: "page", data: unmergedRead(plan, replaced(plan)) };
});
refuse(reopen(context, plan), message(plan));
const state = context.loadState();
expect(state.graphqlMissingData, "the pull request read got the response").toBeUndefined();
expect(
state.calls.filter(([group, command]) => group === "api" && command === "graphql"),
"the pull request read is the only GraphQL read",
).toHaveLength(1);
expect(stored(context, plan.number)).toStrictEqual(ONGOING);
expect(context.writes()).toStrictEqual([]);
expect(context.waits()).toStrictEqual([]);
},
SPAWN_TIMEOUT_MS,
);
}

it(
"reopen refuses a v5 plan before any wait or write, and names child plans",
() => {
Expand Down Expand Up @@ -747,6 +830,24 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => {
SPAWN_TIMEOUT_MS,
);

it(
"reopen refuses an assigned viewer without a login in its pre-write response",
() => {
const context = planCliContext();
const plan = context.partialMerge("viewer login missing from guarded read", {
assignees: ["plan-agent"],
});
context.schedule(plan.number, { afterReads: 0, ...closedBy(plan.closer) });
context.updateState((state) => {
state.issueViewOmitsViewerLoginOnce = plan.number;
});
refuse(reopen(context, plan), `plan #${plan.number} is owned by undefined`);
expect(context.issue(plan.number).state).toBe("CLOSED");
expect(context.writes()).toStrictEqual([]);
},
SPAWN_TIMEOUT_MS,
);

it(
"reopen refuses a plan that another login claims after the settle-wait read, right before the write",
() => {
Expand Down Expand Up @@ -821,6 +922,30 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan reopen", () => {
SPAWN_TIMEOUT_MS,
);

it(
"reopen refuses an unassigned plan that only its last read before the write shows owned by the acting login",
() => {
const context = planCliContext();
const plan = context.partialMerge("acting login claims after the pre-write read");
context.schedule(plan.number, { afterReads: 0, ...closedBy(plan.closer) });
// The pre-write read shows no owner, so the reopen would claim the plan. The acting login is no foreign owner, but
// the owners of the last read no longer match the owners that the claim was decided from.
context.updateState((state) => {
state.afterIssueViewOnce = { issue: plan.number, afterReads: 2, assignees: ["plan-agent"] };
});
refuse(reopen(context, plan), settleRefusal(plan.number));
expect(context.waits()).toStrictEqual([SETTLE_WAIT]);
expect(stored(context, plan.number)).toStrictEqual({
...ONGOING,
state: "CLOSED",
stateReason: "COMPLETED",
assignees: ["plan-agent"],
});
expect(context.writes(), "no reopen, no claim, and no comment").toStrictEqual([]);
},
SPAWN_TIMEOUT_MS,
);

it(
"reopen reports a failed first request with the state that the plan reads after it",
() => {
Expand Down
42 changes: 42 additions & 0 deletions cli/test/unit/plan/write-postconditions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,48 @@ describe.skipIf(!PLAN_CLI_HOST_SUPPORTED)("plan write postconditions", () => {
SPAWN_TIMEOUT_MS,
);

it(
"retire admits a pending claim by the viewer's node id and refuses a confirmed claim without the viewer's login",
() => {
const { run, issue, updateIssue, updateState, loadState, createPlan, schedule } =
planCliContext();
// The viewer is assigned after the snapshot, and the pre-write read shows it by its node id alone.
const pending = createPlan("viewer by node id before the claim");
updateIssue(pending, (entry) => {
entry.assignees = [];
});
schedule(pending, { afterReads: 1, assignees: ["plan-agent"] });
updateState((state) => {
state.issueViewOmitsViewerLoginOnce = pending;
});
const retired = run("retire", String(pending), "--reason", "No longer needed");
expectSuccess(retired, "retire with the viewer by node id");
expect(loadState().issueViewOmitsViewerLoginOnce).toBeUndefined();
expect(retired.stdout.trim()).toBe(`plan #${pending} retired`);
expect(issue(pending).state).toBe("CLOSED");
expect(issue(pending).assignees).toStrictEqual(["plan-agent"]);

// The claim lands, and the read right before the close shows the viewer by its node id alone.
const confirmed = createPlan("viewer by node id after the claim");
updateIssue(confirmed, (entry) => {
entry.assignees = [];
});
updateState((state) => {
state.issueViewOmitsViewerLoginOnce = confirmed;
});
refuse(
run("retire", String(confirmed), "--reason", "No longer needed"),
`plan #${confirmed} is owned by undefined`,
);
expect(loadState().issueViewOmitsViewerLoginOnce).toBeUndefined();
expect(issue(confirmed).state).toBe("OPEN");
expect(issue(confirmed).comments ?? []).toStrictEqual([]);
expect(issue(confirmed).assignees).toStrictEqual(["plan-agent"]);
expect(issue(confirmed).labels).toStrictEqual(["plan"]);
},
SPAWN_TIMEOUT_MS,
);

it(
"retire reads the plan before the close even when it removes and claims nothing",
() => {
Expand Down
Loading