Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import type { ListPullRequestFiles } from "../../../engine/model/pull-request.js";

/** Lists the integrations without a quality scale, so a first tier changes it. */
const HASSFEST_LIST = "script/hassfest/quality_scale.py";

const MANIFEST = /^homeassistant\/components\/([^/]+)\/manifest\.json$/;

/** A top-level manifest key, indented by two spaces. */
const TOP_LEVEL_KEY = /^ {2}"(\w+)":/;

/** A PR's change to the quality scale tier in an existing integration's manifest. */
export interface TierChange {
domain: string;
tier: string;
/** The tier it replaces; absent for a first tier. */
previous?: string;
/**
* Whether the PR changes nothing else: no other manifest setting and no
* other file, apart from the hassfest list for a first tier.
*/
standalone: boolean;
}

/**
* The top-level keys a manifest patch changes, `?` for lines it can't place,
* and the tier it sets and replaces. A line before a new last key gains a
* comma, which is not a change.
*/
export function changedKeys(patch: string): {
keys: Set<string>;
tier?: string;
previous?: string;
} {
const lines = new Map<string, { "+": string[]; "-": string[] }>();
let key: string | undefined;
let tier: string | undefined;
let previous: string | undefined;
for (const line of patch.split("\n")) {
if (line.startsWith("@@")) {
key = undefined;
continue;
}
const own = TOP_LEVEL_KEY.exec(line.slice(1))?.[1];
if (own) key = own;
const sign = line[0];
if (sign !== "+" && sign !== "-") continue;

const content = line.slice(1).trim().replace(/,$/, "");
const changed = lines.get(key ?? "?") ?? { "+": [], "-": [] };
changed[sign].push(content);
lines.set(key ?? "?", changed);

const scale = /^"quality_scale":\s*"([^"]+)"$/.exec(content);
if (scale && sign === "+") tier = scale[1];
else if (scale) previous = scale[1];
}
const keys = new Set<string>();
for (const [name, changed] of lines) {
if (changed["+"].sort().join("\n") !== changed["-"].sort().join("\n")) keys.add(name);
}
return { keys, tier, previous };
}

