github.com/pavlo67/common@v0.5.3/common/filelib/search.go (about)

     1  package filelib
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"regexp"
     8  	"slices"
     9  
    10  	"github.com/pavlo67/common/common/errors"
    11  )
    12  
    13  const onSearch = "on filelib.Search()"
    14  
    15  func Search(path string, re regexp.Regexp, getFirst bool) ([]string, error) {
    16  	dirEntries, err := os.ReadDir(path)
    17  	if err != nil {
    18  		return nil, errors.Wrap(err, onSearch)
    19  	}
    20  
    21  	names := make([]string, len(dirEntries))
    22  	for i, dirEntry := range dirEntries {
    23  		names[i] = dirEntry.Name()
    24  	}
    25  
    26  	slices.Sort(names)
    27  	// sort.Slice(names, func(i, j int) bool { return names[i] < names[j] })
    28  
    29  	var matches []string
    30  	for _, name := range names {
    31  		if matches = re.FindStringSubmatch(name); getFirst && len(matches) > 0 {
    32  			return matches, nil
    33  		}
    34  	}
    35  
    36  	return matches, nil
    37  }
    38  
    39  const onList = "on filelib.List()"
    40  
    41  func List(path string, re *regexp.Regexp, getDirs, getFiles bool) ([]string, error) {
    42  	dirEntries, err := os.ReadDir(path)
    43  	if err != nil {
    44  		return nil, errors.Wrap(err, onList)
    45  	}
    46  
    47  	var names []string
    48  	for _, dirEntry := range dirEntries {
    49  		if (dirEntry.IsDir() && !getDirs) || (!dirEntry.IsDir() && !getFiles) {
    50  			continue
    51  		}
    52  		names = append(names, dirEntry.Name())
    53  	}
    54  
    55  	slices.Sort(names)
    56  
    57  	var namesListed []string
    58  	for _, name := range names {
    59  		if re == nil || re.MatchString(name) {
    60  			namesListed = append(namesListed, filepath.Join(path, name))
    61  		}
    62  	}
    63  
    64  	return namesListed, nil
    65  }
    66  
    67  const onFileExists = "on filelib.FileExists()"
    68  
    69  func FileExists(path string, isDir bool) (bool, error) {
    70  	fileInfo, _ := os.Stat(path)
    71  	if fileInfo == nil {
    72  		return false, nil
    73  	}
    74  
    75  	if fileInfo.IsDir() {
    76  		if isDir {
    77  			return true, nil
    78  		}
    79  		return false, fmt.Errorf("%s is not a directory / "+onFileExists, path)
    80  	}
    81  
    82  	if isDir {
    83  		return false, fmt.Errorf("%s is a directory / "+onFileExists, path)
    84  	}
    85  
    86  	return true, nil
    87  }
    88  
    89  const onFileExistsAny = "on filelib.FileExistsAny()"
    90  
    91  func FileExistsAny(path string) (exists, isDir bool) {
    92  	fileInfo, _ := os.Stat(path)
    93  	if fileInfo == nil {
    94  		return false, false
    95  	}
    96  
    97  	return true, fileInfo.IsDir()
    98  }