github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/common/file.go (about) 1 // Copyright (C) 2017 go-nebulas authors 2 // 3 // This file is part of the go-nebulas library. 4 // 5 // the go-nebulas library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // the go-nebulas library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 19 package common 20 21 import ( 22 "errors" 23 "fmt" 24 "io/ioutil" 25 "os" 26 "path/filepath" 27 "strings" 28 ) 29 30 var ( 31 // ErrFileExists file exists 32 ErrFileExists = errors.New("file exists") 33 ) 34 35 // FileExists check file exists 36 func FileExists(path string) (bool, error) { 37 _, err := os.Stat(path) 38 if err == nil { 39 return true, nil 40 } 41 if os.IsNotExist(err) { 42 return false, nil 43 } 44 return true, err 45 } 46 47 // FileWrite write file to path 48 func FileWrite(file string, content []byte, overwrite bool) error { 49 if strings.Contains(file, "ct0111111111111111111111") { 50 fmt.Printf("jjjsls") 51 } 52 // Create the keystore directory with appropriate permissions 53 const dirPerm = 0700 54 if err := os.MkdirAll(filepath.Dir(file), dirPerm); err != nil { 55 return err 56 } 57 f, err := ioutil.TempFile(filepath.Dir(file), "."+filepath.Base(file)+".tmp") 58 if err != nil { 59 return err 60 } 61 if _, err := f.Write(content); err != nil { 62 f.Close() 63 os.Remove(f.Name()) 64 return err 65 } 66 f.Close() 67 68 if overwrite { 69 if exist, _ := FileExists(file); exist { 70 if err := os.Remove(file); err != nil { 71 os.Remove(f.Name()) 72 return err 73 } 74 } 75 } 76 77 return os.Rename(f.Name(), file) 78 }