-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelper.ts
60 lines (48 loc) · 2.04 KB
/
helper.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
import { existsSync, lstatSync, mkdirSync, readdirSync, rmSync } from 'node:fs'
import { isAbsolute, join } from 'node:path'
import validate from 'validate-npm-package-name'
import { log } from './log'
import { promptClear } from './prompt'
const hiddenFiles = ['.DS_Store']
const protectedFiles = ['.git'] // User checking out a template into a repository.
const invisibleFiles = [...hiddenFiles, ...protectedFiles]
function deleteFolderContents(directory: string) {
for (const file of readdirSync(directory)) {
if (!protectedFiles.includes(file)) {
rmSync(join(directory, file), { recursive: true })
}
}
}
const isDirectoryEmpty = (directory: string) => readdirSync(directory).filter((file: string) => !invisibleFiles.includes(file)).length === 0
export const getDestinationPath = async (input = process.cwd(), skipClear = false) => {
let destinationPath = process.cwd()
if (input && !isAbsolute(input)) {
destinationPath = join(process.cwd(), input)
} else {
destinationPath = input
}
if (!existsSync(destinationPath)) {
mkdirSync(destinationPath, { recursive: true })
} else if (!lstatSync(destinationPath).isDirectory()) {
log(`Destination ${destinationPath} must be a directory`, 'error')
} else if (!(skipClear || isDirectoryEmpty(destinationPath))) {
const clear = await promptClear(destinationPath)
if (clear) {
// Clear directory contents to ensure proper template installation.
deleteFolderContents(destinationPath)
} else {
log('Keeping existing contents, might be overriden when copying the template')
}
}
return destinationPath
}
export const validatePackageName = (packageName?: string) => {
if (!(packageName && typeof packageName === 'string')) {
log('Please provide a valid package name', 'error')
}
if (!validate(packageName as string).validForOldPackages) {
log(`${packageName} is not a valid package name`, 'error')
}
return packageName
}
export const cleanup = (cachePath: string) => existsSync(cachePath) && rmSync(cachePath, { recursive: true })