use write-file-atomic for config saving

This commit is contained in:
Eugene Pankov
2022-06-15 20:56:47 +02:00
parent 8d5dffcca1
commit ef49aa213e
3 changed files with 27 additions and 18 deletions

View File

@@ -1,10 +1,9 @@
import * as fs from 'mz/fs'
import * as path from 'path'
import * as yaml from 'js-yaml'
import { v4 as uuidv4 } from 'uuid'
import * as gracefulFS from 'graceful-fs'
import { app } from 'electron'
import { promisify } from 'util'
import writeFileAtomic from 'write-file-atomic'
export function migrateConfig (): void {
const configPath = path.join(app.getPath('userData'), 'config.yaml')
@@ -28,21 +27,9 @@ export function loadConfig (): any {
}
}
const configPath = path.join(app.getPath('userData'), 'config.yaml')
let _configSaveInProgress = Promise.resolve()
async function _saveConfigInternal (content: string): Promise<void> {
const tempPath = configPath + '.new.' + uuidv4().toString()
await fs.writeFile(tempPath, content, 'utf8')
await fs.writeFile(configPath + '.backup', content, 'utf8')
await promisify(gracefulFS.rename)(tempPath, configPath)
}
export async function saveConfig (content: string): Promise<void> {
try {
await _configSaveInProgress
} catch { }
_configSaveInProgress = _saveConfigInternal(content)
await _configSaveInProgress
await writeFileAtomic(configPath, content, { encoding: 'utf8' })
await writeFileAtomic(configPath + '.backup', content, { encoding: 'utf8' })
}