2023-05-02 13:24:11 +00:00
|
|
|
import { existsSync, promises as fsp } from 'node:fs'
|
|
|
|
import { dirname, join } from 'pathe'
|
2023-04-08 10:16:06 +00:00
|
|
|
import { consola } from 'consola'
|
2021-07-26 14:46:19 +00:00
|
|
|
|
2023-05-02 13:24:11 +00:00
|
|
|
export async function clearDir (path: string, exclude?: string[]) {
|
|
|
|
if (!exclude) {
|
|
|
|
await fsp.rm(path, { recursive: true, force: true })
|
|
|
|
} else if (existsSync(path)) {
|
|
|
|
const files = await fsp.readdir(path)
|
|
|
|
await Promise.all(files.map(async (name) => {
|
|
|
|
if (!exclude.includes(name)) {
|
|
|
|
await fsp.rm(join(path, name), { recursive: true, force: true })
|
|
|
|
}
|
|
|
|
}))
|
|
|
|
}
|
2021-10-18 14:22:02 +00:00
|
|
|
await fsp.mkdir(path, { recursive: true })
|
|
|
|
}
|
2021-10-29 08:41:04 +00:00
|
|
|
|
2023-05-02 13:24:11 +00:00
|
|
|
export function clearBuildDir (path: string) {
|
|
|
|
return clearDir(path, ['cache', 'analyze'])
|
|
|
|
}
|
|
|
|
|
2022-07-25 15:19:17 +00:00
|
|
|
export async function rmRecursive (paths: string[]) {
|
2022-08-11 11:41:53 +00:00
|
|
|
await Promise.all(paths.filter(p => typeof p === 'string').map(async (path) => {
|
|
|
|
consola.debug('Removing recursive path', path)
|
|
|
|
await fsp.rm(path, { recursive: true, force: true }).catch(() => {})
|
2022-07-25 15:19:17 +00:00
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
2022-08-11 11:41:53 +00:00
|
|
|
export async function touchFile (path: string) {
|
|
|
|
const time = new Date()
|
|
|
|
await fsp.utimes(path, time, time).catch(() => {})
|
|
|
|
}
|
|
|
|
|
2021-10-29 08:41:04 +00:00
|
|
|
export function findup<T> (rootDir: string, fn: (dir: string) => T | undefined): T | null {
|
|
|
|
let dir = rootDir
|
|
|
|
while (dir !== dirname(dir)) {
|
|
|
|
const res = fn(dir)
|
|
|
|
if (res) {
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
dir = dirname(dir)
|
|
|
|
}
|
|
|
|
return null
|
|
|
|
}
|