github.com/devwanda/aphelion-staking@v0.33.9/libs/os/os.go (about)

     1  package os
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"os/signal"
     8  	"syscall"
     9  )
    10  
    11  type logger interface {
    12  	Info(msg string, keyvals ...interface{})
    13  }
    14  
    15  // TrapSignal catches the SIGTERM/SIGINT and executes cb function. After that it exits
    16  // with code 0.
    17  func TrapSignal(logger logger, cb func()) {
    18  	c := make(chan os.Signal, 1)
    19  	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    20  	go func() {
    21  		for sig := range c {
    22  			logger.Info(fmt.Sprintf("captured %v, exiting...", sig))
    23  			if cb != nil {
    24  				cb()
    25  			}
    26  			os.Exit(0)
    27  		}
    28  	}()
    29  }
    30  
    31  // Kill the running process by sending itself SIGTERM.
    32  func Kill() error {
    33  	p, err := os.FindProcess(os.Getpid())
    34  	if err != nil {
    35  		return err
    36  	}
    37  	return p.Signal(syscall.SIGTERM)
    38  }
    39  
    40  func Exit(s string) {
    41  	fmt.Printf(s + "\n")
    42  	os.Exit(1)
    43  }
    44  
    45  func EnsureDir(dir string, mode os.FileMode) error {
    46  	if _, err := os.Stat(dir); os.IsNotExist(err) {
    47  		err := os.MkdirAll(dir, mode)
    48  		if err != nil {
    49  			return fmt.Errorf("could not create directory %v: %w", dir, err)
    50  		}
    51  	}
    52  	return nil
    53  }
    54  
    55  func FileExists(filePath string) bool {
    56  	_, err := os.Stat(filePath)
    57  	return !os.IsNotExist(err)
    58  }
    59  
    60  func ReadFile(filePath string) ([]byte, error) {
    61  	return ioutil.ReadFile(filePath)
    62  }
    63  
    64  func MustReadFile(filePath string) []byte {
    65  	fileBytes, err := ioutil.ReadFile(filePath)
    66  	if err != nil {
    67  		Exit(fmt.Sprintf("MustReadFile failed: %v", err))
    68  		return nil
    69  	}
    70  	return fileBytes
    71  }
    72  
    73  func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
    74  	return ioutil.WriteFile(filePath, contents, mode)
    75  }
    76  
    77  func MustWriteFile(filePath string, contents []byte, mode os.FileMode) {
    78  	err := WriteFile(filePath, contents, mode)
    79  	if err != nil {
    80  		Exit(fmt.Sprintf("MustWriteFile failed: %v", err))
    81  	}
    82  }