github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/file.go (about)

     1  package utils
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"gopkg.in/yaml.v3"
     9  )
    10  
    11  func GetExecDir() string {
    12  	execDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    13  	if err != nil {
    14  		return ""
    15  	}
    16  
    17  	return execDir
    18  }
    19  
    20  func GetExecName() string {
    21  	return filepath.Base(os.Args[0])
    22  }
    23  
    24  func CopyFile(srcFile, dstFile string) error {
    25  	const bufferSize = 1024 * 1024
    26  	buf := make([]byte, bufferSize)
    27  
    28  	return CopyFileWithBuffer(srcFile, dstFile, buf)
    29  }
    30  
    31  func CopyFileWithBuffer(srcFile, dstFile string, buf []byte) error {
    32  	src, err := os.Open(srcFile)
    33  	if err != nil {
    34  		return err
    35  	}
    36  	defer func(src *os.File) {
    37  		_ = src.Close()
    38  	}(src)
    39  	dst, err := os.Create(dstFile)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	defer func(dst *os.File) {
    44  		_ = dst.Close()
    45  	}(dst)
    46  
    47  	for {
    48  		n, err := src.Read(buf)
    49  		if err != nil && err != io.EOF {
    50  			return err
    51  		}
    52  		if n == 0 {
    53  			break
    54  		}
    55  
    56  		if _, err := dst.Write(buf[:n]); err != nil {
    57  			return err
    58  		}
    59  	}
    60  
    61  	return nil
    62  }
    63  
    64  func WriteYamlFile(filePath string, data any) error {
    65  	f, err := os.Create(filePath)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	defer func(f *os.File) {
    70  		_ = f.Close()
    71  	}(f)
    72  
    73  	enc := yaml.NewEncoder(f)
    74  	err = enc.Encode(data)
    75  	if err != nil {
    76  		return err
    77  	}
    78  
    79  	return enc.Close()
    80  }
    81  
    82  func ReadYamlFile(filePath string, data any) error {
    83  	f, err := os.Open(filePath)
    84  	if err != nil {
    85  		return err
    86  	}
    87  	defer func(f *os.File) {
    88  		_ = f.Close()
    89  	}(f)
    90  
    91  	dec := yaml.NewDecoder(f)
    92  
    93  	return dec.Decode(data)
    94  }