-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy.ts
More file actions
77 lines (66 loc) · 1.8 KB
/
copy.ts
File metadata and controls
77 lines (66 loc) · 1.8 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
import { existsSync } from 'node:fs';
import { copyFile, mkdir, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import prompts from 'prompts';
import { replaceInFile } from 'replace-in-file';
// Select year and date
const { year, day } = await prompts([
{
type: 'number',
name: 'year',
message: 'What year?',
initial: new Date().getFullYear(),
validate: (val) =>
val > 2000 && val < 3000 ? true : 'Year needs to be between 2000-3000',
format: String
},
{
type: 'number',
name: 'day',
message: 'What day?',
initial: new Date().getDate(),
validate: (val) =>
val > 0 && val < 32 ? true : 'Day needs to be between 1-31',
format: (val) => String(val).padStart(2, '0')
}
]);
const dir = join(year, day);
if (existsSync(dir)) {
console.warn('Directory already exists!');
process.exit(1);
}
// Create new day folder
await mkdir(dir, { recursive: true });
// Parse template folder for files
const templateDir = 'template';
const files = await readdir(templateDir);
const yearRegex = /YYYY/g;
const dayRegex = /DD/g;
// Copy files from template to day folder, replace placeholders in filename
await Promise.all(
files.map((f) =>
copyFile(
join(templateDir, f),
join(dir, f.replaceAll(yearRegex, year).replaceAll(dayRegex, day))
)
)
);
// Replace placeholders in code
const resultYear = await replaceInFile({
files: [join(dir, '*')],
from: yearRegex,
to: year
});
const resultDay = await replaceInFile({
files: [join(dir, '*')],
from: dayRegex,
to: day
});
const results = [...resultYear, ...resultDay];
if (results.filter((r) => r.hasChanged).length <= 0) {
console.error(
'Something went wrong while replace placeholders! Did they change?'
);
process.exit(1);
}
console.log('Directory created! Have fun!');