X-Git-Url: https://ruderich.org/simon/gitweb/?p=nsscash%2Fnsscash.git;a=blobdiff_plain;f=main.go;h=7a7d8b0da8e6855b8545c609f6169184819db7ae;hp=a563b511355273983d0a0ea3060a288ad64e456d;hb=HEAD;hpb=78239472f30846add39a4f14455cc92aba8ea79b diff --git a/main.go b/main.go index a563b51..7a7d8b0 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,6 @@ // Main file for nsscash -// Copyright (C) 2019 Simon Ruderich +// Copyright (C) 2019-2021 Simon Ruderich // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by @@ -24,6 +24,9 @@ import ( "io/ioutil" "log" "os" + "path/filepath" + + "github.com/google/renameio" ) func main() { @@ -129,21 +132,28 @@ func mainConvert(typ, srcPath, dstPath string) error { return fmt.Errorf("unsupported file type %v", t) } - // We must create the file first or deployFile() will abort - f, err := os.Create(dstPath) + // We must create the file first or deployFile() will abort; this is + // ugly because deployFile() already performs an atomic replacement + // but the simplest solution with the least duplicate code + f, err := renameio.TempFile(filepath.Dir(dstPath), dstPath) if err != nil { return err } - f.Close() + defer f.Cleanup() err = deployFile(&File{ Type: t, Url: srcPath, - Path: dstPath, + Path: f.Name(), body: x.Bytes(), }) if err != nil { return err } - return nil + + err = f.CloseAtomicallyReplace() + if err != nil { + return err + } + return syncPath(filepath.Dir(dstPath)) }