Skip to content
Draft
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
99 changes: 99 additions & 0 deletions .github/pr-checks/new-dependency.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
'use strict';

const prBody = require('./pr-body.js');
const { Toml } = require('./toml.js');

/** The workspace's manifest, whose `[workspace.dependencies]` every crate
* takes its dependencies from. */
const MANIFEST = 'Cargo.toml';

/** cargo-deny's configuration. */
const DENY = 'deny.toml';

/** The arrays of deny.toml whose elements are exceptions to its policy. */
const EXCEPTIONS = [
'advisories.ignore',
'licenses.allow',
'licenses.exceptions',
'bans.skip',
'bans.skip-tree',
'sources.allow-git',
'sources.allow-registry',
];

/** The description's section that justifies a new dependency. */
const SECTION = 'Dependencies';

/**
* DP8: a pull request that adds an entry to `[workspace.dependencies]` or
* an exception to deny.toml says why in a "Dependencies" section of its
* description, as the `tech-stack` skill writes it. What it says is left to
* review.
*/
const newDependency = {
name: 'new-dependency',

async findings(pr) {
const justified = prBody
.sections(pr.body)
.some(({ heading, text }) => heading.toLowerCase() === SECTION.toLowerCase() && text);
if (justified) return [];
const changed = new Set((await pr.files()).map(({ path }) => path));
const added = [];
for (const [path, read] of [
[MANIFEST, newDependency.dependencies],
[DENY, newDependency.exceptions],
]) {
if (!changed.has(path)) continue;
const before = new Set(read(new Toml((await pr.fileAt(pr.base, path)) ?? '')).keys());
for (const [item, { line, what }] of read(new Toml((await pr.fileAt(pr.head, path)) ?? ''))) {
if (!before.has(item)) added.push({ path, line, what });
}
}
return added.map(({ path, line, what }) => ({
path,
line,
message:
`this adds ${what}: add a \`## ${SECTION}\` section to the description saying what it ` +
`is for and what else was considered, as the \`tech-stack\` skill writes it.`,
}));
},

/** Each workspace dependency of a manifest, by name. */
dependencies(toml) {
const found = new Map();
for (const { table, key, line } of toml.entries) {
const name =
table === 'workspace.dependencies'
? key.split('.')[0]
: table.startsWith('workspace.dependencies.') && table.split('.')[2];
if (name && !found.has(name)) found.set(name, { line, what: `the workspace dependency \`${name}\`` });
}
return found;
},

/** Each exception of a deny.toml, by its array and its text, squeezed. */
exceptions(toml) {
const found = new Map();
const sections = new Map();
for (const { table, key, value, line, section } of toml.entries) {
const array = table ? `${table}.${key}` : key;
if (EXCEPTIONS.includes(array)) {
for (const item of Toml.items(value)) {
found.set(`${array}: ${item}`, { line, what: `\`${item}\` to \`${array}\`` });
}
} else if (EXCEPTIONS.includes(table)) {
const element = sections.get(section) ?? { table, line, fields: [] };
element.fields.push(`${key} = ${value.replace(/\s+/g, ' ')}`);
sections.set(section, element);
}
}
for (const { table, line, fields } of sections.values()) {
const item = `{ ${fields.sort().join(', ')} }`;
found.set(`${table}: ${item}`, { line, what: `\`${item}\` to \`${table}\`` });
}
return found;
},
};

module.exports = newDependency;
63 changes: 63 additions & 0 deletions .github/pr-checks/new-dependency.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
'use strict';

const test = require('node:test');
const assert = require('node:assert/strict');
const newDependency = require('./new-dependency.js');
const { Fake } = require('./testing.js');

const manifest = (dependencies) =>
`[workspace]\nmembers = ["crates/*"]\n\n[workspace.dependencies]\n${dependencies}\n\n[profile.release]\nlto = true\n`;

const findings = async (base, head, body = '') => {
const changed = Object.keys(head).map((filename) => ({ filename, status: 'modified' }));
return newDependency.findings(await Fake.pr({ body }, { files: { base, head }, changed }));
};

