forked from kt3k/license-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.ts
executable file
·104 lines (89 loc) · 2.52 KB
/
lib.ts
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
// Copyright 2020-2022 Yoshiya Hinosawa. All rights reserved. MIT license.
import writeFile = Deno.writeFile;
const { readFile } = Deno;
import {
blue,
contains,
delay,
expandGlob,
green,
red,
relative,
} from "./deps.ts";
const decoder = new TextDecoder();
const decode = (data: Uint8Array) => decoder.decode(data);
const encoder = new TextEncoder();
const encode = (str: string) => encoder.encode(str);
type LicenseLines = string | string[];
export interface Config {
ignore?: string[];
config: Array<[string, LicenseLines]>;
}
const checkFile = async (
filename: string,
copyrightLines: Uint8Array[],
quiet: boolean,
inject: boolean,
): Promise<boolean> => {
const stat = await Deno.lstat(filename);
if (stat.isDirectory) {
if (!quiet) {
console.log(filename, "is a directory. Skipping this item.");
}
return true;
}
const file = await Deno.open(filename, { read: true });
// We assume copyright header appears in first 8KB of each file.
const sourceCode = new Uint8Array(8192);
await Deno.read(file.rid, sourceCode);
Deno.close(file.rid);
if (copyrightLines.every((line) => contains(sourceCode, line))) {
if (!quiet) {
console.log(filename, "...", green("ok"));
}
return true;
}
if (inject) {
const sourceCode = await readFile(filename);
console.log(`${filename} ${blue("missing copyright. injecting ... done")}`);
await writeFile(
filename,
encode(copyrightLines.map(decode).join("\n") + "\n" + decode(sourceCode)),
);
return true;
} else {
console.log(filename, red("missing copyright!"));
}
return false;
};
type CheckOptions = {
cwd?: string;
quiet?: boolean;
inject?: boolean;
};
export const checkLicense = async (
configs: Config[],
opts: CheckOptions = {},
): Promise<boolean> => {
const cwd = opts.cwd ?? Deno.cwd();
const quiet = opts.quiet ?? false;
const inject = opts.inject ?? false;
const tasks = [];
for (const { ignore, config } of configs) {
for (const [glob, copyright] of config) {
const copyrightLines = Array.isArray(copyright)
? copyright.map(encode)
: [encode(copyright)];
for await (const file of expandGlob(glob)) {
const relPath = relative(cwd, file.path);
if (ignore?.some((pattern) => relPath.includes(pattern))) {
continue;
}
tasks.push(checkFile(relPath, copyrightLines, quiet, inject));
await delay(1);
}
}
}
const results = await Promise.all(tasks);
return !results.includes(false);
};