github.com/osdi23p228/fabric@v0.0.0-20221218062954-77808885f5db/internal/fileutil/fileutil.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package fileutil
     8  
     9  import (
    10  	"io/ioutil"
    11  	"os"
    12  	"path/filepath"
    13  
    14  	"github.com/pkg/errors"
    15  )
    16  
    17  // RemoveContents removes all the files and subdirs under the specified directory.
    18  // It returns nil if the specified directory does not exist.
    19  func RemoveContents(dir string) error {
    20  	contents, err := ioutil.ReadDir(dir)
    21  	if os.IsNotExist(err) {
    22  		return nil
    23  	}
    24  	if err != nil {
    25  		return errors.Wrapf(err, "error reading directory %s", dir)
    26  	}
    27  
    28  	for _, c := range contents {
    29  		if err = os.RemoveAll(filepath.Join(dir, c.Name())); err != nil {
    30  			return errors.Wrapf(err, "error removing %s under directory %s", c.Name(), dir)
    31  		}
    32  	}
    33  	return syncDir(dir)
    34  }
    35  
    36  // SyncDir fsyncs the given dir
    37  func syncDir(dirPath string) error {
    38  	dir, err := os.Open(dirPath)
    39  	if err != nil {
    40  		return errors.Wrapf(err, "error while opening dir:%s", dirPath)
    41  	}
    42  	if err := dir.Sync(); err != nil {
    43  		dir.Close()
    44  		return errors.Wrapf(err, "error while synching dir:%s", dirPath)
    45  	}
    46  	if err := dir.Close(); err != nil {
    47  		return errors.Wrapf(err, "error while closing dir:%s", dirPath)
    48  	}
    49  	return err
    50  }