|
1 | 1 | import type { Arguments } from "yargs-types"; |
2 | | -import { join } from "@std/path"; |
| 2 | +import { dirname, join } from "@std/path"; |
3 | 3 | import z from "zod"; |
4 | 4 |
|
5 | 5 | export const globalConfigSchema = z.object({ |
@@ -74,28 +74,44 @@ export function globalConfigMiddleware( |
74 | 74 | const result = globalConfigSchema.safeParse(JSON.parse(content)); |
75 | 75 | if (!result.success) { |
76 | 76 | // wrong config, generate a new one |
77 | | - config = defaultConfig; |
78 | | - Deno.writeTextFileSync(configPath, JSON.stringify(config, null, 2)); |
79 | | - } |
80 | | - if (result.data) { |
81 | | - config = result.data; |
| 77 | + setConfig(config); |
| 78 | + args.globalConfig = config; |
| 79 | + return; |
82 | 80 | } |
| 81 | + |
| 82 | + // config is valid, use it |
| 83 | + config = result.data; |
| 84 | + args.globalConfig = config; |
| 85 | + return; |
83 | 86 | } else { |
84 | 87 | // no config, generate a new one |
85 | | - config = defaultConfig; |
86 | | - Deno.writeTextFileSync(configPath, JSON.stringify(config, null, 2)); |
| 88 | + setConfig(config); |
| 89 | + args.globalConfig = config; |
| 90 | + return; |
87 | 91 | } |
88 | 92 | } catch (_error) { |
89 | 93 | // failed to read or create config, generate a new one |
90 | 94 | config = defaultConfig; |
91 | | - Deno.writeTextFileSync(configPath, JSON.stringify(config, null, 2)); |
| 95 | + setConfig(config); |
| 96 | + args.globalConfig = config; |
| 97 | + return; |
92 | 98 | } |
93 | | - |
94 | | - args.globalConfig = config; |
95 | 99 | } |
96 | 100 |
|
97 | 101 | export function setConfig( |
98 | 102 | config: z.infer<typeof globalConfigSchema>, |
99 | 103 | ) { |
100 | | - Deno.writeTextFileSync(getConfigPath(), JSON.stringify(config, null, 2)); |
| 104 | + const configPath = getConfigPath(); |
| 105 | + const dir = dirname(configPath); |
| 106 | + let dirExists = false; |
| 107 | + try { |
| 108 | + Deno.statSync(dir); |
| 109 | + dirExists = true; |
| 110 | + } catch { |
| 111 | + dirExists = false; |
| 112 | + } |
| 113 | + if (!dirExists) { |
| 114 | + Deno.mkdirSync(dir, { recursive: true }); |
| 115 | + } |
| 116 | + Deno.writeTextFileSync(configPath, JSON.stringify(config, null, 2)); |
101 | 117 | } |
0 commit comments