2020-02-04 20:27:46 +01:00
|
|
|
import * as fs from "fs-extra"
|
2020-02-14 23:41:42 +01:00
|
|
|
import * as path from "path"
|
2020-05-10 07:35:42 +02:00
|
|
|
import { extend, paths } from "./util"
|
2020-02-04 20:27:46 +01:00
|
|
|
import { logger } from "@coder/logger"
|
2020-07-30 07:37:41 +02:00
|
|
|
import { Route } from "./http"
|
2020-02-04 20:27:46 +01: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.
|
|
|
|
* Objects will be merged and everything else will be replaced.
|
|
|
|
*/
|
2020-07-30 07:37:41 +02:00
|
|
|
public async write(settings: Partial<T>, shallow?: boolean): Promise<void> {
|
2020-02-04 20:27:46 +01:00
|
|
|
try {
|
2020-07-30 07:37:41 +02:00
|
|
|
const oldSettings = await this.read()
|
|
|
|
const nextSettings = shallow ? Object.assign({}, oldSettings, settings) : extend(oldSettings, settings)
|
|
|
|
await fs.writeFile(this.settingsPath, JSON.stringify(nextSettings, null, 2))
|
2020-02-04 20:27:46 +01:00
|
|
|
} catch (error) {
|
|
|
|
logger.warn(error.message)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-02-14 23:41:42 +01:00
|
|
|
|
2020-02-20 22:50:01 +01:00
|
|
|
export interface UpdateSettings {
|
|
|
|
update: {
|
|
|
|
checked: number
|
|
|
|
version: string
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-14 23:41:42 +01:00
|
|
|
/**
|
|
|
|
* Global code-server settings.
|
|
|
|
*/
|
2020-02-20 22:50:01 +01:00
|
|
|
export interface CoderSettings extends UpdateSettings {
|
2020-02-14 23:41:42 +01:00
|
|
|
lastVisited: {
|
|
|
|
url: string
|
|
|
|
workspace: boolean
|
|
|
|
}
|
2020-07-30 07:37:41 +02:00
|
|
|
query: Route["query"]
|
2020-02-14 23:41:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Global code-server settings file.
|
|
|
|
*/
|
2020-05-10 07:35:42 +02:00
|
|
|
export const settings = new SettingsProvider<CoderSettings>(path.join(paths.data, "coder.json"))
|