gitlab.com/gpdionisio/tendermint@v0.34.19-dev2/libs/os/os.go (about) 1 package os 2 3 import ( 4 "errors" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "os" 9 "os/signal" 10 "syscall" 11 ) 12 13 type logger interface { 14 Info(msg string, keyvals ...interface{}) 15 } 16 17 // TrapSignal catches the SIGTERM/SIGINT and executes cb function. After that it exits 18 // with code 0. 19 func TrapSignal(logger logger, cb func()) { 20 c := make(chan os.Signal, 1) 21 signal.Notify(c, os.Interrupt, syscall.SIGTERM) 22 go func() { 23 for sig := range 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 33 // Kill the running process by sending itself SIGTERM. 34 func Kill() error { 35 p, err := os.FindProcess(os.Getpid()) 36 if err != nil { 37 return err 38 } 39 return p.Signal(syscall.SIGTERM) 40 } 41 42 func Exit(s string) { 43 fmt.Printf(s + "\n") 44 os.Exit(1) 45 } 46 47 // EnsureDir ensures the given directory exists, creating it if necessary. 48 // Errors if the path already exists as a non-directory. 49 func EnsureDir(dir string, mode os.FileMode) error { 50 err := os.MkdirAll(dir, mode) 51 if err != nil { 52 return fmt.Errorf("could not create directory %q: %w", dir, err) 53 } 54 return nil 55 } 56 57 func FileExists(filePath string) bool { 58 _, err := os.Stat(filePath) 59 return !os.IsNotExist(err) 60 } 61 62 func ReadFile(filePath string) ([]byte, error) { 63 return ioutil.ReadFile(filePath) 64 } 65 66 func MustReadFile(filePath string) []byte { 67 fileBytes, err := ioutil.ReadFile(filePath) 68 if err != nil { 69 Exit(fmt.Sprintf("MustReadFile failed: %v", err)) 70 return nil 71 } 72 return fileBytes 73 } 74 75 func WriteFile(filePath string, contents []byte, mode os.FileMode) error { 76 return ioutil.WriteFile(filePath, contents, mode) 77 } 78 79 func MustWriteFile(filePath string, contents []byte, mode os.FileMode) { 80 err := WriteFile(filePath, contents, mode) 81 if err != nil { 82 Exit(fmt.Sprintf("MustWriteFile failed: %v", err)) 83 } 84 } 85 86 // CopyFile copies a file. It truncates the destination file if it exists. 87 func CopyFile(src, dst string) error { 88 srcfile, err := os.Open(src) 89 if err != nil { 90 return err 91 } 92 defer srcfile.Close() 93 94 info, err := srcfile.Stat() 95 if err != nil { 96 return err 97 } 98 if info.IsDir() { 99 return errors.New("cannot read from directories") 100 } 101 102 // create new file, truncate if exists and apply same permissions as the original one 103 dstfile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode().Perm()) 104 if err != nil { 105 return err 106 } 107 defer dstfile.Close() 108 109 _, err = io.Copy(dstfile, srcfile) 110 return err 111 }