github.com/turingchain2020/turingchain@v1.1.21/cmd/tools/util/system.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package util util turingchain基础功能函数实现
     6  package util
     7  
     8  import (
     9  	"io"
    10  	"os"
    11  	"path/filepath"
    12  )
    13  
    14  // DirExists : 检查文件夹是否存在
    15  func DirExists(path string) (bool, error) {
    16  	_, err := os.Stat(path)
    17  	if err == nil {
    18  		return true, nil
    19  	}
    20  	if os.IsNotExist(err) {
    21  		return false, nil
    22  	}
    23  	return false, err
    24  }
    25  
    26  //CheckPathExisted : check the path exists or not
    27  func CheckPathExisted(path string) bool {
    28  	existed, _ := DirExists(path)
    29  	return existed
    30  }
    31  
    32  //CheckFileExists : check file exists or not
    33  func CheckFileExists(fileName string) (bool, error) {
    34  	if _, err := os.Stat(fileName); os.IsNotExist(err) {
    35  		return false, err
    36  	}
    37  	return true, nil
    38  }
    39  
    40  //DeleteFile : delete the file
    41  func DeleteFile(fileName string) error {
    42  	if existed, _ := CheckFileExists(fileName); existed {
    43  		return os.Remove(fileName)
    44  	}
    45  	return nil
    46  }
    47  
    48  //OpenFile : OpenFile
    49  func OpenFile(fileName string) (*os.File, error) {
    50  	var file *os.File
    51  	var err error
    52  	if existed, _ := CheckFileExists(fileName); !existed {
    53  		file, err = os.Create(fileName)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  	} else {
    58  		file, err = os.OpenFile(fileName, os.O_RDWR, os.ModePerm)
    59  		if err != nil {
    60  			return nil, err
    61  		}
    62  	}
    63  	return file, nil
    64  }
    65  
    66  //MakeDir : MakeDir
    67  func MakeDir(path string) error {
    68  	dir := filepath.Dir(path)
    69  	return os.MkdirAll(dir, os.ModePerm)
    70  }
    71  
    72  //Pwd : Pwd
    73  func Pwd() string {
    74  	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    75  	if err != nil {
    76  		panic(err)
    77  	}
    78  	return dir
    79  }
    80  
    81  //DirEmpty : DirEmpty
    82  func DirEmpty(path string) (bool, error) {
    83  	f, err := os.Open(path)
    84  	if err != nil {
    85  		return false, err
    86  	}
    87  	defer f.Close()
    88  
    89  	_, err = f.Readdir(1)
    90  	if err == io.EOF {
    91  		return true, nil
    92  	}
    93  	return false, err
    94  }