github.com/igggame/nebulas-go@v2.1.0+incompatible/util/file.go (about)

     1  // Copyright (C) 2017 go-nebulas authors
     2  //
     3  // This file is part of the go-nebulas library.
     4  //
     5  // the go-nebulas library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // the go-nebulas library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU General Public License
    16  // along with the go-nebulas library.  If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  
    19  package util
    20  
    21  import (
    22  	"errors"
    23  	"io/ioutil"
    24  	"os"
    25  	"path/filepath"
    26  )
    27  
    28  var (
    29  	// ErrFileExists file exists
    30  	ErrFileExists = errors.New("file exists")
    31  )
    32  
    33  // CreateDirIfNotExist create dir
    34  func CreateDirIfNotExist(dir string) error {
    35  	if exist, err := FileExists(dir); !exist || err != nil {
    36  		if err != nil {
    37  			return err
    38  		}
    39  		err = os.MkdirAll(dir, os.ModeDir|os.ModePerm)
    40  		if err != nil {
    41  			return err
    42  		}
    43  	}
    44  	return nil
    45  }
    46  
    47  // FileExists check file exists
    48  func FileExists(path string) (bool, error) {
    49  	_, err := os.Stat(path)
    50  	if err == nil {
    51  		return true, nil
    52  	}
    53  	if os.IsNotExist(err) {
    54  		return false, nil
    55  	}
    56  	return true, err
    57  }
    58  
    59  // FileWrite write file to path
    60  func FileWrite(file string, content []byte, overwrite bool) error {
    61  	// Create the keystore directory with appropriate permissions
    62  	if err := CreateDirIfNotExist(filepath.Dir(file)); err != nil {
    63  		return err
    64  	}
    65  	f, err := ioutil.TempFile(filepath.Dir(file), "."+filepath.Base(file)+".tmp")
    66  	if err != nil {
    67  		return err
    68  	}
    69  	if _, err := f.Write(content); err != nil {
    70  		f.Close()
    71  		os.Remove(f.Name())
    72  		return err
    73  	}
    74  	f.Close()
    75  
    76  	if overwrite {
    77  		if exist, _ := FileExists(file); exist {
    78  			if err := os.Remove(file); err != nil {
    79  				os.Remove(f.Name())
    80  				return err
    81  			}
    82  		}
    83  	}
    84  
    85  	return os.Rename(f.Name(), file)
    86  }