test('a new workspace dependency fails at its line, in either form', async () => {
const before = manifest('serde = "1"');
const after = manifest('serde = "1"\ntoml = { version = "1", features = [\n "parse",\n] }') + '[workspace.dependencies.syn]\nversion = "2"\n';
const result = await findings({ 'Cargo.toml': before }, { 'Cargo.toml': after });
assert.deepEqual(
result.map(({ path, line }) => `${path}:${line}`),
['Cargo.toml:6', 'Cargo.toml:13'],
);
assert.match(result[0].message, /^this adds the workspace dependency `toml`: add a `## Dependencies` section/);
});

test('changing an existing dependency, or anything else, passes', async () => {
const before = manifest('serde = "1"\nfoo.version = "1"');
const after = manifest('serde = { version = "1.1", features = ["derive"] }\nfoo.version = "2"') + '[lints]\nx = 1\n';
assert.deepEqual(await findings({ 'Cargo.toml': before }, { 'Cargo.toml': after }), []);
});

test('a new workspace manifest counts every dependency as added', async () => {
assert.equal((await findings({}, { 'Cargo.toml': manifest('a = "1"\nb = "1"') })).length, 2);
});

test('a new deny.toml exception fails, in an array or an array of tables', async () => {
const before = '[advisories]\nignore = []\n[licenses]\nallow = ["MIT"]\n';
const after =
'[advisories]\nignore = [\n "RUSTSEC-2024-0001", # why\n]\n[licenses]\nallow = ["MIT"]\n' +
'[[licenses.exceptions]]\ncrate = "ring"\nallow = ["OpenSSL"]\n[bans]\nskip = [{ crate = "a@1", reason = "b" }]\n';
const result = await findings({ 'deny.toml': before }, { 'deny.toml': after });
assert.deepEqual(
result.map(({ message }) => message.split(':')[0]),
[
'this adds `"RUSTSEC-2024-0001"` to `advisories.ignore`',
'this adds `{ crate = "a@1", reason = "b" }` to `bans.skip`',
'this adds `{ allow = ["OpenSSL"], crate = "ring" }` to `licenses.exceptions`',
],
);
});

test('a Dependencies section in the description justifies them', async () => {
const body = '## What and why\nx\n\n## Dependencies\n\n`toml` parses the manifests; `basic-toml` lacks spans.';
const head = { 'Cargo.toml': manifest('toml = "1"') };
assert.deepEqual(await findings({ 'Cargo.toml': manifest('') }, head, body), []);
assert.equal((await findings({ 'Cargo.toml': manifest('') }, head, '## Dependencies\n<!-- why -->')).length, 1);
});

test('an unchanged manifest is not read', async () => {
const pr = await Fake.pr({}, { files: { head: { 'Cargo.toml': manifest('a = "1"') } }, changed: [] });
assert.deepEqual(await newDependency.findings(pr), []);
});
1 change: 1 addition & 0 deletions .github/pr-checks/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class Runner {
require('./pr-body.js'),
require('./no-co-authors.js'),
require('./fix-has-test.js'),
require('./new-dependency.js'),
];

/** Runs the check named in `CHECK` with the inputs in `INPUTS`. Each
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pr-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jobs:
strategy:
fail-fast: false
matrix:
check: [pr-title, pr-body, no-co-authors, fix-has-test]
check: [pr-title, pr-body, no-co-authors, fix-has-test, new-dependency]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
Expand Down
4 changes: 4 additions & 0 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ check:
test (a `tests.rs`, a `tests/` directory, an added `#[test]`, or another
language's test file), or carries the `visual` label and images in its
description.
- `new-dependency`: a pull request that adds an entry to
`[workspace.dependencies]`, or an exception to `deny.toml` (an ignored
advisory, an allowed license, a skipped duplicate, an allowed source),
has a `## Dependencies` section in its description saying why.

A repository calls it from `.github/workflows/pr.yml`, pinned to a commit of
this repository's `main`. Reviews and labels re-run it, as some checks
Expand Down