github.com/puellanivis/breton@v0.2.16/lib/files/open.go (about)

     1  package files
     2  
     3  import (
     4  	"context"
     5  	"io/ioutil"
     6  	"net/url"
     7  	"os"
     8  	"path/filepath"
     9  )
    10  
    11  // Open returns a files.Reader, which can be used to read content from the resource at the given URL.
    12  //
    13  // All errors and reversion functions returned by Option arguments are discarded.
    14  func Open(ctx context.Context, url string, options ...Option) (Reader, error) {
    15  	f, err := open(ctx, url)
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  
    20  	for _, opt := range options {
    21  		_, _ = opt(f)
    22  	}
    23  
    24  	return f, nil
    25  }
    26  
    27  func open(ctx context.Context, resource string) (Reader, error) {
    28  	switch resource {
    29  	case "", "-", "/dev/stdin":
    30  		return os.Stdin, nil
    31  	}
    32  
    33  	if filepath.IsAbs(resource) {
    34  		return os.Open(resource)
    35  	}
    36  
    37  	if uri, err := url.Parse(resource); err == nil {
    38  		uri = resolveFilename(ctx, uri)
    39  
    40  		if fs, ok := getFS(uri); ok {
    41  			return fs.Open(ctx, uri)
    42  		}
    43  	}
    44  
    45  	return os.Open(resource)
    46  }
    47  
    48  // ReadDir reads the directory or listing of the resource at the given URL, and
    49  // returns a slice of os.FileInfo, which describe the files contained in the directory.
    50  func ReadDir(ctx context.Context, url string) ([]os.FileInfo, error) {
    51  	return readDir(ctx, url)
    52  }
    53  
    54  func readDir(ctx context.Context, resource string) ([]os.FileInfo, error) {
    55  	switch resource {
    56  	case "", "-", "/dev/stdin":
    57  		return os.Stdin.Readdir(0)
    58  	}
    59  
    60  	if filepath.IsAbs(resource) {
    61  		return ioutil.ReadDir(resource)
    62  	}
    63  
    64  	if uri, err := url.Parse(resource); err == nil {
    65  		uri = resolveFilename(ctx, uri)
    66  
    67  		if fs, ok := getFS(uri); ok {
    68  			return fs.List(ctx, uri)
    69  		}
    70  	}
    71  
    72  	return ioutil.ReadDir(resource)
    73  }
    74  
    75  // List reads the directory or listing of the resource at the given URL, and
    76  // returns a slice of os.FileInfo, which describe the files contained in the directory.
    77  //
    78  // Depcrecated: Use `ReadDir`.
    79  func List(ctx context.Context, url string) ([]os.FileInfo, error) {
    80  	return readDir(ctx, url)
    81  }