forked from QwikDev/qwik
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils-api.ts
More file actions
79 lines (70 loc) · 2.38 KB
/
utils-api.ts
File metadata and controls
79 lines (70 loc) · 2.38 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
import { copyFileSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'fs';
import { extname, join } from 'path';
import type { PackageJSON } from '../../../scripts/util';
export type Replacements = [RegExp, string][];
export function cp(srcDir: string, destDir: string, replacements: Replacements) {
const items = readdirSync(srcDir);
for (const itemName of items) {
const destName = itemName === 'gitignore' ? '.gitignore' : itemName;
const srcChildPath = join(srcDir, itemName);
const destChildPath = join(destDir, destName);
const s = statSync(srcChildPath);
if (s.isDirectory()) {
mkdirSync(destChildPath, { recursive: true });
cp(srcChildPath, destChildPath, replacements);
} else if (s.isFile()) {
const shouldReplace =
replacements.length > 0 &&
['.json', '.toml', '.md', '.html'].includes(extname(srcChildPath));
if (shouldReplace) {
let srcContent = readFileSync(srcChildPath, 'utf8');
for (const regex of replacements) {
srcContent = srcContent.replace(regex[0], regex[1]);
}
writeFileSync(destChildPath, srcContent);
} else {
copyFileSync(srcChildPath, destChildPath);
}
}
}
}
export function readPackageJson(dir: string) {
const path = join(dir, 'package.json');
const pkgJson: PackageJSON = JSON.parse(readFileSync(path, 'utf-8'));
return pkgJson;
}
export function writePackageJson(dir: string, pkgJson: PackageJSON) {
const path = join(dir, 'package.json');
writeFileSync(path, JSON.stringify(pkgJson, null, 2) + '\n');
}
export function dashToTitlelCase(str: string) {
return str
.toLocaleLowerCase()
.split('-')
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
.join(' ');
}
export function toDashCase(str: string) {
return str.toLocaleLowerCase().replace(/ /g, '-');
}
export function mergePackageJSONs(a: any, b: any) {
const props = ['scripts', 'dependencies', 'devDependencies'];
props.forEach((prop) => {
mergeSort(a, b, prop);
});
}
function mergeSort(a: any, b: any, prop: string) {
if (b[prop]) {
if (a[prop]) {
Object.assign(a[prop], { ...b[prop] });
} else {
a[prop] = { ...b[prop] };
}
const sorted: any = {};
const keys = Object.keys(a[prop]).sort();
for (const key of keys) {
sorted[key] = a[prop][key];
}
a[prop] = sorted;
}
}