github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/osx/file.go (about)

     1  package osx
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/bingoohuang/gg/pkg/gz"
    10  )
    11  
    12  func Remove(f string) {
    13  	if err := os.Remove(f); err != nil {
    14  		log.Printf("E! remove %s failed: %v", f, err)
    15  	}
    16  }
    17  
    18  type ReadFileConfig struct {
    19  	AutoUncompress bool
    20  	FatalOnError   bool
    21  }
    22  
    23  type ReadFileResult struct {
    24  	Data []byte
    25  	Err  error
    26  }
    27  
    28  func (r ReadFileResult) OK() bool { return r.Err == nil }
    29  
    30  // ReadFile reads a file content, if it's a .gz, decompress it.
    31  func ReadFile(filename string, fns ...ReadFileConfigFn) (rr ReadFileResult) {
    32  	config := (ReadFileConfigFns(fns)).Create()
    33  
    34  	defer func() {
    35  		if config.FatalOnError && rr.Err != nil {
    36  			log.Fatal(rr.Err)
    37  		}
    38  	}()
    39  
    40  	data, err := os.ReadFile(ExpandHome(filename))
    41  	if err != nil {
    42  		rr.Err = fmt.Errorf("read file %s failed: %w", filename, err)
    43  		return rr
    44  	}
    45  
    46  	if config.AutoUncompress && strings.HasSuffix(filename, ".gz") {
    47  		if data, err = gz.Ungzip(data); err != nil {
    48  			rr.Err = fmt.Errorf("Ungzip file %s failed: %w", filename, err)
    49  			return rr
    50  		}
    51  	}
    52  
    53  	return ReadFileResult{Data: data}
    54  }
    55  
    56  type ReadFileConfigFn func(*ReadFileConfig)
    57  
    58  func WithFatalOnError(v bool) ReadFileConfigFn {
    59  	return func(config *ReadFileConfig) {
    60  		config.FatalOnError = v
    61  	}
    62  }
    63  
    64  func WithAutoUncompress(v bool) ReadFileConfigFn {
    65  	return func(config *ReadFileConfig) {
    66  		config.AutoUncompress = v
    67  	}
    68  }
    69  
    70  type ReadFileConfigFns []ReadFileConfigFn
    71  
    72  func (fns ReadFileConfigFns) Create() (config ReadFileConfig) {
    73  	for _, fn := range fns {
    74  		fn(&config)
    75  	}
    76  
    77  	return config
    78  }