github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/util/file.go (about)

     1  package util
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"os"
     7  	"path"
     8  )
     9  
    10  // PathExist check if the directory or file exists.
    11  func PathExist(path string) bool {
    12  	if _, err := os.Stat(path); os.IsNotExist(err) {
    13  		return false
    14  	}
    15  	return true
    16  }
    17  
    18  // CopyDir copy directory from src to dst.
    19  func CopyDir(src string, dst string) error {
    20  	var (
    21  		err     error
    22  		dir     []os.FileInfo
    23  		srcInfo os.FileInfo
    24  	)
    25  
    26  	if srcInfo, err = os.Stat(src); err != nil {
    27  		return err
    28  	}
    29  	if err = os.MkdirAll(dst, srcInfo.Mode()); err != nil {
    30  		return err
    31  	}
    32  	if dir, err = ioutil.ReadDir(src); err != nil {
    33  		return err
    34  	}
    35  
    36  	for _, fd := range dir {
    37  		srcPath := path.Join(src, fd.Name())
    38  		dstPath := path.Join(dst, fd.Name())
    39  
    40  		if fd.IsDir() {
    41  			if err = CopyDir(srcPath, dstPath); err != nil {
    42  				return err
    43  			}
    44  		} else {
    45  			if err = CopyFile(srcPath, dstPath); err != nil {
    46  				return err
    47  			}
    48  		}
    49  	}
    50  
    51  	return nil
    52  }
    53  
    54  // CopyFile copy a single file.
    55  func CopyFile(src, dst string) error {
    56  	var (
    57  		err     error
    58  		srcFile *os.File
    59  		dstFie  *os.File
    60  		srcInfo os.FileInfo
    61  	)
    62  
    63  	if srcFile, err = os.Open(src); err != nil {
    64  		return err
    65  	}
    66  	defer srcFile.Close()
    67  
    68  	if dstFie, err = os.Create(dst); err != nil {
    69  		return err
    70  	}
    71  	defer dstFie.Close()
    72  
    73  	if _, err = io.Copy(dstFie, srcFile); err != nil {
    74  		return err
    75  	}
    76  
    77  	if srcInfo, err = os.Stat(src); err != nil {
    78  		return err
    79  	}
    80  
    81  	return os.Chmod(dst, srcInfo.Mode())
    82  }