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
2 changes: 1 addition & 1 deletion .agents/rules/github_authoring_and_prs.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ Whenever creating, modifying, or reviewing GitHub Actions workflow files under `
```yaml
on:
# zizmor: ignore[pull-request-target]
# Required to grant PR write permissions for auto-approving ABSENCE.md updates on fork PRs.
# Required to grant PR write permissions on fork PRs.
pull_request_target:
```

Expand Down
4 changes: 3 additions & 1 deletion .github/scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ graph TD
| [`git-range-diff.js`](git-range-diff.js) | **Git Subprocess Mechanics**: Proactively fetches missing Git refs (`ensureGitRefs`), detects fast-forward ancestry, computes line deltas, indexes candidate commits using `git patch-id` and commit subjects, and resolves commit ranges for stacked PRs. |
| [`range-diff-parser.js`](range-diff-parser.js) | **Diff Parser**: Parses raw `git range-diff` output. Distinguishes code hunks from commit metadata/commit message hunks, computes added/deleted line deltas (tracking the test file subset), and extracts added commit SHAs. |
| [`test-file-classifier.js`](test-file-classifier.js) | **Test File Classifier**: Identifies test files and fixtures whose line changes are excluded from the code owner grace budget. |
| [`approval-policy.js`](approval-policy.js) | **Decision Engine**: Evaluates whether a PR qualify for auto-reapproval (clean rebase vs code owner grace delta). Enforces protected file boundaries, handles absence PR auto-approvals, and manages reviewer assignment logic. |
| [`approval-policy.js`](approval-policy.js) | **Decision Engine**: Evaluates whether a PR qualifies for auto-reapproval (clean rebase vs code owner grace delta) and enforces protected file boundaries. |
| [`assign-reviewers.js`](assign-reviewers.js) | **Reviewer Assignment**: Parses `OWNERS`, filters out absent reviewers configured in the `ABSENCE_LIST` repository variable (`vars.ABSENCE_LIST` — **Settings → Secrets and variables → Actions → Variables** or `gh variable set ABSENCE_LIST`, requiring repository `write` / Actions Variables write access), and assigns eligible reviewers to open pull requests. |
| [`absence-schedule.js`](absence-schedule.js) | **Absence Schedule Parser**: Parses unconditional (`NICK`) and inclusive UTC date-ranged (`NICK DD.MM.YYYY-DD.MM.YYYY`) reviewer absence entries from `ABSENCE_LIST` (entries separated by newlines, `,`, or `;`; `#` starts an end-of-line comment; optional leading `-`/`*`/`+`/`@` prefixes). Consumed by `assign-reviewers.js` and `nightly-failure-alert.js`; malformed entries emit a non-blocking `core.warning` and are ignored (user treated as available). |

---

Expand Down
52 changes: 22 additions & 30 deletions .github/scripts/absence-schedule.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ function parseAbsenceDateRange(rangeStr, lineNumber) {
}

/**
* Pure function: Parses and validates a single line from ABSENCE.md.
* Pure function: Parses and validates a single line or entry from ABSENCE_LIST.
* Supports either bare "NICK" or "NICK DD.MM.YYYY-DD.MM.YYYY" (inclusive).
* @param {string} rawLine - Raw line from ABSENCE.md.
* @param {string} rawLine - Raw line from ABSENCE_LIST.
* @param {number} [lineNumber=1] - 1-based line number for error reporting.
* @returns {{ empty: boolean, valid: boolean, username?: string, startDate?: Date|null, endDate?: Date|null, reason?: string }}
*/
Expand All @@ -114,10 +114,11 @@ function parseAbsenceLine(rawLine, lineNumber = 1) {
}

