|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * Upstream drift detector — Phase 1 (log-only). |
| 5 | + * |
| 6 | + * Reads `upstream/.upstream-sync.json`, asks the GitHub API how many |
| 7 | + * commits the upstream repo is ahead of the recorded baseline, and logs |
| 8 | + * the result. Does NOT create or update GitHub issues yet — that lands |
| 9 | + * in Phase 2. |
| 10 | + * |
| 11 | + * Designed to run in `.github/workflows/upstream-drift.yml`: |
| 12 | + * - Uses `gh api` via execFileSync (argv array — no shell parsing). |
| 13 | + * - Exits 0 on success and on tolerated upstream errors (the repo |
| 14 | + * itself was renamed/archived/deleted) so weekly cron does not |
| 15 | + * produce red runs nobody triages. |
| 16 | + * - Exits non-zero on programmer/config errors: a malformed state |
| 17 | + * file, or a baseline SHA that doesn't exist in an otherwise |
| 18 | + * reachable upstream repo (almost always a typo). |
| 19 | + */ |
| 20 | + |
| 21 | +const fs = require('fs'); |
| 22 | +const path = require('path'); |
| 23 | +const { execFileSync } = require('child_process'); |
| 24 | + |
| 25 | +const lib = require('../lib/upstream-drift'); |
| 26 | + |
| 27 | +const REPO_ROOT = path.join(__dirname, '..', '..'); |
| 28 | +const STATE_PATH = path.join(REPO_ROOT, 'upstream', '.upstream-sync.json'); |
| 29 | + |
| 30 | +function log(message) { |
| 31 | + console.log(`[upstream-drift] ${message}`); |
| 32 | +} |
| 33 | + |
| 34 | +function warn(message) { |
| 35 | + console.error(`[upstream-drift] ${message}`); |
| 36 | +} |
| 37 | + |
| 38 | +function readState() { |
| 39 | + let raw; |
| 40 | + try { |
| 41 | + raw = fs.readFileSync(STATE_PATH, 'utf8'); |
| 42 | + } catch (err) { |
| 43 | + throw new Error(`Could not read state file at ${STATE_PATH}: ${err.message}`, { cause: err }); |
| 44 | + } |
| 45 | + return lib.parseUpstreamState(raw); |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Invoke `gh api` for the given endpoint and return the parsed JSON. |
| 50 | + * Uses execFileSync with an argv array so the endpoint never reaches |
| 51 | + * a shell — defense-in-depth against future inputs that might bypass |
| 52 | + * the JSON-schema validation upstream. |
| 53 | + * |
| 54 | + * 404s are surfaced as a typed error (`err.is404 === true`) so callers |
| 55 | + * can distinguish tolerable cases (upstream repo gone) from hard |
| 56 | + * failures (invalid baseline SHA against a repo that does exist). |
| 57 | + * |
| 58 | + * @param {string} endpoint - path like "repos/owner/repo/compare/A...B" |
| 59 | + * @returns {object} |
| 60 | + */ |
| 61 | +function ghApi(endpoint) { |
| 62 | + let stdout; |
| 63 | + try { |
| 64 | + stdout = execFileSync('gh', ['api', endpoint], { |
| 65 | + encoding: 'utf8', |
| 66 | + stdio: ['ignore', 'pipe', 'pipe'], |
| 67 | + // The compare endpoint can return well over 1 MB of JSON when |
| 68 | + // the delta includes hundreds of commits. Default maxBuffer is |
| 69 | + // 1 MB and the process is killed with SIGTERM on overflow. |
| 70 | + maxBuffer: 50 * 1024 * 1024, |
| 71 | + }); |
| 72 | + } catch (err) { |
| 73 | + const stderr = (err.stderr || '').toString(); |
| 74 | + const is404 = stderr.includes('HTTP 404') || stderr.includes('Not Found'); |
| 75 | + const apiError = new Error(`gh api failed for "${endpoint}": ${stderr || err.message}`, { cause: err }); |
| 76 | + apiError.stderr = stderr; |
| 77 | + apiError.is404 = is404; |
| 78 | + throw apiError; |
| 79 | + } |
| 80 | + try { |
| 81 | + return JSON.parse(stdout); |
| 82 | + } catch (err) { |
| 83 | + throw new Error(`gh api returned non-JSON for "${endpoint}": ${err.message}`, { cause: err }); |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +/** |
| 88 | + * Pre-flight: check whether the upstream repo itself is reachable. A |
| 89 | + * 404 here genuinely means "rename / archive / deletion" — a tolerable |
| 90 | + * config drift the workflow should warn about, not fail on. A 404 on |
| 91 | + * the *compare* endpoint after this check passes is a hard error |
| 92 | + * (almost certainly a malformed `lastSyncedSha`). |
| 93 | + * |
| 94 | + * @param {string} repo - "owner/repo" |
| 95 | + * @returns {boolean} true if reachable; false if the repo returns 404 |
| 96 | + */ |
| 97 | +function isUpstreamReachable(repo) { |
| 98 | + try { |
| 99 | + ghApi(`repos/${repo}`); |
| 100 | + return true; |
| 101 | + } catch (err) { |
| 102 | + if (err.is404) { |
| 103 | + warn(`Upstream repo "${repo}" returned 404. Treating as tolerated upstream-unreachable (rename, archive, or deletion).`); |
| 104 | + return false; |
| 105 | + } |
| 106 | + throw err; |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +function summarize(state, compare) { |
| 111 | + const status = compare.status; |
| 112 | + const ahead = compare.ahead_by; |
| 113 | + const behind = compare.behind_by; |
| 114 | + const headSha = compare.commits && compare.commits.length > 0 |
| 115 | + ? compare.commits[compare.commits.length - 1].sha |
| 116 | + : state.lastSyncedSha; |
| 117 | + |
| 118 | + log(`Status: ${status} (ahead_by=${ahead}, behind_by=${behind})`); |
| 119 | + log(`Baseline: ${lib.shortSha(state.lastSyncedSha)} (recorded ${state.lastSyncedAt})`); |
| 120 | + log(`Upstream HEAD: ${lib.shortSha(headSha)}`); |
| 121 | + log(`Compare: ${lib.compareUrl(state.upstream, state.lastSyncedSha, headSha)}`); |
| 122 | + |
| 123 | + if (status === 'identical' || ahead === 0) { |
| 124 | + log('No drift — baseline matches upstream HEAD.'); |
| 125 | + return; |
| 126 | + } |
| 127 | + |
| 128 | + if (status === 'ahead' || status === 'diverged') { |
| 129 | + log(`Drift detected: upstream is ${ahead} commit(s) ahead.`); |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + if (status === 'behind') { |
| 134 | + log('Baseline is ahead of upstream HEAD — likely a manual cherry-pick or upstream reset.'); |
| 135 | + return; |
| 136 | + } |
| 137 | + |
| 138 | + log(`Unknown compare status "${status}" — surfacing as drift for review.`); |
| 139 | +} |
| 140 | + |
| 141 | +function main() { |
| 142 | + let state; |
| 143 | + try { |
| 144 | + state = readState(); |
| 145 | + } catch (err) { |
| 146 | + console.error(err.message); |
| 147 | + process.exit(1); |
| 148 | + } |
| 149 | + |
| 150 | + log(`Upstream: ${state.upstream}`); |
| 151 | + |
| 152 | + // Pre-flight: if the repo itself is 404, treat it as tolerable |
| 153 | + // (rename/archive/deletion) and exit 0. Phase 2 will optionally post |
| 154 | + // a comment on the existing tracking issue in this branch. |
| 155 | + if (!isUpstreamReachable(state.upstream)) { |
| 156 | + process.exit(0); |
| 157 | + } |
| 158 | + |
| 159 | + // Repo exists. A 404 on the compare endpoint now means the recorded |
| 160 | + // baseline SHA is not reachable in the upstream repo — almost always |
| 161 | + // a typo in upstream/.upstream-sync.json. Fail loudly so the |
| 162 | + // operator notices. |
| 163 | + const endpoint = `repos/${state.upstream}/compare/${state.lastSyncedSha}...HEAD`; |
| 164 | + let compare; |
| 165 | + try { |
| 166 | + compare = ghApi(endpoint); |
| 167 | + } catch (err) { |
| 168 | + if (err.is404) { |
| 169 | + console.error( |
| 170 | + `Baseline SHA "${state.lastSyncedSha}" is not reachable in ${state.upstream}. ` + |
| 171 | + `Check upstream/.upstream-sync.json — the SHA may be malformed or refer to a commit ` + |
| 172 | + `that was force-removed from the upstream history.`, |
| 173 | + ); |
| 174 | + process.exit(1); |
| 175 | + } |
| 176 | + console.error(err.message); |
| 177 | + process.exit(1); |
| 178 | + } |
| 179 | + |
| 180 | + summarize(state, compare); |
| 181 | +} |
| 182 | + |
| 183 | +if (require.main === module) { |
| 184 | + main(); |
| 185 | +} |
| 186 | + |
| 187 | +module.exports = { readState, ghApi, isUpstreamReachable, summarize }; |
0 commit comments