github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/storage/file_util.go (about) 1 // Copyright 2019 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package storage 12 13 import ( 14 "bytes" 15 "fmt" 16 "io" 17 18 "github.com/cockroachdb/pebble/vfs" 19 ) 20 21 // SafeWriteToFile writes the byte slice to the filename, contained in dir, using the given fs. 22 // It returns after both the file and the containing directory are synced. 23 func SafeWriteToFile(fs vfs.FS, dir string, filename string, b []byte) error { 24 tempName := filename + ".crdbtmp" 25 f, err := fs.Create(tempName) 26 if err != nil { 27 fmt.Printf("%v\n", err) 28 return err 29 } 30 bReader := bytes.NewReader(b) 31 if _, err = io.Copy(f, bReader); err != nil { 32 f.Close() 33 return err 34 } 35 if err = f.Close(); err != nil { 36 return err 37 } 38 if err = fs.Rename(tempName, filename); err != nil { 39 return err 40 } 41 fdir, err := fs.OpenDir(dir) 42 if err != nil { 43 return err 44 } 45 defer fdir.Close() 46 return fdir.Sync() 47 }