github.com/MetalBlockchain/metalgo@v1.11.9/utils/storage/storage_common.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package storage
     5  
     6  import (
     7  	"errors"
     8  	"fmt"
     9  	"os"
    10  	"path/filepath"
    11  )
    12  
    13  // fileExists checks if a file exists before we
    14  // try using it to prevent further errors.
    15  func FileExists(filePath string) (bool, error) {
    16  	info, err := os.Stat(filePath)
    17  	if err == nil {
    18  		return !info.IsDir(), nil
    19  	}
    20  	if errors.Is(err, os.ErrNotExist) {
    21  		return false, nil
    22  	}
    23  	return false, err
    24  }
    25  
    26  // ReadFileWithName reads a single file with name fileNameWithoutExt without specifying any extension.
    27  // it errors when there are more than 1 file with the given fileName
    28  func ReadFileWithName(parentDir string, fileNameNoExt string) ([]byte, error) {
    29  	filePath := filepath.Join(parentDir, fileNameNoExt)
    30  	files, err := filepath.Glob(filePath + ".*") // all possible extensions
    31  	switch {
    32  	case err != nil:
    33  		return nil, err
    34  	case len(files) > 1:
    35  		return nil, fmt.Errorf(`too many files matched "%s.*" in %s`, fileNameNoExt, parentDir)
    36  	case len(files) == 0:
    37  		// no file found, return nothing
    38  		return nil, nil
    39  	default:
    40  		return os.ReadFile(files[0])
    41  	}
    42  }
    43  
    44  // folderExists checks if a folder exists before we
    45  // try using it to prevent further errors.
    46  func FolderExists(filePath string) (bool, error) {
    47  	info, err := os.Stat(filePath)
    48  	switch {
    49  	case errors.Is(err, os.ErrNotExist):
    50  		return false, nil
    51  	case err != nil:
    52  		return false, err
    53  	default:
    54  		return info.IsDir(), nil
    55  	}
    56  }
    57  
    58  func DirSize(path string) (uint64, error) {
    59  	var size int64
    60  	err := filepath.Walk(path,
    61  		func(_ string, info os.FileInfo, err error) error {
    62  			if err != nil {
    63  				return err
    64  			}
    65  			if !info.IsDir() {
    66  				size += info.Size()
    67  			}
    68  			return nil
    69  		})
    70  	return uint64(size), err
    71  }