/**
* The quality scale tier the PR sets in an existing integration's manifest,
* if any. A new integration's manifest is not a change.
*/
export function tierChange(files: ListPullRequestFiles): TierChange | undefined {
const manifests = files.flatMap((file) => {
const match = MANIFEST.exec(file.filename);
if (!match || file.status !== "modified") return [];
return [{ file, domain: match[1], ...changedKeys(file.patch ?? "") }];
});
const first = manifests.find((m) => m.tier && m.keys.has("quality_scale"));
if (!first?.tier) return undefined;

const companion = (filename: string) =>
filename === HASSFEST_LIST && first.previous === undefined;
const standalone =
manifests.length === 1 &&
first.keys.size === 1 &&
files.every((f) => f === first.file || companion(f.filename));
return { domain: first.domain, tier: first.tier, previous: first.previous, standalone };
}
2 changes: 2 additions & 0 deletions src/github/manifests/home-assistant-core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { integrationTopRank } from "./rules/integration-top-rank.js";
import { integrationTransport } from "./rules/integration-transport.js";
import { issueContext } from "./rules/issue-context.js";
import { issueLinks } from "./rules/issue-links.js";
import { manifestChangeCheck } from "./rules/manifest-change.js";
import { newIntegrationValidation } from "./rules/new-integration-validation.js";
import { newPlatformValidation } from "./rules/new-platform-validation.js";
import { platinumApproval } from "./rules/platinum-approval.js";
Expand Down Expand Up @@ -66,6 +67,7 @@ export const homeAssistantCore: RepoManifest = {
newIntegrationValidation,
newPlatformValidation,
configFlowTests,
manifestChangeCheck,
forbiddenFiles({ base: "dev", files: coreForbiddenFiles }),
integrationTransport,
mentionCodeOwners({ pathPattern: componentCodeowners, domains }),
Expand Down
46 changes: 46 additions & 0 deletions src/github/manifests/home-assistant-core/rules/manifest-change.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { EventType } from "../../../engine/event.js";
import type { RuleContext } from "../../../engine/model/rule-context.js";
import { type CheckOutcome, check } from "../../../engine/rule.js";
import { tierChange } from "../helpers/manifest-change.js";
import { isReleasePR } from "../helpers/release-pr.js";

type HandledEvent =
| EventType.PULL_REQUEST_OPENED
| EventType.PULL_REQUEST_REOPENED
| EventType.PULL_REQUEST_EDITED
| EventType.PULL_REQUEST_SYNCHRONIZE
| EventType.ON_DEMAND;

async function evaluate(ctx: RuleContext<HandledEvent>): Promise<CheckOutcome> {
if (await isReleasePR(ctx.target)) {
return { status: "skip", message: "Not checked on release PRs." };
}

const change = tierChange(await ctx.target.files());
if (!change) return { status: "skip", message: "No quality scale tier change." };
if (change.standalone) {
return { status: "pass", message: "The quality scale tier change stands alone." };
}
return {
status: "fail",
message:
"Change only the quality scale tier in this PR, and move the other changes to a separate PR.",
};
}

export const manifestChangeCheck = check({
id: "manifest-change",
title: "Manifest",
waivableBy: "member",
description:
"Fails PRs that change an existing integration's quality scale tier along with " +
"anything else; a first tier may also update the hassfest list",
events: [
EventType.PULL_REQUEST_OPENED,
EventType.PULL_REQUEST_REOPENED,
EventType.PULL_REQUEST_EDITED,
EventType.PULL_REQUEST_SYNCHRONIZE,
EventType.ON_DEMAND,
],
evaluate,
});
29 changes: 28 additions & 1 deletion src/github/manifests/home-assistant-core/rules/title.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { EventType } from "../../../engine/event.js";
import type { ListPullRequestFiles } from "../../../engine/model/pull-request.js";
import type { RuleContext } from "../../../engine/model/rule-context.js";
import { type CheckOutcome, check } from "../../../engine/rule.js";
import { fetchIntegrationManifest } from "../../../helpers/integration-manifest.js";
import { tierChange } from "../helpers/manifest-change.js";
import { isReleasePR } from "../helpers/release-pr.js";

type HandledEvent =
Expand Down Expand Up @@ -38,6 +41,24 @@ function styleProblems(title: string): string[] {
return problems;
}

/**
* `Set quality scale to <tier> in <integration>` for a PR that changes nothing
* but the tier, with the name the integration has on dev. The "Manifest" check
* flags a tier change that doesn't stand alone, which has no expected title.
*/
async function qualityScaleTitle(
files: ListPullRequestFiles,
): Promise<{ suggestion: string; matches: (title: string) => boolean } | undefined> {
const change = tierChange(files);
if (!change?.standalone) return undefined;
const text = `Set quality scale to ${change.tier} in`;
const name = (await fetchIntegrationManifest(change.domain))?.name;
return {
matches: (title) => (name ? title === `${text} ${name}` : title.startsWith(`${text} `)),
suggestion: `${text} ${name ?? change.domain}`,
};
}

async function evaluate(ctx: RuleContext<HandledEvent>): Promise<CheckOutcome> {
const pr = ctx.target;
if (await isReleasePR(pr)) {
Expand All @@ -47,6 +68,11 @@ async function evaluate(ctx: RuleContext<HandledEvent>): Promise<CheckOutcome> {
const title = (await pr.title()).trim();
if (/^revert\b/i.test(title)) return { status: "skip", message: "Not checked on reverts." };

const qualityScale = await qualityScaleTitle(await pr.files());
if (qualityScale && !qualityScale.matches(title)) {
return { status: "fail", message: `Rename this PR to \`${qualityScale.suggestion}\`.` };
}

const problems = styleProblems(title);
return problems.length > 0
? { status: "fail", message: problems.join("\n") }
Expand All @@ -57,7 +83,8 @@ export const title = check({
id: "title",
title: "PR title",
description:
"Fails titles with a prefix, a lowercase first letter, a trailing dot, an issue number or more than 72 characters.",
"Fails quality scale changes that aren't titled in the usual form, " +
"and any title with a prefix, a lowercase first letter, a trailing dot, an issue number or more than 72 characters.",
allowBots: false,
events: [
EventType.PULL_REQUEST_OPENED,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { changedKeys } from "../../../../../src/github/manifests/home-assistant-core/helpers/manifest-change.js";

const keys = (patch: string) => [...changedKeys(patch).keys].sort();

describe("changedKeys", () => {
it("reads a changed tier and the one it replaces", () => {
expect(changedKeys('- "quality_scale": "silver",\n+ "quality_scale": "gold",')).toEqual({
keys: new Set(["quality_scale"]),
tier: "gold",
previous: "silver",
});
});

it("ignores the comma a new last key adds", () => {
expect(
keys(
'- "requirements": ["foo==1"]\n+ "requirements": ["foo==1"],\n+ "quality_scale": "bronze"',
),
).toEqual(["quality_scale"]);
});

it("places lines inside a list under its key", () => {
expect(keys(' "codeowners": [\n- "@a"\n+ "@a",\n+ "@b"\n ],')).toEqual([
"codeowners",
]);
});

it("places nested keys under the top-level key", () => {
expect(
keys(
' "zeroconf": [\n {\n- "type": "_a._tcp.local."\n+ "type": "_b._tcp.local."',
),
).toEqual(["zeroconf"]);
});

it("can't place a changed line before any key in its hunk", () => {
expect(keys('@@ -10,3 +10,4 @@\n "@a",\n+ "@b",\n ],')).toEqual(["?"]);
});

it("reports several keys", () => {
expect(
keys('- "name": "A",\n+ "name": "B",\n- "codeowners": ["@a"],\n+ "codeowners": ["@b"],'),
).toEqual(["codeowners", "name"]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { describe, expect, it } from "vitest";
import { EventType } from "../../../../../src/github/engine/event.js";
import { manifestChangeCheck } from "../../../../../src/github/manifests/home-assistant-core/rules/manifest-change.js";
import { createMockContext, mockPRFiles, runRule } from "../../../helpers/mock-context.js";

const HASSFEST_LIST = "script/hassfest/quality_scale.py";
const TIER_PATCH = '- "quality_scale": "silver",\n+ "quality_scale": "gold",';
const FIRST_TIER_PATCH =
'- "requirements": ["iometer==1"]\n+ "requirements": ["iometer==1"],\n+ "quality_scale": "gold"';
const OWNERS_PATCH = '- "codeowners": ["@a"],\n+ "codeowners": ["@a", "@b"],';

function makeFile(filename: string, patch = "+x = 1", status = "modified") {
return { filename, status, additions: 1, deletions: 1, changes: 2, patch };
}

function component(path: string, patch = "+x = 1", status = "modified", domain = "iometer") {
return makeFile(`homeassistant/components/${domain}/${path}`, patch, status);
}

async function run(files: Record<string, unknown>[]) {
const context = createMockContext({
eventType: EventType.PULL_REQUEST_SYNCHRONIZE,
payload: { pull_request: { title: "Some title", base: { ref: "dev" } } },
});
mockPRFiles(context, files);
const result = await runRule(manifestChangeCheck, context);
expect(result?.effects).toEqual([]);
return result?.section;
}

const TIER_FAIL =
"Change only the quality scale tier in this PR, and move the other changes to a separate PR.";

describe("manifest-change", () => {
it.each([
["no manifest change", [component("sensor.py")]],
[
"another manifest change",
[
component(
"manifest.json",
'- "iot_class": "cloud_polling",\n+ "iot_class": "local_polling",',
),
],
],
["a new integration", [component("manifest.json", FIRST_TIER_PATCH, "added")]],
["rule changes only", [component("quality_scale.yaml")]],
["a code owner change", [component("manifest.json", OWNERS_PATCH), makeFile("CODEOWNERS")]],
])("skips %s", async (_name, files) => {
expect(await run(files)).toMatchObject({ id: "manifest-change", status: "skip" });
});

it.each([
["a changed tier", [component("manifest.json", TIER_PATCH)]],
["a first tier", [component("manifest.json", FIRST_TIER_PATCH)]],
[
"a first tier with the hassfest list",
[component("manifest.json", FIRST_TIER_PATCH), makeFile(HASSFEST_LIST)],
],
])("passes %s", async (_name, files) => {
expect(await run(files)).toMatchObject({ title: "Manifest", status: "pass" });
});

it.each([
["rule changes", [component("manifest.json", TIER_PATCH), component("quality_scale.yaml")]],
[
"a first tier and a new rules file",
[
component("manifest.json", FIRST_TIER_PATCH),
component("quality_scale.yaml", "+rules:", "added"),
makeFile(HASSFEST_LIST),
],
],
[
"other manifest changes",
[component("manifest.json", `${TIER_PATCH}\n- "iot_class": "a",\n+ "iot_class": "b",`)],
],
["a code owner change", [component("manifest.json", `${OWNERS_PATCH}\n${TIER_PATCH}`)]],
["the hassfest list", [component("manifest.json", TIER_PATCH), makeFile(HASSFEST_LIST)]],
["CODEOWNERS", [component("manifest.json", TIER_PATCH), makeFile("CODEOWNERS")]],
["code", [component("manifest.json", TIER_PATCH), component("sensor.py")]],
[
"another integration's tier",
[
component("manifest.json", TIER_PATCH),
component("manifest.json", TIER_PATCH, "modified", "other"),
],
],
])("fails a tier change with %s", async (_name, files) => {
expect(await run(files)).toMatchObject({ status: "fail", message: TIER_FAIL });
});
});
Loading