11cb0ef41Sopenharmony_ci#!/usr/bin/env node
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ci// Usage:
41cb0ef41Sopenharmony_ci// git diff upstream/main...HEAD -G"pr-url:" -- "*.md" | \
51cb0ef41Sopenharmony_ci// ./tools/lint-pr-url.mjs <expected-pr-url>
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciimport process from 'node:process';
81cb0ef41Sopenharmony_ciimport readline from 'node:readline';
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ciconst [, , expectedPrUrl] = process.argv;
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ciconst fileDelimiter = /^\+\+\+ b\/(.+\.md)$/;
131cb0ef41Sopenharmony_ciconst changeDelimiter = /^@@ -\d+,\d+ \+(\d+),\d+ @@/;
141cb0ef41Sopenharmony_ciconst prUrlDefinition = /^\+\s+pr-url: (.+)$/;
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_ciconst validatePrUrl = (url) => url == null || url === expectedPrUrl;
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_cilet currentFile;
191cb0ef41Sopenharmony_cilet currentLine;
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_ciconst diff = readline.createInterface({ input: process.stdin });
221cb0ef41Sopenharmony_cifor await (const line of diff) {
231cb0ef41Sopenharmony_ci  if (fileDelimiter.test(line)) {
241cb0ef41Sopenharmony_ci    currentFile = line.match(fileDelimiter)[1];
251cb0ef41Sopenharmony_ci    console.log(`Parsing changes in ${currentFile}.`);
261cb0ef41Sopenharmony_ci  } else if (changeDelimiter.test(line)) {
271cb0ef41Sopenharmony_ci    currentLine = Number(line.match(changeDelimiter)[1]);
281cb0ef41Sopenharmony_ci  } else if (!validatePrUrl(line.match(prUrlDefinition)?.[1])) {
291cb0ef41Sopenharmony_ci    console.warn(
301cb0ef41Sopenharmony_ci      `::warning file=${currentFile},line=${currentLine++},col=${line.length}` +
311cb0ef41Sopenharmony_ci      '::pr-url doesn\'t match the URL of the current PR.',
321cb0ef41Sopenharmony_ci    );
331cb0ef41Sopenharmony_ci  } else if (line[0] !== '-') {
341cb0ef41Sopenharmony_ci    // Increment line counter if line is not being deleted.
351cb0ef41Sopenharmony_ci    currentLine++;
361cb0ef41Sopenharmony_ci  }
371cb0ef41Sopenharmony_ci}
38