forked from antfu-collective/bumpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs.ts
82 lines (71 loc) · 1.72 KB
/
fs.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
import fs from 'node:fs'
import path from 'node:path'
import detectIndent from 'detect-indent'
import { detectNewline } from 'detect-newline'
/**
* Describes a plain-text file.
*/
export interface TextFile {
path: string
data: string
}
/**
* Describes a JSON file.
*/
interface JsonFile {
path: string
data: unknown
indent: string
newline: string | undefined
}
/**
* Reads a JSON file and returns the parsed data.
*/
export async function readJsonFile(name: string, cwd: string): Promise<JsonFile> {
const file = await readTextFile(name, cwd)
const data = JSON.parse(file.data) as unknown
const indent = detectIndent(file.data).indent
const newline = detectNewline(file.data)
return { ...file, data, indent, newline }
}
/**
* Writes the given data to the specified JSON file.
*/
export async function writeJsonFile(file: JsonFile): Promise<void> {
let json = JSON.stringify(file.data, undefined, file.indent)
if (file.newline)
json += file.newline
return writeTextFile({ ...file, data: json })
}
/**
* Reads a text file and returns its contents.
*/
export function readTextFile(name: string, cwd: string): Promise<TextFile> {
return new Promise((resolve, reject) => {
const filePath = path.join(cwd, name)
fs.readFile(filePath, 'utf8', (err, text) => {
if (err) {
reject(err)
}
else {
resolve({
path: filePath,
data: text,
})
}
})
})
}
/**
* Writes the given text to the specified file.
*/
export function writeTextFile(file: TextFile): Promise<void> {
return new Promise((resolve, reject) => {
fs.writeFile(file.path, file.data, (err) => {
if (err)
reject(err)
else
resolve()
})
})
}