github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/rw/file.go (about)

     1  package rw
     2  
     3  import (
     4  	"encoding/json"
     5  	"io"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/sagernet/sing/common"
    10  )
    11  
    12  func FileExists(path string) bool {
    13  	return common.Error(os.Stat(path)) == nil
    14  }
    15  
    16  func CopyFile(srcPath, dstPath string) error {
    17  	srcFile, err := os.Open(srcPath)
    18  	if err != nil {
    19  		return err
    20  	}
    21  	defer srcFile.Close()
    22  	if strings.Contains(dstPath, "/") {
    23  		parent := dstPath[:strings.LastIndex(dstPath, "/")]
    24  		if !FileExists(parent) {
    25  			err = os.MkdirAll(parent, 0o755)
    26  			if err != nil {
    27  				return err
    28  			}
    29  		}
    30  	}
    31  	dstFile, err := os.Create(dstPath)
    32  	if err != nil {
    33  		return err
    34  	}
    35  	defer dstFile.Close()
    36  	return common.Error(io.Copy(dstFile, srcFile))
    37  }
    38  
    39  func WriteFile(path string, content []byte) error {
    40  	if strings.Contains(path, "/") {
    41  		parent := path[:strings.LastIndex(path, "/")]
    42  		if !FileExists(parent) {
    43  			err := os.MkdirAll(parent, 0o755)
    44  			if err != nil {
    45  				return err
    46  			}
    47  		}
    48  	}
    49  
    50  	file, err := os.Create(path)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	defer file.Close()
    55  	_, err = file.Write(content)
    56  	return err
    57  }
    58  
    59  func ReadJSON(path string, data any) error {
    60  	content, err := os.ReadFile(path)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	err = json.Unmarshal(content, data)
    65  	if err != nil {
    66  		return err
    67  	}
    68  	return nil
    69  }
    70  
    71  func WriteJSON(path string, data any) error {
    72  	content, err := json.Marshal(data)
    73  	if err != nil {
    74  		return err
    75  	}
    76  	return WriteFile(path, content)
    77  }