@@ -222,36 +222,51 @@ func RemoveRepository(repo *Repository, configFolderPath string) error {
222222 }
223223
224224 // Create the new version of the file
225- f , err := os .OpenFile (fileToFilter + ".new" , os .O_CREATE | os .O_WRONLY , 0644 )
226- if err != nil {
227- return fmt .Errorf ("Writing of new config %s: %s" , fileToFilter + ".new" , err )
228- }
229225 scanner := bufio .NewScanner (bytes .NewReader (data ))
226+ newContent := ""
230227 for scanner .Scan () {
231228 line := scanner .Text ()
232229 r := parseAPTConfigLine (line )
233230 if r .Equals (repo ) {
234231 // Filter repo configs that match the repo to be removed
235232 continue
236233 }
237- f .WriteString (line + "\n " )
234+ newContent += line + "\n "
235+ }
236+
237+ err = replaceFile (fileToFilter , []byte (newContent ))
238+ if err != nil {
239+ return fmt .Errorf ("Writing of new config: %s" , err )
240+ }
241+
242+ return nil
243+ }
244+
245+ func replaceFile (path string , newContent []byte ) error {
246+ newPath := path + ".new"
247+ backupPath := path + ".save"
248+
249+ // Create the new version of the file
250+ err := ioutil .WriteFile (newPath , newContent , 0644 )
251+ if err != nil {
252+ return fmt .Errorf ("Creating replacement file for %s: %s" , newPath , err )
238253 }
239- f .Close ()
240- // In case of error clean-up the .new copy
241- defer os .Remove (fileToFilter + ".new" )
242254
243- // Rename .list to .list.save
244- err = os .Rename (fileToFilter , fileToFilter + ".save" )
255+ // Only in case of error clean-up the new copy (otherwise ignore the error...)
256+ defer os .Remove (newPath )
257+
258+ // Make a backup copy
259+ err = os .Rename (path , backupPath )
245260 if err != nil {
246- return fmt .Errorf ("Making backup copy of %s: %s" , fileToFilter , err )
261+ return fmt .Errorf ("Making backup copy of %s: %s" , path , err )
247262 }
248263
249- // Rename .list. new to .list
250- err = os .Rename (fileToFilter + ".new" , fileToFilter )
264+ // Rename the new copy to the final path
265+ err = os .Rename (newPath , path )
251266 if err != nil {
252- // Try to rollback change ...
253- os .Rename (fileToFilter + ".save" , fileToFilter )
254- return fmt .Errorf ("Renaming %s to %s: %s" , fileToFilter + ".new" , fileToFilter , err )
267+ // Something went wrong ... try to rollback the backup
268+ os .Rename (backupPath , path )
269+ return fmt .Errorf ("Renaming %s to %s: %s" , newPath , path , err )
255270 }
256271
257272 return nil
0 commit comments