-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidators.js
More file actions
775 lines (671 loc) · 27.4 KB
/
Copy pathvalidators.js
File metadata and controls
775 lines (671 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
export function isValidName(name) {
const nameRegex = /^[\p{L}'.-]+(?: [\p{L}'.-]+)+$/u;
return nameRegex.test(name);
}
export function isNoreplyEmail(email) {
const parts = email.split('@');
if (parts.length !== 2) return false;
const domain = parts[1].toLowerCase();
return domain === 'noreply.github.com' || domain === 'users.noreply.github.com';
}
export function getNormalizedText(str, pkgName) {
let cleaned = str.toLowerCase();
if (pkgName) {
cleaned = cleaned.replaceAll(pkgName.toLowerCase(), '');
}
// Remove common list bullet markers and generic words
cleaned = cleaned.replace(/^[\s\-*+•#]+/, '');
// Remove leading 'v' before a digit (e.g., v1.2 -> 1.2, but keep words like version)
cleaned = cleaned.replace(/\bv(?=\d)/g, '');
// Remove all non-alphanumeric characters
return cleaned.replace(/[^a-z0-9]/g, '');
}
async function getSshKeyFingerprint(sigText) {
try {
let cleanSig = sigText.replace(/-----[a-zA-Z0-9\s]+-----/g, '');
cleanSig = cleanSig.replace(/[^a-zA-Z0-9+\/=]/g, '');
const binaryString = atob(cleanSig);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
if (bytes[0] !== 0x53 || bytes[1] !== 0x53 || bytes[2] !== 0x48 ||
bytes[3] !== 0x53 || bytes[4] !== 0x49 || bytes[5] !== 0x47) {
return null;
}
const pubKeyLen = (bytes[10] << 24) | (bytes[11] << 16) | (bytes[12] << 8) | bytes[13];
if (pubKeyLen <= 0 || pubKeyLen + 14 > bytes.length) {
return null;
}
const pubKeyBlob = bytes.slice(14, 14 + pubKeyLen);
const hashBuffer = await crypto.subtle.digest("SHA-256", pubKeyBlob);
const hashBytes = new Uint8Array(hashBuffer);
let binaryHash = '';
for (let i = 0; i < hashBytes.length; i++) {
binaryHash += String.fromCharCode(hashBytes[i]);
}
return btoa(binaryHash).replace(/=+$/, '');
} catch (e) {
return null;
}
}
// --- ENGINE CHECKS ---
export async function validateFormalities(fullCommit, CONFIG) {
const errors = [];
const successes = [];
const warnings = [];
const commit = fullCommit.commit;
const message = commit.message || '';
const authorName = commit.author?.name || '';
const authorEmail = commit.author?.email || '';
const committerName = commit.committer?.name || '';
const committerEmail = commit.committer?.email || '';
if (!message.trim()) {
return { errors: ["- Commit message is completely empty"], successes: [], warnings: [] };
}
const lines = message.split("\n");
let subject = lines[0].trim();
// Identity Check
const identityErrors = [];
if (!isValidName(authorName)) identityErrors.push(`Author name format is invalid ('${authorName}')`);
if (!isValidName(committerName)) identityErrors.push(`Committer name format is invalid ('${committerName}')`);
if (CONFIG.check_noreply_email) {
if (isNoreplyEmail(authorEmail)) identityErrors.push("Author email must not be a GitHub noreply address");
if (isNoreplyEmail(committerEmail)) identityErrors.push("Committer email must not be a GitHub noreply address");
}
if (CONFIG.require_linked_github_account) {
if (!fullCommit.author || !fullCommit.author.login) {
identityErrors.push(`Commit author email '${authorEmail}' is not linked to any registered GitHub account. Please add and verify this email in your GitHub profile settings.`);
}
}
if (identityErrors.length === 0) {
successes.push("✅ Author and committer identities are valid");
} else {
identityErrors.forEach(err => errors.push("- " + err));
}
// Merge commits check
if (CONFIG.check_merge_commits) {
if ((fullCommit.parents || []).length > 1) {
errors.push("- Merge commits are not allowed within the pull request");
} else {
successes.push("✅ Commit is not a merge commit");
}
}
// Subject layout checks
const subjectErrors = [];
let isAutosquash = false;
if (CONFIG.allow_autosquash && /^(fixup!|squash!)\s+/.test(subject)) {
isAutosquash = true;
subject = subject.replace(/^(fixup!|squash!)\s+/, '');
}
if (!isAutosquash) {
if (/^\s/.test(lines[0])) subjectErrors.push("Commit subject must not start with whitespace");
if (!/^[a-zA-Z0-9_-]+: /.test(subject)) {
subjectErrors.push("Commit subject must start with \`<package name or prefix>: \`");
} else {
const afterPrefix = subject.replace(/^[a-zA-Z0-9_-]+: \s*/, '');
if (afterPrefix.length > 0 && afterPrefix[0] === afterPrefix[0].toUpperCase() && /[a-zA-Z]/.test(afterPrefix[0])) {
subjectErrors.push("Commit subject must start with a lower-case word after the prefix");
}
}
if (subject.endsWith('.')) {
subjectErrors.push("Commit subject must not end with a period");
}
}
const subjectLen = lines[0].length;
if (subjectLen > CONFIG.max_subject_len_hard) {
subjectErrors.push(`Subject line exceeds hard limit (${subjectLen}/${CONFIG.max_subject_len_hard} chars)`);
} else if (subjectLen > CONFIG.max_subject_len_soft) {
warnings.push(`Subject line exceeds soft limit (${subjectLen}/${CONFIG.max_subject_len_soft} chars)`);
}
if (subjectErrors.length === 0) {
successes.push(`✅ Commit subject layout and length are valid: "${lines[0]}"`);
} else {
subjectErrors.forEach(err => errors.push("- " + err));
}
// Description Quality Warnings
const bodyLines = lines.slice(1);
const cleanBodyLines = [];
bodyLines.forEach(line => {
const trimmed = line.trim();
if (trimmed === '' || /^(signed-off-by:|cherry picked from)/i.test(trimmed)) {
return;
}
cleanBodyLines.push(trimmed);
});
const fullCleanBody = cleanBodyLines.join(" ");
// Require meaningful commit body (not just trailers)
if (CONFIG.require_body && fullCleanBody.length === 0) {
errors.push("- Commit description body is empty or contains only trailers (e.g. Signed-off-by). Please provide a meaningful description of what this change does and why");
}
// Generic phrase checking
if (CONFIG.warn_generic_subjects) {
const genericPatterns = [
/update to latest version/i, /bump to latest/i,
/minor update/i, /fix bugs/i
];
for (const pattern of genericPatterns) {
if (pattern.test(lines[0])) {
warnings.push(`Subject uses generic phrase matching '${pattern.source}'. Please specify explicitly what changed.`);
break;
}
}
}
if (fullCleanBody.length > 0) {
if (CONFIG.warn_duplicate_body) {
const pkgPrefixMatch = lines[0].match(/^([a-zA-Z0-9_-]+):/);
const pkgName = pkgPrefixMatch ? pkgPrefixMatch[1] : '';
const normSubject = getNormalizedText(lines[0], pkgName);
const normBody = getNormalizedText(fullCleanBody, pkgName);
if (normSubject === normBody || (normBody.includes(normSubject) && normBody.length < normSubject.length + 20) || (normSubject.includes(normBody) && normSubject.length < normBody.length + 20)) {
warnings.push("Commit subject and description body are identical or virtually identical. Avoid repeating the subject line in the body; provide context instead.");
}
}
if (CONFIG.require_release_notes && !/https?:\/\/[^\s]+/i.test(fullCleanBody)) {
warnings.push("No reference link (e.g., upstream release notes, changelog, or history URL) detected in description.");
}
}
// Body lines width check
const bodyErrors = [];
let inCodeBlock = false;
lines.forEach((line, index) => {
if (index === 0) return;
const trimmed = line.trim();
if (trimmed.startsWith('```')) {
inCodeBlock = !inCodeBlock;
return;
}
if (inCodeBlock) {
return;
}
if (/[a-zA-Z]+:\/\/\S+/.test(line)) {
return;
}
if (line.length > CONFIG.max_body_line_len) {
bodyErrors.push(`Line ${index + 1} in commit body exceeds max width (${line.length}/${CONFIG.max_body_line_len} chars)`);
}
});
if (bodyErrors.length === 0) {
successes.push("✅ Commit description lines adhere to width formatting rules");
} else {
bodyErrors.forEach(err => errors.push("- " + err));
}
// Signed-off-by check
if (CONFIG.check_signoff) {
const signoffPattern = /Signed-off-by:\s*([^<]+)\s*<([^>]+)>/i;
let hasSignoff = false;
const signoffErrors = [];
lines.forEach(line => {
const matches = line.match(signoffPattern);
if (matches) {
hasSignoff = true;
const sobName = matches[1].trim();
const sobEmail = matches[2].trim();
if (sobName.toLowerCase() !== authorName.toLowerCase() || sobEmail.toLowerCase() !== authorEmail.toLowerCase()) {
signoffErrors.push(`Signed-off-by value (\`${sobName} <${sobEmail}>\`) does not match commit author (\`${authorName} <${authorEmail}>\`)`);
}
if (isNoreplyEmail(sobEmail)) {
signoffErrors.push("Signed-off-by email must not be a GitHub noreply address");
}
}
});
if (!hasSignoff) {
errors.push("- Missing 'Signed-off-by:' line");
} else if (signoffErrors.length > 0) {
signoffErrors.forEach(err => errors.push("- " + err));
} else {
successes.push("✅ Commit contains a consistent and valid 'Signed-off-by:' line");
}
}
// Signature check
if (CONFIG.check_signature) {
const verification = fullCommit.commit.verification || {};
if (verification.verified === true) {
let keyDetails = "";
const reason = verification.reason || '';
const sigText = verification.signature || '';
if (verification.key_id) {
keyDetails = ` (GPG Key ID: ${verification.key_id})`;
} else if (sigText.includes('SSH SIGNATURE')) {
const fingerprint = await getSshKeyFingerprint(sigText);
if (fingerprint) {
keyDetails = ` (SSH Key Fingerprint: SHA256:${fingerprint})`;
} else {
keyDetails = " (Verified via SSH)";
}
} else if (reason === 'valid' || reason === 'valid_signature') {
keyDetails = " (Verified via GitHub Profile)";
}
successes.push("✅ Excellent! Commit contains a valid cryptographic signature (GPG/SSH). Thank you for signing your work!" + keyDetails);
} else {
const reason = verification.reason || 'unsigned';
warnings.push(`Commit is unsigned or cryptographic signature verification failed (Reason: ${reason}). Signing commits is a recommended best practice for verifying identity, but is not mandatory.`);
}
}
return { errors, successes, warnings };
}
export function validateMakefileContext(fullCommit, commitPatch, CONFIG, state) {
const errors = [];
const successes = [];
const warnings = [];
const subject = (fullCommit.commit.message || '').split("\n")[0].trim();
if (!commitPatch) {
return { errors: [], successes: ["✅ No codebase text files changed to analyze"], warnings: [] };
}
let isNewPackageThisCommit = false;
if (/^---\s+\/dev\/null\r?\n\+\+\+\s+b\/(?:.*\/)?Makefile\r?$/m.test(commitPatch)) {
state.isNewPackage = true;
isNewPackageThisCommit = true;
}
if (/^---\s+a\/(?:.*\/)?Makefile\r?\n\+\+\+\s+\/dev\/null\r?$/m.test(commitPatch)) {
state.isDroppedPackage = true;
}
if (CONFIG.check_pkg_version && !state.isNewPackage) {
const versionMatch = commitPatch.match(/^\+\s*PKG_VERSION\s*(?::=|=)\s*(.+)$/m);
if (versionMatch) {
const newVersion = versionMatch[1].replace(/["']/g, "").trim();
const cleanSubject = subject.replace(/^(fixup!|squash!)\s+/, '');
if (!cleanSubject.includes(newVersion)) {
errors.push(`- Makefile introduces PKG_VERSION '${newVersion}', but this version string is missing in the commit subject line`);
} else {
successes.push(`✅ PKG_VERSION bump matches context information inside subject line (${newVersion})`);
}
}
}
if (CONFIG.check_openwrt_meta) {
let requiredMeta = ['PKG_MAINTAINER', 'PKG_LICENSE', 'PKG_LICENSE_FILES'];
if (Array.isArray(CONFIG.check_openwrt_meta)) {
requiredMeta = CONFIG.check_openwrt_meta;
}
if (isNewPackageThisCommit) {
requiredMeta.forEach(meta => {
const metaRegex = new RegExp(`^\\+\\s*${meta}\\s*(?::=|=)`, 'm');
if (!metaRegex.test(commitPatch)) {
errors.push(`- New OpenWrt package is missing the mandatory parameter: '${meta}'`);
} else {
successes.push(`✅ Mandatory structural metadata present: '${meta}'`);
}
});
}
const maintainerLines = commitPatch.split('\n').filter(line => line.startsWith('+') && line.includes('PKG_MAINTAINER'));
for (const line of maintainerLines) {
const match = line.match(/^\+\s*PKG_MAINTAINER\s*(?::=|=)\s*(.+)$/);
if (match) {
const value = match[1].trim();
const emails = (value.match(/<([^>]+)>/g) || []).map(m => m.slice(1, -1).trim());
if (emails.length === 0) {
errors.push(`- PKG_MAINTAINER format is invalid; it should contain an email address inside angle brackets '<>'`);
} else {
for (const email of emails) {
if (email.includes('://') || email.includes('http') || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push(`- PKG_MAINTAINER contains an invalid email address: '${email}'. In angle brackets '<>' must be a valid email address and not a website/URL.`);
} else {
successes.push(`✅ PKG_MAINTAINER email address format is valid: '${email}'`);
}
}
}
}
}
}
if (CONFIG.check_conffiles && /INSTALL_CONF/m.test(commitPatch)) {
if (!/define\s+Package\/[a-zA-Z0-9_.-]+\/conffiles/m.test(commitPatch)) {
errors.push("- Makefile triggers 'INSTALL_CONF', but is missing the required 'conffiles' tracking macro configuration block");
} else {
successes.push("✅ Makefile conffiles macro properly registers INSTALL_CONF tracking parameters");
}
}
if (CONFIG.check_conffiles) {
const fileDiffs = commitPatch.split(/^diff --git /m);
let conffilesCheckRun = false;
let conffilesCheckErrors = 0;
for (const fileDiff of fileDiffs) {
const fileMatch = fileDiff.match(/^\+\+\+\s+b\/(.*)$/m);
if (!fileMatch) continue;
const filePath = fileMatch[1].trim();
const isMakefile = filePath.endsWith('/Makefile') || filePath === 'Makefile';
if (!isMakefile) continue;
let inConffiles = false;
let currentPackage = '';
const lines = fileDiff.split('\n');
for (const line of lines) {
if (line.startsWith('+') || line.startsWith(' ')) {
const contentLine = line.slice(1);
const defineMatch = contentLine.match(/^define\s+(Package\/[^\s]*conffiles)/);
if (defineMatch) {
inConffiles = true;
currentPackage = defineMatch[1];
continue;
}
if (contentLine.match(/^endef/)) {
inConffiles = false;
currentPackage = '';
continue;
}
if (inConffiles && line.startsWith('+')) {
conffilesCheckRun = true;
if (/[ \t]/.test(contentLine)) {
conffilesCheckErrors++;
errors.push(`- ${currentPackage} line '${contentLine}' must not contain any spaces or indentation`);
}
}
}
}
}
if (conffilesCheckRun && conffilesCheckErrors === 0) {
successes.push("✅ Makefile conffiles block contains no spaces or indentation");
}
}
if (CONFIG.check_crlf) {
if (/^\+.*\r$/m.test(commitPatch)) {
errors.push("- Windows style line endings (CRLF) detected inside added source lines. Use UNIX (LF) formatting exclusively");
} else {
successes.push("✅ File additions contain clean UNIX (LF) line termination");
}
}
if (CONFIG.check_trailing_newline && CONFIG.check_trailing_newline !== 'disabled') {
let currentFile = null;
let prevLine = null;
const missingNewlineFiles = [];
const changedFiles = new Set();
const patchLines = commitPatch.split('\n');
for (const line of patchLines) {
if (line.startsWith('+++ b/')) {
currentFile = line.slice(6).trim().replace(/\r$/, '');
if (currentFile !== '/dev/null') {
changedFiles.add(currentFile);
}
} else if (line.startsWith('+++ /dev/null')) {
currentFile = null;
} else if (line.trim() === '\\ No newline at end of file') {
if (currentFile && prevLine && prevLine.startsWith('+')) {
missingNewlineFiles.push(currentFile);
}
}
prevLine = line;
}
if (missingNewlineFiles.length > 0) {
const isWarning = CONFIG.check_trailing_newline === 'warning';
missingNewlineFiles.forEach(file => {
const msg = `- File '${file}' is missing a trailing newline`;
if (isWarning) {
warnings.push(msg);
} else {
errors.push(msg);
}
});
} else if (changedFiles.size > 0) {
successes.push("✅ All modified files contain a trailing newline");
}
}
return { errors, successes, warnings };
}
export async function validateEmbeddedPatches(commitPatch, CONFIG, fetchFileContent) {
const errors = [];
const successes = [];
if (CONFIG.check_patch_headers === false || CONFIG.check_patch_headers === 'disabled') {
return { errors: [], successes: [] };
}
if (!commitPatch) {
return { errors: [], successes: ["✅ No diff footprint present for patches validation"] };
}
const patchMatch = commitPatch.match(/^\+\+\+\s+b\/(.*\.patch)/mg);
const patchFiles = patchMatch ? patchMatch.map(line => line.replace(/^\+\+\+\s+b\//, '')) : [];
if (patchFiles.length === 0) {
return { errors: [], successes: ["✅ No downstream raw embedded patch files modified or introduced"] };
}
const fileChunks = commitPatch.split(/^diff\s+--git\s+/m);
for (const chunk of fileChunks) {
for (const patchFile of patchFiles) {
if (chunk.includes('b/' + patchFile)) {
let hasFrom = false;
let hasSubject = false;
let checked = false;
if (fetchFileContent) {
try {
const rawContent = await fetchFileContent(patchFile);
if (rawContent !== null) {
hasFrom = /^From:\s+.+/m.test(rawContent);
hasSubject = /^Subject:\s+.+/m.test(rawContent);
checked = true;
}
} catch (e) {
// Ignore fetch errors and fallback
}
}
if (!checked) {
// Fallback: only validate if it is a new file
const isNewFile = /^(?:new file mode|--- \/dev\/null)/m.test(chunk);
if (!isNewFile) {
successes.push(`✅ Embedded patch '${patchFile}' is an existing patch modification, header validation skipped (unable to fetch full file)`);
continue;
}
hasFrom = /^\+\s*From:\s+.+/m.test(chunk);
hasSubject = /^\+\s*Subject:\s+.+/m.test(chunk);
}
if (!hasFrom || !hasSubject) {
errors.push(`- Embedded patch file '${patchFile}' violates standard guidelines. Missing required Git header parameters ('From:' / 'Subject:') to ensure 'git am' application compatibility`);
} else {
successes.push(`✅ Embedded patch '${patchFile}' contains valid Git compliance headers`);
}
}
}
}
return { errors, successes };
}
export function getChangedFilesFromPatch(patch) {
if (!patch) return [];
const files = [];
const lines = patch.split('\n');
for (const line of lines) {
if (line.startsWith('+++ b/')) {
files.push(line.slice(6).trim().replace(/\r$/, ''));
}
}
return files;
}
export function parseDiffFileStates(patch) {
const addedFiles = new Set();
const deletedFiles = new Set();
if (!patch) return { addedFiles, deletedFiles };
const lines = patch.split('\n');
let currentFile = null;
for (const line of lines) {
if (line.startsWith('diff --git ')) {
currentFile = null;
const match = line.match(/^diff --git a\/(.*?) b\/(.*)$/);
if (match) {
currentFile = match[2].trim().replace(/\r$/, '');
}
} else if (currentFile) {
if (line.startsWith('--- /dev/null')) {
addedFiles.add(currentFile);
} else if (line.startsWith('+++ /dev/null')) {
deletedFiles.add(currentFile);
}
}
}
return { addedFiles, deletedFiles };
}
export function isHiddenOrSpecial(filePath) {
return filePath.split('/').some(part => part.startsWith('.'));
}
export async function findPkgRoot(filePath, fetchFileContent, cache = {}) {
const skipDirs = new Set(['patches', 'files', 'src', 'images', '.github', '.git']);
const CATEGORIES = new Set([
'utils', 'net', 'libs', 'lang', 'kernel', 'firmware', 'devel', 'boot',
'system', 'multimedia', 'mail', 'sound', 'network'
]);
const hasPkgName = async (dir) => {
if (!fetchFileContent) return false;
if (dir in cache) return cache[dir];
const makefilePath = `${dir}/Makefile`;
const content = await fetchFileContent(makefilePath);
const ok = !!(content && /^PKG_NAME\s*(?::=|=)/m.test(content));
cache[dir] = ok;
return ok;
};
const isCategoryLevel = (parts) => {
if (parts.length === 0) return true;
if (parts.length === 1 && CATEGORIES.has(parts[0])) return true;
if (parts[0] === 'package' && parts.length === 2 && CATEGORIES.has(parts[1])) return true;
if (parts.length === 2 && CATEGORIES.has(parts[1])) return true;
return false;
};
let parts = filePath.split('/');
if (parts.length > 0) {
// Remove filename
parts.pop();
}
// Traverse up skipping standard directories
while (parts.length > 0) {
const last = parts[parts.length - 1];
if (skipDirs.has(last) || last.startsWith('.')) {
parts.pop();
} else {
break;
}
}
if (parts.length === 0 || parts.some(p => p.startsWith('.'))) {
return null;
}
// Fast path for common OpenWrt layouts: no network calls needed.
if (parts[0] === 'package') {
if (parts.length >= 3 && CATEGORIES.has(parts[1])) {
return `package/${parts[1]}/${parts[2]}`;
}
if (parts.length === 2 && !CATEGORIES.has(parts[1])) {
return `package/${parts[1]}`;
}
}
if (parts.length >= 2 && CATEGORIES.has(parts[0])) {
return `${parts[0]}/${parts[1]}`;
}
if (parts.length >= 3 && CATEGORIES.has(parts[1])) {
return `${parts[0]}/${parts[1]}/${parts[2]}`;
}
const candidates = [];
const seen = new Set();
const pushCandidate = (candidate) => {
if (!candidate) return;
if (seen.has(candidate)) return;
seen.add(candidate);
candidates.push(candidate);
};
// Fallback candidates for uncommon feed/category layouts.
for (let i = parts.length; i >= 2; i--) {
pushCandidate(parts.slice(0, i).join('/'));
}
for (const candidate of candidates) {
const candidateParts = candidate.split('/');
const last = candidateParts[candidateParts.length - 1];
if (last === 'package' || last.startsWith('.') || skipDirs.has(last)) {
continue;
}
if (isCategoryLevel(candidateParts)) {
continue;
}
if (await hasPkgName(candidate)) {
return candidate;
}
// When fetching is unavailable (unit tests / dry mode), trust first viable heuristic candidate.
if (!fetchFileContent) {
return candidate;
}
}
return null;
}
function parseMakefileVar(content, varName) {
const regex = new RegExp(`^${varName}\\s*(?::=|=)\\s*([^\\s#]+)`, 'm');
const match = content.match(regex);
return match ? match[1].replace(/["']/g, "").trim() : null;
}
export async function validatePkgReleaseBumps(commitDetails, CONFIG, fetchFileContentAtHead, fetchFileContentAtBase) {
const errors = [];
const warnings = [];
const successes = [];
if (CONFIG.check_pkg_release === false || CONFIG.check_pkg_release === 'disabled') {
return { errors, warnings, successes };
}
// 1. Collect all modified package roots
const pkgRoots = new Set();
const pkgRootCache = {};
const addedFiles = new Set();
const deletedFiles = new Set();
let exceededPkgLimit = false;
outer: for (const item of commitDetails) {
if (item.commitPatch) {
const states = parseDiffFileStates(item.commitPatch);
states.addedFiles.forEach(f => addedFiles.add(f));
states.deletedFiles.forEach(f => deletedFiles.add(f));
}
const files = getChangedFilesFromPatch(item.commitPatch);
for (const file of files) {
if (isHiddenOrSpecial(file)) continue;
// Ignore test files that serve only within CI/CD (e.g. test.sh, test-version.sh)
const filename = file.split('/').pop();
if (filename === 'test.sh' || filename === 'test-version.sh') {
continue;
}
const pkgRoot = await findPkgRoot(file, fetchFileContentAtHead, pkgRootCache);
if (pkgRoot) {
pkgRoots.add(pkgRoot);
if (pkgRoots.size > 15) {
exceededPkgLimit = true;
break outer;
}
}
}
}
if (exceededPkgLimit) {
warnings.push(`Package release bump audit skipped: PR modifies ${pkgRoots.size} packages. Batch updates of >15 packages are not automatically audited to prevent hitting API rate/subrequest limits.`);
return { errors, warnings, successes };
}
// 2. Process each package root
for (const pkgRoot of pkgRoots) {
const makefilePath = `${pkgRoot}/Makefile`;
if (deletedFiles.has(makefilePath)) {
// Package was deleted/dropped, skip checks
continue;
}
const headContent = await fetchFileContentAtHead(makefilePath);
if (headContent === null) {
// Package was deleted/dropped, skip checks
continue;
}
const isNew = addedFiles.has(makefilePath);
const baseContent = isNew ? null : await fetchFileContentAtBase(makefilePath);
const headRelease = parseMakefileVar(headContent, 'PKG_RELEASE');
if (isNew) {
if (headRelease !== '1') {
errors.push(`New package \`${pkgRoot}\` must start with PKG_RELEASE set to 1 (currently: '${headRelease || 'not defined'}')`);
} else {
successes.push(`✅ New package \`${pkgRoot}\` correctly initializes PKG_RELEASE to 1`);
}
continue;
}
// Existing package modified
const baseVersion = parseMakefileVar(baseContent, 'PKG_VERSION');
const headVersion = parseMakefileVar(headContent, 'PKG_VERSION');
const baseRelease = parseMakefileVar(baseContent, 'PKG_RELEASE');
const baseSourceVer = parseMakefileVar(baseContent, 'PKG_SOURCE_VERSION');
const headSourceVer = parseMakefileVar(headContent, 'PKG_SOURCE_VERSION');
const baseSourceDate = parseMakefileVar(baseContent, 'PKG_SOURCE_DATE');
const headSourceDate = parseMakefileVar(headContent, 'PKG_SOURCE_DATE');
const versionChanged = (baseVersion !== headVersion) || (baseSourceVer !== headSourceVer) || (baseSourceDate !== headSourceDate);
const releaseChanged = (baseRelease !== headRelease);
const bumped = versionChanged || releaseChanged;
if (!bumped) {
errors.push(`Package \`${pkgRoot}\` content changed without a PKG_RELEASE or version bump`);
} else if (versionChanged) {
if (headRelease !== '1') {
errors.push(`Package \`${pkgRoot}\` version updated from '${baseVersion || baseSourceVer || baseSourceDate}' to '${headVersion || headSourceVer || headSourceDate}', but PKG_RELEASE was not reset to 1 (currently: '${headRelease || 'not defined'}')`);
} else {
successes.push(`✅ Package \`${pkgRoot}\` version updated to '${headVersion || headSourceVer || headSourceDate}' and PKG_RELEASE correctly reset to 1`);
}
} else {
successes.push(`✅ Package \`${pkgRoot}\` version unchanged, but PKG_RELEASE bumped from '${baseRelease}' to '${headRelease}'`);
}
}
return { errors, warnings, successes };
}