@@ -3,8 +3,13 @@ package project
3
3
import (
4
4
"bufio"
5
5
"fmt"
6
+ "io/ioutil"
6
7
"os"
8
+ "path"
9
+ "path/filepath"
7
10
"strings"
11
+
12
+ log "github.com/golang/glog"
8
13
)
9
14
10
15
// Lookup creates a string slice of string containing a "docker-friendly" environment string
@@ -99,3 +104,58 @@ func ParseEnvFile(filename string) ([]string, error) {
99
104
}
100
105
return lines , scanner .Err ()
101
106
}
107
+
108
+ // relativePath returns the proper relative path for the given file path. If
109
+ // the relativeTo string equals "-", then it means that it's from the stdin,
110
+ // and the returned path will be the current working directory. Otherwise, if
111
+ // file is really an absolute path, then it will be returned without any
112
+ // changes. Otherwise, the returned path will be a combination of relativeTo
113
+ // and file.
114
+ func relativePath (file , relativeTo string ) string {
115
+ // stdin: return the current working directory if possible.
116
+ if relativeTo == "-" {
117
+ if cwd , err := os .Getwd (); err == nil {
118
+ return filepath .Join (cwd , file )
119
+ }
120
+ }
121
+
122
+ // If the given file is already an absolute path, just return it.
123
+ // Otherwise, the returned path will be relative to the given relativeTo
124
+ // path.
125
+ if filepath .IsAbs (file ) {
126
+ return file
127
+ }
128
+
129
+ abs , err := filepath .Abs (filepath .Join (path .Dir (relativeTo ), file ))
130
+ if err != nil {
131
+ log .V (4 ).Infof ("Failed to get absolute directory: %s" , err )
132
+ return file
133
+ }
134
+ return abs
135
+ }
136
+
137
+ // FileResourceLookup is a "bare" structure that implements the project.ResourceLookup interface
138
+ type FileResourceLookup struct {
139
+ }
140
+
141
+ // Lookup returns the content and the actual filename of the file that is "built" using the
142
+ // specified file and relativeTo string. file and relativeTo are supposed to be file path.
143
+ // If file starts with a slash ('/'), it tries to load it, otherwise it will build a
144
+ // filename using the folder part of relativeTo joined with file.
145
+ func (f * FileResourceLookup ) Lookup (file , relativeTo string ) ([]byte , string , error ) {
146
+ file = relativePath (file , relativeTo )
147
+ log .V (4 ).Infof ("Reading file %s" , file )
148
+ bytes , err := ioutil .ReadFile (file )
149
+ return bytes , file , err
150
+ }
151
+
152
+ // ResolvePath returns the path to be used for the given path volume. This
153
+ // function already takes care of relative paths.
154
+ func (f * FileResourceLookup ) ResolvePath (path , relativeTo string ) string {
155
+ vs := strings .SplitN (path , ":" , 2 )
156
+ if len (vs ) != 2 || filepath .IsAbs (vs [0 ]) {
157
+ return path
158
+ }
159
+ vs [0 ] = relativePath (vs [0 ], relativeTo )
160
+ return strings .Join (vs , ":" )
161
+ }
0 commit comments