|
| 1 | +import * as fs from 'fs'; |
| 2 | +import * as path from 'path'; |
| 3 | + |
| 4 | +const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx']; |
| 5 | +const IGNORE_DIRS = ['node_modules', 'dist', 'build', '.git', 'generated']; |
| 6 | + |
| 7 | +function hasLicenseHeader(fileContent: string): boolean { |
| 8 | + const normalizedContent = fileContent.trim().substring(0, 500); |
| 9 | + |
| 10 | + return ( |
| 11 | + normalizedContent.includes('@license') || |
| 12 | + normalizedContent.includes('Licensed to the Apache Software Foundation') |
| 13 | + ); |
| 14 | +} |
| 15 | + |
| 16 | +function checkFile(filePath: string): boolean { |
| 17 | + const content = fs.readFileSync(filePath, 'utf-8'); |
| 18 | + |
| 19 | + if (!hasLicenseHeader(content)) { |
| 20 | + console.error(`Missing license header: ${filePath}`); |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + return true; |
| 25 | +} |
| 26 | + |
| 27 | +function processDirectory(dirPath: string): boolean { |
| 28 | + let allValid = true; |
| 29 | + const entries = fs.readdirSync(dirPath, { withFileTypes: true }); |
| 30 | + |
| 31 | + for (const entry of entries) { |
| 32 | + const fullPath = path.join(dirPath, entry.name); |
| 33 | + |
| 34 | + if (entry.isDirectory()) { |
| 35 | + if (!IGNORE_DIRS.includes(entry.name)) { |
| 36 | + if (!processDirectory(fullPath)) { |
| 37 | + allValid = false; |
| 38 | + } |
| 39 | + } |
| 40 | + } else if (entry.isFile()) { |
| 41 | + const ext = path.extname(entry.name); |
| 42 | + if (SOURCE_EXTENSIONS.includes(ext)) { |
| 43 | + if (!checkFile(fullPath)) { |
| 44 | + allValid = false; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return allValid; |
| 51 | +} |
| 52 | + |
| 53 | +function main(): void { |
| 54 | + try { |
| 55 | + console.log('Checking license headers...\n'); |
| 56 | + |
| 57 | + const isValid = processDirectory('.'); |
| 58 | + |
| 59 | + if (!isValid) { |
| 60 | + console.error( |
| 61 | + '\nSome files are missing license headers.\n' + 'Run: npm run add-license-headers', |
| 62 | + ); |
| 63 | + process.exit(1); |
| 64 | + } |
| 65 | + |
| 66 | + console.log('All files contain license headers.'); |
| 67 | + } catch (error) { |
| 68 | + console.error('Error:', error); |
| 69 | + process.exit(1); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +main(); |
0 commit comments