-
Notifications
You must be signed in to change notification settings - Fork 153
/
local-options.ts
79 lines (68 loc) · 1.83 KB
/
local-options.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
import { homedir } from 'node:os'
import { existsSync } from 'node:fs'
import fs from 'node:fs/promises'
import { dirname } from 'node:path'
import { join } from 'pathe'
import { hash } from 'ohash'
interface LocalOptionSearchOptions {
root: string
key?: string | boolean
}
export function getHomeDir() {
return process.env.XDG_CONFIG_HOME || homedir()
}
export async function readLocalOptions<T>(defaults: T, options: LocalOptionSearchOptions): Promise<T> {
const { filePath } = getOptionsFilepath(options)
if (existsSync(filePath)) {
try {
const options = {
...defaults,
...JSON.parse(await fs.readFile(filePath, 'utf-8')).settings || {},
}
return options
}
catch (e) {
console.error(`[DevTools] failed to parse local options file: ${filePath}, fallback to defaults`)
console.error(e)
return { ...defaults }
}
}
else {
return { ...defaults }
}
}
function getOptionsFilepath(options: LocalOptionSearchOptions) {
let hashedKey
if (options.key)
hashedKey = hash(`${options.root}:${options.key}`)
else
hashedKey = hash(options.root)
const home = getHomeDir()
const filePath = join(home, '.nuxt/devtools', `${hashedKey}.json`)
return {
filePath,
hashedKey,
}
}
export async function clearLocalOptions(options: LocalOptionSearchOptions) {
const { filePath } = getOptionsFilepath(options)
if (existsSync(filePath))
await fs.unlink(filePath)
}
export async function writeLocalOptions<T>(settings: T, options: LocalOptionSearchOptions) {
const { filePath, hashedKey } = getOptionsFilepath(options)
await fs.mkdir(dirname(filePath), { recursive: true })
await fs.writeFile(
filePath,
JSON.stringify(
{
root: options.root,
hash: hashedKey,
settings,
},
null,
2,
),
'utf-8',
)
}