-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.ts
More file actions
90 lines (73 loc) · 2.19 KB
/
Copy pathsync.ts
File metadata and controls
90 lines (73 loc) · 2.19 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
83
84
85
86
87
88
89
90
import {execSync} from 'child_process';
import fs from 'fs';
import path from 'path';
type Task = {
src: string;
dest: string;
};
const IGNORE_FILES = [
/^bin/,
/^\.git.*$/,
/^README\.md$/,
/^LICENSE$/,
/^sync\.ts$/,
/^package\.json$/,
/^package-lock\.json$/,
/^tsconfig\.json$/,
/^node_modules/,
/^dist/,
];
function copyFile(src: string, dest: string) {
fs.copyFileSync(src, dest);
if (src.startsWith('bin/')) {
const srcStat = fs.statSync(src);
fs.chmodSync(dest, srcStat.mode);
fs.utimesSync(dest, srcStat.atime, srcStat.mtime);
}
}
async function main() {
const targetDir = process.env.HOME;
if (!targetDir) {
throw new Error('HOME environment variable not set');
}
const files = execSync('git ls-files -co --exclude-standard', {encoding: 'utf8'})
.split('\n')
.filter(Boolean)
.filter(file => !IGNORE_FILES.some(re => re.test(file)));
console.log(`Installing ${files.length} dotfiles to ${targetDir}`);
const tasks: Task[] = [
...files.map(file => ({src: file, dest: `.${file}`})),
...getAllFilesInDir('bin').map(file => ({
src: file,
dest: path.join('bin', path.relative('bin', file))
}))
];
for (const { src, dest } of tasks) {
if (!fs.existsSync(src)) {
continue;
}
const targetFile = path.join(targetDir, dest);
const parentDir = path.dirname(targetFile);
if (fs.existsSync(parentDir) && !fs.statSync(parentDir).isDirectory()) {
fs.unlinkSync(parentDir);
}
if (!fs.existsSync(parentDir)) {
fs.mkdirSync(parentDir, {recursive: true});
}
copyFile(src, targetFile);
console.log(`Installed ${src} to ${targetFile}`);
}
}
function getAllFilesInDir(dir: string): string[] {
if (!fs.existsSync(dir)) {
return [];
}
return fs.readdirSync(dir, {withFileTypes: true}).flatMap(entry => {
const fullPath = path.join(dir, entry.name);
return entry.isDirectory() ? getAllFilesInDir(fullPath) : fullPath;
});
}
main().catch(err => {
console.error(err);
process.exit(1);
});