github.com/number571/tendermint@v0.34.11-gost/libs/os/os.go (about) 1 package os 2 3 import ( 4 "errors" 5 "fmt" 6 "io" 7 "os" 8 "os/signal" 9 "syscall" 10 ) 11 12 type logger interface { 13 Info(msg string, keyvals ...interface{}) 14 } 15 16 // TrapSignal catches SIGTERM and SIGINT, executes the cleanup function, 17 // and exits with code 0. 18 func TrapSignal(logger logger, cb func()) { 19 c := make(chan os.Signal, 1) 20 signal.Notify(c, os.Interrupt, syscall.SIGTERM) 21 22 go func() { 23 sig := <-c 24 logger.Info(fmt.Sprintf("captured %v, exiting...", sig)) 25 if cb != nil { 26 cb() 27 } 28 os.Exit(0) 29 }() 30 } 31 32 func Exit(s string) { 33 fmt.Printf(s + "\n") 34 os.Exit(1) 35 } 36 37 // EnsureDir ensures the given directory exists, creating it if necessary. 38 // Errors if the path already exists as a non-directory. 39 func EnsureDir(dir string, mode os.FileMode) error { 40 err := os.MkdirAll(dir, mode) 41 if err != nil { 42 return fmt.Errorf("could not create directory %q: %w", dir, err) 43 } 44 return nil 45 } 46 47 func FileExists(filePath string) bool { 48 _, err := os.Stat(filePath) 49 return !os.IsNotExist(err) 50 } 51 52 // CopyFile copies a file. It truncates the destination file if it exists. 53 func CopyFile(src, dst string) error { 54 srcfile, err := os.Open(src) 55 if err != nil { 56 return err 57 } 58 defer srcfile.Close() 59 60 info, err := srcfile.Stat() 61 if err != nil { 62 return err 63 } 64 if info.IsDir() { 65 return errors.New("cannot read from directories") 66 } 67 68 // create new file, truncate if exists and apply same permissions as the original one 69 dstfile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode().Perm()) 70 if err != nil { 71 return err 72 } 73 defer dstfile.Close() 74 75 _, err = io.Copy(dstfile, srcfile) 76 return err 77 }