src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/must/must.go (about)

     1  // Package must contains simple functions that panic on errors.
     2  //
     3  // It should only be used in tests and rare places where errors are provably
     4  // impossible.
     5  package must
     6  
     7  import (
     8  	"io"
     9  	"os"
    10  	"path/filepath"
    11  )
    12  
    13  // OK panics if the error value is not nil. It is intended for use with
    14  // functions that return just an error.
    15  func OK(err error) {
    16  	if err != nil {
    17  		panic(err)
    18  	}
    19  }
    20  
    21  // OK1 panics if the error value is not nil. It is intended for use with
    22  // functions that return one value and an error.
    23  func OK1[T any](v T, err error) T {
    24  	if err != nil {
    25  		panic(err)
    26  	}
    27  	return v
    28  }
    29  
    30  // OK2 panics if the error value is not nil. It is intended for use with
    31  // functions that return two values and an error.
    32  func OK2[T1, T2 any](v1 T1, v2 T2, err error) (T1, T2) {
    33  	if err != nil {
    34  		panic(err)
    35  	}
    36  	return v1, v2
    37  }
    38  
    39  // Pipe wraps os.Pipe.
    40  func Pipe() (*os.File, *os.File) {
    41  	return OK2(os.Pipe())
    42  }
    43  
    44  // Chdir wraps os.Chdir.
    45  func Chdir(dir string) {
    46  	OK(os.Chdir(dir))
    47  }
    48  
    49  // ReadAll wraps io.ReadAll and io.Closer.Close.
    50  func ReadAllAndClose(r io.ReadCloser) []byte {
    51  	v := OK1(io.ReadAll(r))
    52  	OK(r.Close())
    53  	return v
    54  }
    55  
    56  // ReadFile wraps os.ReadFile.
    57  func ReadFile(fname string) []byte {
    58  	return OK1(os.ReadFile(fname))
    59  }
    60  
    61  // ReadFileString converts the result of ReadFile to a string.
    62  func ReadFileString(fname string) string {
    63  	return string(ReadFile(fname))
    64  }
    65  
    66  // MkdirAll calls os.MkdirAll for each argument.
    67  func MkdirAll(names ...string) {
    68  	for _, name := range names {
    69  		OK(os.MkdirAll(name, 0700))
    70  	}
    71  }
    72  
    73  // CreateEmpty creates empty file, after creating all ancestor directories that
    74  // don't exist.
    75  func CreateEmpty(names ...string) {
    76  	for _, name := range names {
    77  		OK(os.MkdirAll(filepath.Dir(name), 0700))
    78  		file := OK1(os.Create(name))
    79  		OK(file.Close())
    80  	}
    81  }
    82  
    83  // WriteFile writes data to a file, after creating all ancestor directories that
    84  // don't exist.
    85  func WriteFile(filename, data string) {
    86  	OK(os.MkdirAll(filepath.Dir(filename), 0700))
    87  	OK(os.WriteFile(filename, []byte(data), 0600))
    88  }