Skip to content

Commit 7485ba0

Browse files
committed
ConfigHandler: create backup and a fresh configuration file when a json config file fails parsing
1 parent 43e1a4a commit 7485ba0

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

modules/DependencyControl/ConfigHandler.moon

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ mutex = require "BM.BadMutex"
99
class ConfigHandler
1010
@handlers = {}
1111
errors = {
12-
jsonDecode: "Failed decoding JSON (%s)."
12+
jsonDecode: "JSON parse error: %s"
13+
configCorrupted: [[An error occured while parsing the JSON config file.
14+
A backup of the corrupted configuration has been written to '%s'.
15+
Reload your automation scripts to generate a new configuration file.]]
1316
badKey: "Can't %s section because the key #%d (%s) leads to a %s."
1417
jsonRoot: "JSON root element must be an array or a hashtable, got a %s."
1518
noFile: "No config file defined."
@@ -125,7 +128,16 @@ class ConfigHandler
125128
data = handle\read "*a"
126129
success, result = pcall json.decode, data
127130
unless success
128-
return false, errors.jsonDecode\format result
131+
-- JSON parse error usually points to a corrupted config file
132+
-- Rename the broken file to allow generating a new one
133+
-- so the user can continue his work
134+
handle\close!
135+
@logger\trace errors.jsonDecode, result
136+
backup = @file .. ".corrupted"
137+
fileOps.copy @file, backup
138+
fileOps.remove @file, false, true
139+
return false, errors.configCorrupted\format backup
140+
129141
if "table" != type result
130142
return false, errors.jsonRoot\format type result
131143

0 commit comments

Comments
 (0)