-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathtsconfig-mode.mjs
More file actions
59 lines (51 loc) · 1.87 KB
/
Copy pathtsconfig-mode.mjs
File metadata and controls
59 lines (51 loc) · 1.87 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
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const templatesDir = path.join(__dirname, "..", "templates");
export const TSCONFIG_TEMPLATES = {
packages: path.join(templatesDir, "tsconfig.packages-mode.json"),
local: path.join(templatesDir, "tsconfig.local-mode.json"),
};
export const ROOT_TSCONFIG_RELATIVE = "tsconfig.json";
function readFileTrimmedTrailingNewline(filePath) {
return fs.readFileSync(filePath, "utf8").replace(/\n+$/, "");
}
export function readRootTsconfig(repoRoot) {
const tsconfigPath = path.join(repoRoot, ROOT_TSCONFIG_RELATIVE);
if (!fs.existsSync(tsconfigPath)) {
return null;
}
return readFileTrimmedTrailingNewline(tsconfigPath);
}
export function readTsconfigTemplate(mode) {
const templatePath = TSCONFIG_TEMPLATES[mode];
if (!templatePath) {
throw new Error(
`[tsconfig-mode] Unsupported mode "${mode}". Use "packages" or "local".`,
);
}
return readFileTrimmedTrailingNewline(templatePath);
}
export function tsconfigMatchesMode(repoRoot, mode) {
const current = readRootTsconfig(repoRoot);
if (current === null) return false;
const expected = readTsconfigTemplate(mode);
return current === expected;
}
export function applyTsconfigMode(repoRoot, mode, { log = console.log } = {}) {
const tsconfigPath = path.join(repoRoot, ROOT_TSCONFIG_RELATIVE);
const template = readTsconfigTemplate(mode);
const current = fs.existsSync(tsconfigPath)
? fs.readFileSync(tsconfigPath, "utf8")
: null;
const desired = `${template}\n`;
if (current === desired) {
return { changed: false, mode };
}
fs.writeFileSync(tsconfigPath, desired);
log(
`[tsconfig-mode] Wrote ${ROOT_TSCONFIG_RELATIVE} from ${path.relative(repoRoot, TSCONFIG_TEMPLATES[mode])}`,
);
return { changed: true, mode };
}