github.com/scottcagno/storage@v1.8.0/pkg/util/filepath.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"runtime"
     8  )
     9  
    10  // GetFilepath returns the absolute filepath from where it's called. It returns the
    11  // result as a split string, first the root directory up until the current file and
    12  // returns the two in this order: dir, file
    13  func GetFilepath() (string, string) {
    14  	// Caller reports file and line number information about function invocations on
    15  	// the calling goroutine's stack. The argument skip is the number of stack frames
    16  	// to ascend, with 0 identifying the caller of Caller.
    17  	_, filename, _, ok := runtime.Caller(1)
    18  	if !ok {
    19  		return "", ""
    20  	}
    21  	// clean and split the filepath
    22  	return filepath.Split(filepath.Clean(filename))
    23  }
    24  
    25  func CreateBaseDir(base string) error {
    26  	base, err := filepath.Abs(base)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	base = filepath.ToSlash(base)
    31  	err = os.MkdirAll(base, os.ModeDir)
    32  	if err != nil {
    33  		return err
    34  	}
    35  	return nil
    36  }
    37  
    38  func UpdateBaseDir(base string) (string, error) {
    39  	base, err := filepath.Abs(base)
    40  	if err != nil {
    41  		return "", err
    42  	}
    43  	base = filepath.ToSlash(base)
    44  	files, err := os.ReadDir(base)
    45  	if err != nil {
    46  		return "", err
    47  	}
    48  	base = filepath.Join(base, fmt.Sprintf("%06d", len(files)))
    49  	_, err = os.Stat(base)
    50  	if os.IsExist(err) {
    51  		return "", nil
    52  	}
    53  	err = os.MkdirAll(base, os.ModeDir)
    54  	if err != nil {
    55  		return "", err
    56  	}
    57  	return base, err
    58  }
    59  
    60  func exists(path string) (bool, error) {
    61  	_, err := os.Stat(path)
    62  	if err == nil {
    63  		return true, nil
    64  	}
    65  	if os.IsNotExist(err) {
    66  		return false, nil
    67  	}
    68  	return true, err
    69  }