github.com/MOXA-ISD/edge-library-libcompose@v0.4.1-0.20200417083957-c90441e63650/lookup/file.go (about)

     1  package lookup
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path"
     7  	"path/filepath"
     8  	"strings"
     9  )
    10  
    11  // relativePath returns the proper relative path for the given file path. If
    12  // the relativeTo string equals "-", then it means that it's from the stdin,
    13  // and the returned path will be the current working directory. Otherwise, if
    14  // file is really an absolute path, then it will be returned without any
    15  // changes. Otherwise, the returned path will be a combination of relativeTo
    16  // and file.
    17  func relativePath(file, relativeTo string) string {
    18  	// stdin: return the current working directory if possible.
    19  	if relativeTo == "-" {
    20  		if cwd, err := os.Getwd(); err == nil {
    21  			return filepath.Join(cwd, file)
    22  		}
    23  	}
    24  
    25  	// If the given file is already an absolute path, just return it.
    26  	// Otherwise, the returned path will be relative to the given relativeTo
    27  	// path.
    28  	if filepath.IsAbs(file) {
    29  		return file
    30  	}
    31  
    32  	abs, err := filepath.Abs(filepath.Join(path.Dir(relativeTo), file))
    33  	if err != nil {
    34  		logrus.Errorf("Failed to get absolute directory: %s", err)
    35  		return file
    36  	}
    37  	return abs
    38  }
    39  
    40  // FileResourceLookup is a "bare" structure that implements the project.ResourceLookup interface
    41  type FileResourceLookup struct {
    42  }
    43  
    44  // Lookup returns the content and the actual filename of the file that is "built" using the
    45  // specified file and relativeTo string. file and relativeTo are supposed to be file path.
    46  // If file starts with a slash ('/'), it tries to load it, otherwise it will build a
    47  // filename using the folder part of relativeTo joined with file.
    48  func (f *FileResourceLookup) Lookup(file, relativeTo string) ([]byte, string, error) {
    49  	file = relativePath(file, relativeTo)
    50  	logrus.Debugf("Reading file %s", file)
    51  	bytes, err := ioutil.ReadFile(file)
    52  	return bytes, file, err
    53  }
    54  
    55  // ResolvePath returns the path to be used for the given path volume. This
    56  // function already takes care of relative paths.
    57  func (f *FileResourceLookup) ResolvePath(path, relativeTo string) string {
    58  	vs := strings.SplitN(path, ":", 2)
    59  	if len(vs) != 2 || filepath.IsAbs(vs[0]) {
    60  		return path
    61  	}
    62  	vs[0] = relativePath(vs[0], relativeTo)
    63  	return strings.Join(vs, ":")
    64  }