-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathaddLicence.js
More file actions
executable file
·82 lines (71 loc) · 2.53 KB
/
addLicence.js
File metadata and controls
executable file
·82 lines (71 loc) · 2.53 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
#!/usr/bin/env node
const { promises: fs } = require("fs");
const path = require("path");
async function findFiles(dir, extension) {
let files = [];
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === "node_modules") continue;
files = files.concat(await findFiles(fullPath, extension));
} else if (entry.isFile() && path.extname(fullPath) === `.${extension}`) {
files.push(fullPath);
}
}
} catch (error) {
console.error(`Error reading directory ${dir}:`, error);
}
return files;
}
function normalizeLicenseContent(content) {
return content
.trim()
.replace(/\r\n/g, "\n") // Normalize line endings
.split("\n")
.map((line) => line.trim().replace(/^\*/, "").trim())
.join("\n")
.replace(/\s+/g, " ")
.replace(/\n+/g, "\n");
}
async function prependContentToFiles(rootDirectory, contentFile, fileExtension) {
try {
const content = await fs.readFile(contentFile, "utf8");
const comment = `/*\n${content}\n*/\n\n`;
// Create normalized version for comparison
const licenseNormalized = normalizeLicenseContent(content);
const files = await findFiles(rootDirectory, fileExtension);
if (files.length === 0) {
console.log("No matching files found.");
return;
}
for (const file of files) {
try {
const existingContent = await fs.readFile(file, "utf8");
// Check for existing license using more sophisticated detection
const existingHeaderMatch = existingContent.match(/^\/\*[\s\S]*?\*\//);
let hasExistingLicense = false;
if (existingHeaderMatch) {
const existingHeader = existingHeaderMatch[0];
const existingNormalized = normalizeLicenseContent(
existingHeader.replace(/^\/\*+/, "").replace(/\*+\/$/, ""),
);
// Compare normalized content
hasExistingLicense = existingNormalized === licenseNormalized;
}
if (!hasExistingLicense) {
await fs.writeFile(file, comment + existingContent);
console.log(`Prepended content to ${file}`);
} else {
console.log(`Valid license header already exists in ${file}, skipping.`);
}
} catch (error) {
console.error(`Error processing file ${file}:`, error);
}
}
} catch (error) {
console.error("Error:", error);
}
}
prependContentToFiles("./", "./LICENSE", "ts");