Skip to content

fix: update existing ruleset when in transition mode #1951

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 4, 2025
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
32 changes: 28 additions & 4 deletions src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import lazyValue from "lazy-value";
import npmUser from "npm-user";
import { z } from "zod";

import { inputFromOctokit } from "./inputs/inputFromGitHub.js";
import { parsePackageAuthor } from "./options/parsePackageAuthor.js";
import { readDefaultsFromReadme } from "./options/readDefaultsFromReadme.js";
import { readDescription } from "./options/readDescription.js";
Expand Down Expand Up @@ -125,6 +126,10 @@ export const base = createBase({
repository: z
.string()
.describe("'kebab-case' or 'PascalCase' title of the repository"),
rulesetId: z
.string()
.optional()
.describe("GitHub branch ruleset ID for main branch protections"),
title: z.string().describe("'Title Case' title for the repository"),
usage: z
.string()
Expand Down Expand Up @@ -163,6 +168,20 @@ export const base = createBase({

const readme = lazyValue(async () => await readFileSafe("README.md", ""));

const rulesetId = lazyValue(async () => {
const rulesets = (await take(inputFromOctokit, {
endpoint: "GET /repos/{owner}/{repo}/rulesets",
options: {
owner: await owner(),
repo: await repository(),
},
})) as { id: string; name: string }[];

return rulesets.find(
(ruleset) => ruleset.name === "Branch protection for main",
)?.id;
});

// TODO: Make these all use take

const gitDefaults = tryCatchLazyValueAsync(async () =>
Expand Down Expand Up @@ -198,6 +217,13 @@ export const base = createBase({

const version = lazyValue(async () => (await packageData()).version);

const owner = lazyValue(
async () =>
(await gitDefaults())?.organization ??
(await packageAuthor()).author ??
(await githubCliUser()),
);

const repository = lazyValue(
async () =>
options.repository ??
Expand All @@ -218,10 +244,7 @@ export const base = createBase({
guide: readGuide,
login: author,
node,
owner: async () =>
(await gitDefaults())?.organization ??
(await packageAuthor()).author ??
(await githubCliUser()),
owner,
packageData: async () => {
const original = await packageData();

Expand All @@ -232,6 +255,7 @@ export const base = createBase({
};
},
repository,
rulesetId,
...readDefaultsFromReadme(readme, repository),
version,
};
Expand Down
72 changes: 66 additions & 6 deletions src/blocks/blockRepositoryBranchRuleset.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,99 @@ import { blockRepositoryBranchRuleset } from "./blockRepositoryBranchRuleset.js"
import { optionsBase } from "./options.fakes.js";

describe("blockRepositoryBranchRuleset", () => {
test("without addons", () => {
test("without addons when mode is undefined", () => {
const creation = testBlock(blockRepositoryBranchRuleset, {
options: optionsBase,
});

expect(creation).toMatchInlineSnapshot(`{}`);
});

// TODO for improving the "requests" snapshots:
// https://github.com/JoshuaKGoldberg/create/issues/65

test("without addons when mode is setup", () => {
const creation = testBlock(blockRepositoryBranchRuleset, {
mode: "setup",
options: optionsBase,
});

expect(creation).toMatchInlineSnapshot(`
{
"requests": [
{
"id": "branch-ruleset",
"id": "branch-ruleset-create",
"send": [Function],
},
],
}
`);
});

// TODO for improving the "requests" snapshots:
// https://github.com/JoshuaKGoldberg/create/issues/65
test("without addons when mode is transition", () => {
const creation = testBlock(blockRepositoryBranchRuleset, {
mode: "transition",
options: optionsBase,
});

expect(creation).toMatchInlineSnapshot(`
{
"requests": [
{
"id": "branch-ruleset-update",
"send": [Function],
},
],
}
`);
});

test("with addons when mode is undefined", () => {
const creation = testBlock(blockRepositoryBranchRuleset, {
addons: {
requiredStatusChecks: ["build", "test"],
},
options: optionsBase,
});

expect(creation).toMatchInlineSnapshot(`{}`);
});

test("with addons when mode is setup", () => {
const creation = testBlock(blockRepositoryBranchRuleset, {
addons: {
requiredStatusChecks: ["build", "test"],
},
mode: "setup",
options: optionsBase,
});

expect(creation).toMatchInlineSnapshot(`
{
"requests": [
{
"id": "branch-ruleset-create",
"send": [Function],
},
],
}
`);
});

test("with addons", () => {
test("with addons when mode is transition", () => {
const creation = testBlock(blockRepositoryBranchRuleset, {
addons: {
requiredStatusChecks: ["build", "test"],
},
mode: "setup",
options: optionsBase,
});

expect(creation).toMatchInlineSnapshot(`
{
"requests": [
{
"id": "branch-ruleset",
"id": "branch-ruleset-create",
"send": [Function],
},
],
Expand Down
140 changes: 86 additions & 54 deletions src/blocks/blockRepositoryBranchRuleset.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BlockCreation } from "bingo-stratum";
import { z } from "zod";

import { base } from "../base.js";
import { base, BaseOptions } from "../base.js";

export const blockRepositoryBranchRuleset = base.createBlock({
about: {
Expand All @@ -9,60 +10,91 @@ export const blockRepositoryBranchRuleset = base.createBlock({
addons: {
requiredStatusChecks: z.array(z.string()).default([]),
},
produce({ addons, options }) {
return {
requests: [
{
id: "branch-ruleset",
async send({ octokit }) {
await octokit.request("POST /repos/{owner}/{repo}/rulesets", {
bypass_actors: [
{
// This *seems* to be the Repository Admin role always?
// https://github.com/github/rest-api-description/issues/4406
actor_id: 5,
actor_type: "RepositoryRole",
bypass_mode: "always",
},
],
conditions: {
ref_name: {
exclude: [],
include: ["refs/heads/main"],
},
setup({ addons, options }) {
return createRequestSend(
addons.requiredStatusChecks,
"POST /repos/{owner}/{repo}/rulesets",
options,
"branch-ruleset-create",
undefined,
);
},
transition({ addons, options }) {
return createRequestSend(
addons.requiredStatusChecks,
`PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}`,
options,
"branch-ruleset-update",
options.rulesetId,
);
},
// TODO: Make produce() optional
// This needs createBlock to be generic to know if block.produce({}) is ok
produce() {
return {};
},
});

function createRequestSend(
contexts: string[],
endpoint: string,
options: BaseOptions,
requestId: string,
rulesetId: string | undefined,
): Partial<BlockCreation<BaseOptions>> {
return {
requests: [
{
id: requestId,
async send({ octokit }) {
await octokit.request(endpoint, {
bypass_actors: [
{
// This *seems* to be the Repository Admin role always?
// https://github.com/github/rest-api-description/issues/4406
actor_id: 5,
actor_type: "RepositoryRole",
bypass_mode: "always",
},
],
conditions: {
ref_name: {
exclude: [],
include: ["refs/heads/main"],
},
enforcement: "active",
name: "Branch protection for main",
owner: options.owner,
repo: options.repository,
rules: [
{ type: "deletion" },
{
parameters: {
allowed_merge_methods: ["squash"],
dismiss_stale_reviews_on_push: false,
require_code_owner_review: false,
require_last_push_approval: false,
required_approving_review_count: 0,
required_review_thread_resolution: false,
},
type: "pull_request",
},
enforcement: "active",
name: "Branch protection for main",
owner: options.owner,
repo: options.repository,
rules: [
{ type: "deletion" },
{
parameters: {
allowed_merge_methods: ["squash"],
dismiss_stale_reviews_on_push: false,
require_code_owner_review: false,
require_last_push_approval: false,
required_approving_review_count: 0,
required_review_thread_resolution: false,
},
{
parameters: {
required_status_checks: addons.requiredStatusChecks.map(
(context) => ({ context }),
),
strict_required_status_checks_policy: false,
},
type: "required_status_checks",
type: "pull_request",
},
{
parameters: {
required_status_checks: contexts.map((context) => ({
context,
})),
strict_required_status_checks_policy: false,
},
],
target: "branch",
});
},
type: "required_status_checks",
},
],
ruleset_id: rulesetId,
target: "branch",
});
},
],
};
},
});
},
],
};
}
22 changes: 22 additions & 0 deletions src/inputs/inputFromGitHub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createInput } from "bingo";
import { z } from "zod";

export const inputFromOctokit = createInput({
args: {
endpoint: z.string(),
options: z.record(z.string(), z.unknown()),
},
// TODO: Strongly type this, then push it upstream to Bingo
// This will require smart types around GitHub endpoints, similar to:
// https://github.com/JoshuaKGoldberg/bingo/issues/65
async produce({ args, fetchers }): Promise<unknown> {
const response = await fetchers.octokit.request(args.endpoint, {
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
...args.options,
});

return response.data;
},
});