code-server/src/node/settings.ts

68 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-08-05 04:51:39 +08:00
import { logger } from "@coder/logger"
2020-10-21 07:05:58 +08:00
import { Query } from "express-serve-static-core"
2020-02-05 03:27:46 +08:00
import * as fs from "fs-extra"
import * as path from "path"
2020-08-05 04:51:39 +08:00
import { paths } from "./util"
2020-02-05 03:27:46 +08:00
export type Settings = { [key: string]: Settings | string | boolean | number }
/**
* Provides read and write access to settings.
*/
export class SettingsProvider<T> {
public constructor(private readonly settingsPath: string) {}
/**
* Read settings from the file. On a failure return last known settings and
* log a warning.
*/
public async read(): Promise<T> {
try {
const raw = (await fs.readFile(this.settingsPath, "utf8")).trim()
return raw ? JSON.parse(raw) : {}
} catch (error) {
if (error.code !== "ENOENT") {
logger.warn(error.message)
}
}
return {} as T
}
/**
* Write settings combined with current settings. On failure log a warning.
2020-08-05 04:12:15 +08:00
* Settings will be merged shallowly.
2020-02-05 03:27:46 +08:00
*/
2020-08-05 04:12:15 +08:00
public async write(settings: Partial<T>): Promise<void> {
2020-02-05 03:27:46 +08:00
try {
const oldSettings = await this.read()
2020-08-05 04:12:15 +08:00
const nextSettings = { ...oldSettings, ...settings }
await fs.writeFile(this.settingsPath, JSON.stringify(nextSettings, null, 2))
2020-02-05 03:27:46 +08:00
} catch (error) {
logger.warn(error.message)
}
}
}
export interface UpdateSettings {
update: {
checked: number
version: string
}
}
/**
* Global code-server settings.
*/
export interface CoderSettings extends UpdateSettings {
lastVisited: {
url: string
workspace: boolean
}
2020-10-21 07:05:58 +08:00
query: Query
}
/**
* Global code-server settings file.
*/
export const settings = new SettingsProvider<CoderSettings>(path.join(paths.data, "coder.json"))