159159
160160
161161function LHS :writeAll ()
162- local file = NFS .newFile (self .path )
163- local success ,err = file :open (" w" )
164- if not success then error (err ) end
165- self .saveHandle = file
166-
167162 self :writeHeaders ()
168163
169164 self :writeSingle (" singleForeground" )
@@ -181,11 +176,80 @@ function LHS:writeAll()
181176 self :writeSingle (" singleBackground" )
182177 self :writeStructure (" backgroundRows" )
183178 self :writeStructure (" backgroundColumns" )
184- local hash = self :writeHash ()
179+ local hash = self :writeHash ()
180+ return hash
181+ end
182+
183+ function LHS :writeDirectly ()
184+ local file = NFS .newFile (self .path )
185+ local success ,err = file :open (" w" )
186+ if not success then error (err ) end
187+ self .saveHandle = file
188+
189+ local hash = self :writeAll ()
185190
186191 self .saveHandle :close ()
187192 self .saveHandle = nil
188193 return hash
189194end
190195
196+ function LHS :writeWithBackup ()
197+ local basePath , file = self .path :match (" ^(.+)[/\\ ]([^/\\ ]*)$" )
198+ if not basePath or not file then
199+ error (" Failed getting directory path" , 2 )
200+ end
201+ local r = string.format (" %06i" , love .math .random (0 ,999999 ))
202+ local backupPath = basePath .. " /" .. " ch-backup-" .. r .. " -" .. file
203+ local _success , err = os.rename (self .path , backupPath )
204+ if err then
205+ error (string.format (" Error moving\n %s\n to\n %s\n %s" ,self .path ,backupPath ,err ),2 )
206+ end
207+ table.insert (self .tempFiles , backupPath )
208+
209+ local hash = self :writeDirectly ()
210+
211+ local checker = self .class :new (self .path )
212+ local success , err = xpcall (function ()
213+ checker :readAll ()
214+ end , function (message )
215+ message = tostring (message )
216+ -- part of snippet yoinked from default löve error handling
217+ local fullTrace = debug.traceback (" " ,2 ):gsub (" \n [^\n ]+$" , " " )
218+ print (message )
219+ print (fullTrace )
220+ -- cut of the part of the trace that goes into the code that calls UI:openEditor()
221+ local index = fullTrace :find (" %s+%[C%]: in function 'xpcall'" )
222+ local trace = fullTrace :sub (1 ,index - 1 )
223+ return {message , trace }
224+ end )
225+ if not success then
226+ error (string.format (
227+ " Verification of written level failed: %s\n Backup of old level should live at: %s\n %s" ,
228+ err [1 ],
229+ backupPath ,
230+ err [2 ]
231+ ),2 )
232+ end
233+
234+ local success , err = NFS .remove (backupPath )
235+ if not success then
236+ error (string.format (
237+ " Error removing backup at %s:\n %s" ,
238+ backupPath ,
239+ err
240+ ))
241+ end
242+
243+ local index = - 1
244+ for i ,v in ipairs (self .tempFiles ) do
245+ if v == backupPath then
246+ index = i
247+ break
248+ end
249+ end
250+ table.remove (self .tempFiles ,index )
251+
252+ return hash
253+ end
254+
191255return LHS
0 commit comments