// Settings persistence: one JSON file, written atomically (temp + rename) so a
// crash mid-write can never leave a truncated config.
//
// A config that fails to parse is moved aside, never overwritten: otherwise the
// first change after a bad read would replace the user's units and looks with
// defaults.
import fs from 'bare-fs'
import path from 'bare-path'
export class Store {
constructor (dir) {
this.dir = dir
this.file = path.join(dir, 'config.json')
}
load () {
let text
try {
text = fs.readFileSync(this.file, 'utf8')
} catch {
return {}
}
try {
return JSON.parse(text)
} catch (err) {
const aside = this.file + '.bad-' + Date.now()
fs.renameSync(this.file, aside)
console.error(JSON.stringify({ msg: 'config unreadable, moved aside', aside, error: err.message }))
return {}
}
}
save (data) {
fs.mkdirSync(this.dir, { recursive: true })
const tmp = this.file + '.tmp'
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n')
fs.renameSync(tmp, this.file)
}
}