/**
* Pure function: Parses ABSENCE.md content and evaluates scheduled absences against `currentDate` (UTC).
* Pure function: Parses ABSENCE_LIST content and evaluates scheduled absences against `currentDate` (UTC).
* Bare "NICK" entries are unconditionally absent; "NICK X-Y" entries are absent when the UTC calendar
* day of `currentDate` falls within `[X, Y]` inclusive. Malformed lines are reported in `errors`.
* @param {string} content - Raw string content of ABSENCE.md.
* day of `currentDate` falls within `[X, Y]` inclusive. Supports newline, comma, or semicolon delimiters.
* Malformed entries are reported in `errors`.
* @param {string} content - Raw string content of ABSENCE_LIST.
* @param {Date} [currentDate=new Date()] - Date to evaluate scheduled absences against.
* @returns {{ absentUsers: string[], errors: string[] }} Currently absent usernames and line validation errors.
*/
Expand All @@ -133,41 +134,32 @@ function parseAbsenceFile(content, currentDate = new Date()) {
const errors = [];
const lines = (content || '').split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const entry = parseAbsenceLine(lines[i], i + 1);
if (entry.empty) {
const uncommented = (lines[i] || '').split('#')[0].trim();
if (!uncommented) {
continue;
}
if (!entry.valid) {
errors.push(entry.reason);
continue;
}
if (!entry.startDate || (today >= entry.startDate && today <= entry.endDate)) {
absentUsers.push(entry.username);
const segments = uncommented.split(/[,;]/);
for (const segment of segments) {
const entry = parseAbsenceLine(segment, i + 1);
if (entry.empty) {
continue;
}
if (!entry.valid) {
errors.push(entry.reason);
continue;
}
if (!entry.startDate || (today >= entry.startDate && today <= entry.endDate)) {
absentUsers.push(entry.username);
}
}
}
return { absentUsers, errors };
}

/**
* Pure function: Validates the contents of ABSENCE.md, checking that every non-empty
* non-comment line is either "NICK" or "NICK DD.MM.YYYY-DD.MM.YYYY" with valid
* calendar dates and start <= end.
* @param {string} content - Raw ABSENCE.md content.
* @returns {{ valid: boolean, reason?: string }}
*/
function validateAbsenceContent(content) {
if (typeof content !== 'string') {
return { valid: false, reason: 'ABSENCE.md content is missing or not a string' };
}
const { errors } = parseAbsenceFile(content);
return errors.length > 0 ? { valid: false, reason: errors[0] } : { valid: true };
}

module.exports = {
USERNAME_PATTERN,
parseDdMmYyyy,
parseAbsenceDateRange,
parseAbsenceLine,
parseAbsenceFile,
validateAbsenceContent
parseAbsenceFile
};
61 changes: 52 additions & 9 deletions .github/scripts/absence-schedule.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ const assert = require('node:assert/strict');
const {
parseDdMmYyyy,
parseAbsenceLine,
parseAbsenceFile,
validateAbsenceContent
parseAbsenceFile
} = require('./absence-schedule');

test('parseDdMmYyyy validates strict DD.MM.YYYY calendar dates in UTC', () => {
Expand Down Expand Up @@ -100,11 +99,55 @@ extraTokensUser 10.11.2026-15.11.2026 extra
assert.equal(parseAbsenceLine('invertedUser 15.11.2026-10.11.2026', 2).valid, false);
});

test('validateAbsenceContent validates content and rejects non-string input', () => {
assert.deepEqual(validateAbsenceContent('alice\nbob 10.11.2026-15.11.2026\n'), {
valid: true
});
const nonStringResult = validateAbsenceContent(null);
assert.equal(nonStringResult.valid, false);
assert.ok(nonStringResult.reason.includes('not a string'));
test('parseAbsenceFile handles null/empty content and reports all invalid date and format errors', () => {
assert.deepEqual(parseAbsenceFile(null), { absentUsers: [], errors: [] });
assert.deepEqual(parseAbsenceFile(''), { absentUsers: [], errors: [] });

const invalidCases = [
{
content: 'alice 16.11.2026-15.11.2026\n',
expectedSubstring: 'after end date'
},
{
content: 'alice 31.02.2026-15.03.2026\n',
expectedSubstring: 'invalid start date'
},
{
content: 'alice 10.11.2026-29.02.2027\n',
expectedSubstring: 'invalid end date'
},
{
content: 'alice 2026-11-10-2026-11-15\n',
expectedSubstring: 'invalid date range format'
},
{
content: 'alice 10.11.2026-15.11.2026 extra\n',
expectedSubstring: 'invalid format'
},
{
content: '10.11.2026-15.11.2026\n',
expectedSubstring: 'invalid username'
}
];

for (const { content, expectedSubstring } of invalidCases) {
const { absentUsers, errors } = parseAbsenceFile(content);
assert.deepEqual(absentUsers, []);
assert.equal(errors.length, 1, `Expected 1 error for: ${content}`);
assert.ok(
errors[0].includes(expectedSubstring),
`Expected "${errors[0]}" to include "${expectedSubstring}"`
);
}
});

test('parseAbsenceFile supports comma/semicolon delimiters and comments with commas', () => {
const envContent = `
# - NICK DD.MM.YYYY-DD.MM.YYYY (absent during the inclusive UTC date range, e.g., alice 10.11.2026-15.11.2026)
alice, bob; charlie 16.11.2026-18.11.2026
`;
assert.deepEqual(
parseAbsenceFile(envContent, new Date('2026-11-16T12:00:00Z')),
{ absentUsers: ['alice', 'bob', 'charlie'], errors: [] }
);
});
26 changes: 22 additions & 4 deletions .github/scripts/assign-reviewers.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,16 @@ async function run({ github, context, core }) {
}

let absentUsers = [];
if (fs.existsSync('ABSENCE.md')) {
const parsedAbsence = parseAbsenceFile(fs.readFileSync('ABSENCE.md', 'utf8'));
const rawAbsenceList = process.env.ABSENCE_LIST || '';
Comment thread
VLukiantsev marked this conversation as resolved.
Resolved
if (rawAbsenceList.trim()) {
const parsedAbsence = parseAbsenceFile(rawAbsenceList);
absentUsers = parsedAbsence.absentUsers;
for (const err of parsedAbsence.errors) {
core.warning(`Invalid ABSENCE.md entry ignored: ${err}`);
core.warning(`Invalid ABSENCE_LIST entry ignored: ${err}`);
}
core.info(`Parsed absent reviewers from ABSENCE.md: ${absentUsers.join(', ')}`);
core.info(`Parsed absent reviewers from ABSENCE_LIST: ${absentUsers.join(', ')}`);
} else {
core.info('ABSENCE_LIST is unset or empty; no reviewers marked absent.');
}

const candidates = filterEligibleReviewers(rawReviewers, prAuthor, absentUsers);
Expand Down Expand Up @@ -188,9 +191,24 @@ async function getPullRequestMetadata(github, context, core) {
};
}

/**
* Pure function: Checks if the PR author is listed in the code owners array (case-insensitively).
* @param {string} prAuthor - Username of the PR author.
* @param {string[]} ownersList - Array of code owner usernames.
* @returns {boolean} True if author is in code owners list.
*/
function isAuthorCodeOwner(prAuthor, ownersList) {
if (!prAuthor || !Array.isArray(ownersList)) {
return false;
}
const authorLower = prAuthor.toLowerCase();
return ownersList.some(owner => (owner || '').toLowerCase() === authorLower);
}

module.exports = {
NUM_REVIEWERS_TO_ASSIGN,
parseReviewersFromOwners,
isAuthorCodeOwner,
filterEligibleReviewers,
selectRandomReviewers,
isPullRequestOpen,
Expand Down
55 changes: 50 additions & 5 deletions .github/scripts/assign-reviewers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,23 @@ const path = require('path');
const { parseAbsenceFile } = require('./absence-schedule');
const {
parseReviewersFromOwners,
isAuthorCodeOwner,
filterEligibleReviewers,
selectRandomReviewers,
isPullRequestOpen,
shouldSkipAssignment,
run
} = require('./assign-reviewers');

test('isAuthorCodeOwner checks code owners list case-insensitively', () => {
const owners = ['alice', 'bob', 'charlie'];
assert.strictEqual(isAuthorCodeOwner('alice', owners), true);
assert.strictEqual(isAuthorCodeOwner('ALICE', owners), true);
assert.strictEqual(isAuthorCodeOwner('dave', owners), false);
assert.strictEqual(isAuthorCodeOwner('', owners), false);
assert.strictEqual(isAuthorCodeOwner('alice', null), false);
});

test('parseReviewersFromOwners parses flat text reviewers correctly and strips comments', () => {
const sampleOwners = `
# Sample OWNERS file with one username per line
Expand Down Expand Up @@ -83,19 +93,17 @@ test('absent reviewers mapping handles markdown formatted lists (- , * , @)', ()
assert.deepStrictEqual(result, ['charlie']);
});

test('run skips absent reviewers and logs warnings for malformed ABSENCE.md entries', async () => {
test('run skips absent reviewers and logs warnings for malformed ABSENCE_LIST entries', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xmc-assign-reviewers-'));
const origCwd = process.cwd();
const origAbsenceList = process.env.ABSENCE_LIST;
const warnings = [];
let requestedReviewers = null;

try {
process.chdir(tempDir);
fs.writeFileSync('OWNERS', 'alice\nbob\ncharlie\n');
fs.writeFileSync(
'ABSENCE.md',
'bob\ncharlie 16.11.2026-15.11.2026\n'
);
process.env.ABSENCE_LIST = 'bob\ncharlie 16.11.2026-15.11.2026\n';

await run({
github: {
Expand Down Expand Up @@ -131,7 +139,44 @@ test('run skips absent reviewers and logs warnings for malformed ABSENCE.md entr
assert.deepStrictEqual(requestedReviewers, ['charlie']);
assert.strictEqual(warnings.length, 1);
assert.ok(warnings[0].includes('after end date'));

// When ABSENCE_LIST is unset or empty, logs info and treats all non-author owners as eligible
delete process.env.ABSENCE_LIST;
const infoLogs = [];
await run({
github: {
rest: {
pulls: {
requestReviewers: async () => {}
}
}
},
context: {
repo: { owner: 'google', repo: 'xmc' },
eventName: 'pull_request',
payload: {
pull_request: {
number: 1,
state: 'open',
user: { login: 'alice' },
requested_reviewers: [],
requested_teams: []
}
}
},
core: {
info: msg => infoLogs.push(msg),
warning: () => {},
setFailed: msg => assert.fail(`Unexpected setFailed: ${msg}`)
}
});
assert.ok(infoLogs.includes('ABSENCE_LIST is unset or empty; no reviewers marked absent.'));
} finally {
if (origAbsenceList === undefined) {
delete process.env.ABSENCE_LIST;
} else {
process.env.ABSENCE_LIST = origAbsenceList;
}
process.chdir(origCwd);
fs.rmSync(tempDir, { recursive: true, force: true });
}
Expand Down
Loading
Loading