gobot.io/x/gobot/v2@v2.1.0/system/fs.go (about)

     1  package system
     2  
     3  import (
     4  	"os"
     5  	"path"
     6  	"regexp"
     7  )
     8  
     9  // nativeFilesystem represents the native file system implementation
    10  type nativeFilesystem struct{}
    11  
    12  // openFile calls os.OpenFile().
    13  func (fs *nativeFilesystem) openFile(name string, flag int, perm os.FileMode) (file File, err error) {
    14  	return os.OpenFile(name, flag, perm)
    15  }
    16  
    17  // stat calls os.Stat()
    18  func (fs *nativeFilesystem) stat(name string) (os.FileInfo, error) {
    19  	return os.Stat(name)
    20  }
    21  
    22  // find returns all items (files or folders) below the given directory matching the given pattern.
    23  func (fs *nativeFilesystem) find(baseDir string, pattern string) ([]string, error) {
    24  	reg, err := regexp.Compile(pattern)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	items, err := os.ReadDir(baseDir)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  
    34  	var found []string
    35  	for _, item := range items {
    36  		if reg.MatchString(item.Name()) {
    37  			found = append(found, path.Join(baseDir, item.Name()))
    38  
    39  		}
    40  	}
    41  	return found, nil
    42  }
    43  
    44  // readFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF.
    45  // Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.
    46  func (fs *nativeFilesystem) readFile(name string) ([]byte, error) {
    47  	return os.ReadFile(name)
    48  }