github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/os/os.go (about)

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