-
Notifications
You must be signed in to change notification settings - Fork 1
/
file-system.ts
111 lines (96 loc) · 2.6 KB
/
file-system.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import fs from 'node:fs'
import path from 'node:path'
import { confirm } from '@inquirer/prompts'
import type {
FileModificationOperation,
PathModificationOperation,
SourceTargetOperation,
} from './interfaces'
import logger from './log'
export function isFile(path: string) {
return fs.existsSync(path) && fs.lstatSync(path).isFile()
}
export function isDirectory(path: string) {
return fs.existsSync(path) && fs.lstatSync(path).isDirectory()
}
export function copyFile({ source, target }: SourceTargetOperation) {
if (isFile(target)) {
logger.warn(`Path: ${target} already exists.`)
return
}
if (isFile(source)) {
fs.copyFileSync(source, target, 0)
logger.info(`File: ${source} copied to ${target}.`)
} else {
logger.error('Could not perform file copy operation.')
logger.error('Source is not a valid file.')
}
}
export function createFile({
file,
content,
overwrite = false,
}: FileModificationOperation) {
if (!isFile(file) || overwrite) {
logger.info(`Creating file: ${file}...`)
fs.writeFileSync(file, content, 'utf8')
logger.info(`File: '${file}' successfully created.`)
} else {
logger.warn(`File: '${file}' already exists.`)
}
}
export function createPath({ path }: PathModificationOperation) {
if (!isDirectory(path)) {
logger.info(`Creating path: ${path}...`)
fs.mkdirSync(path, { recursive: true })
logger.info(`Path: '${path}' successfully created.`)
} else {
logger.warn(`Path: '${path}' already exists.`)
}
}
export async function deletePath({
path,
force = false,
}: PathModificationOperation) {
if (await isDirectory(path)) {
if (
force ||
(await confirm({ message: `Delete directory ${path} recursively?` }))
) {
fs.rmdirSync(path, { recursive: true })
logger.info(`Directory ${path} deleted.`)
}
}
if (isFile(path)) {
if (
force ||
(await confirm({
message: `Delete file ${path}?`,
}))
) {
fs.rmSync(path)
logger.info(`File ${path} deleted.`)
}
}
return
}
export function readPathMatchingFiles(
dir: string,
matchFileName: string,
): Array<string> {
const results: Array<string> = []
function recursiveReadDir(dir: string) {
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(entry.parentPath, entry.name)
if (entry.isDirectory()) {
recursiveReadDir(fullPath)
}
if (entry.isFile() && entry.name.includes(matchFileName)) {
results.push(fullPath)
}
}
}
recursiveReadDir(dir)
return results
}