~ach/hermes

ref: b2599991aaddb8326be84178a18443d012bbb798 hermes/src/pkgs/interp/builtins.go -rw-r--r-- 10.4 KiB
b2599991Andrew Chambers Add pkg_tree builtin. 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package interp

import (
	"fmt"
	"io"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/andrewchambers/hermes/dtar"
	"github.com/andrewchambers/hermes/hhash"
	"github.com/andrewchambers/hermes/hscript/hscript"
	"github.com/pkg/errors"
)

var BuiltinEnv hscript.StringDict

func init() {
	// XXX we could lazily init so subcommands don't both.
	BuiltinEnv = make(hscript.StringDict)
	BuiltinEnv["fetch"] = hscript.NewBuiltin("fetch", fetchBuiltin)
	BuiltinEnv["pkg_tree"] = hscript.NewBuiltin("pkg_tree", pkgTreeBuiltin)
	BuiltinEnv["builtins"] = Placeholder{"builtins"}
	BuiltinEnv["build_platform"] = &hscript.Module{
		Name: "build_platform",
		Members: hscript.StringDict{
			"store_path": Placeholder{"build_store_path"},
			"system":     Placeholder{"build_system"},
		},
	}

	for _, bi := range BuiltinEnv {
		bi.Freeze()
	}
}

// XXX this is a badly factored function, it's processes a url, and does some disambiguation of args depending
// if it's a local file we are fetching or a remote url. If we are fetching a local directory, it sets
// the fetch and unpack args.
//
// Untangling it would be a good excercise for anyone with time and some creativity.
// Try to pay attention to performance too, fetch is actually in a performance critical code path when
// it is used for loading in source code and patches.
func processAndValidateFetchUrl(mirrors *MirrorMap, currentDir string, hash, fetchUrl, file_name, unpack_type *string, unpack, unpack_unwrap *bool) error {
	var parsedUrl *url.URL

	if strings.HasPrefix(*fetchUrl, ".") || strings.HasPrefix(*fetchUrl, "/") {
		fpath := *fetchUrl

		if !filepath.IsAbs(fpath) {
			fpath = filepath.Join(currentDir, fpath)
		}

		fpath, err := filepath.Abs(fpath)
		if err != nil {
			return errors.Wrapf(err, "unable to get absolute path of %q", fpath)
		}

		st, err := os.Stat(fpath)
		if err != nil {
			return errors.Wrapf(err, "unable to stat %q", fpath)
		}

		parsedUrl = &url.URL{Scheme: "file", Path: fpath}
		*fetchUrl = parsedUrl.String()
		fdir := filepath.Dir(fpath)

		if !strings.HasPrefix(fdir, currentDir) && !(st.IsDir() && fpath == currentDir) {
			_, err := os.Stat(filepath.Join(fdir, ".hermes_allow"))
			// If it's a dir, the allow file can be within the dir.
			if err != nil && st.IsDir() {
				_, err = os.Stat(filepath.Join(fpath, ".hermes_allow"))
			}
			if err != nil {
				return errors.Errorf("security violation: access of %q outside of current module directory and without file '.hermes_allow'", fpath)
			}
		}

		if st.IsDir() {
			*unpack_type = "tar"
			*unpack_unwrap = false
			*unpack = true
		}

		// If the user didn't specify the hash for a local file, we must read it.
		// if they did specify the hash, we can skip a whole lot of pointless io.
		if *hash == "" {
			h, err := hhash.New("sha256", "hex")
			if err != nil {
				return err
			}

			if st.IsDir() {
				err = dtar.MakeTar(fpath, func(string) bool { return true }, h)
				if err != nil {
					return err
				}
			} else {
				f, err := os.Open(fpath)
				if err != nil {
					return errors.Wrapf(err, "unable to open local file %s", fpath)
				}
				defer f.Close()

				_, err = io.Copy(h, f)
				if err != nil {
					return err
				}
			}

			*hash = h.Done()
		}
	} else if *fetchUrl != "" {
		u, err := url.Parse(*fetchUrl)
		if err != nil {
			return errors.Wrapf(err, "unable to parse url %q", fetchUrl)
		}
		parsedUrl = u
	}

	if *file_name == "" {
		*file_name = path.Base(parsedUrl.Path)
	}

	if *hash == "" && *fetchUrl == "" {
		return errors.Errorf("fetch requires either a hash or a url")
	}

	if *hash != "" && *fetchUrl != "" {
		err := mirrors.AddContentMirror(*hash, *fetchUrl)
		if err != nil {
			return err
		}

		// We no longer need the url, If we have an entry in the hash database.
		// This allows us to change urls without breaking package builds because
		// the url is not part of the package hash.
		*fetchUrl = ""
	}

	return nil
}

func addBuilderFragmentForUrlImport(mirrors *MirrorMap, currentDir, importPath, fetchUrl, filename string, builder *hscript.List) error { // no free variables
	fetchHash := ""
	unpack := true
	unpack_unwrap := true
	unpack_type := ""

	err := processAndValidateFetchUrl(mirrors, currentDir, &fetchHash, &fetchUrl, &filename, &unpack_type, &unpack, &unpack_unwrap)
	if err != nil {
		return err
	}

	urlArg := ""
	if fetchUrl != "" {
		urlArg = " " + strconv.Quote("--url="+fetchUrl)
	}

	hashArg := ""
	if fetchHash != "" {
		hashArg = " " + strconv.Quote("--hash="+fetchHash)
	}

	unpackTypeArg := ""
	if unpack_type != "" {
		unpackTypeArg = " " + strconv.Quote("--type="+unpack_type)
	}

	builder.Append(Placeholder{"builtins"})
	builder.Append(
		hscript.String(
			fmt.Sprintf(
				"/fetch%s%s %q\n",
				urlArg,
				hashArg,
				"--out="+filename,
			),
		),
	)
	builder.Append(Placeholder{"builtins"})
	builder.Append(
		hscript.String(
			fmt.Sprintf(
				"/unpack%s %q %q\n",
				unpackTypeArg,
				"--dest=${out}/"+importPath,
				filename,
			),
		),
	)

	return nil
}

func pkgTreeBuiltin(thread *hscript.Thread, fn *hscript.Builtin, args hscript.Tuple, kwargs []hscript.Tuple) (hscript.Value, error) {
	mirrors := thread.Local("mirror_db").(*MirrorMap)
	currentDir := thread.Local("current_dir").(string)

	fnname := fn.Name()
	contentHash := ""
	importSpecs := args

	if len(kwargs) != 0 {
		err := hscript.UnpackArgs(fnname, hscript.Tuple{}, kwargs, "hash", &contentHash)
		if err != nil {
			return nil, err
		}
	} else {
		if len(importSpecs) <= 2 {
			return nil, errors.Errorf("%s: expects at least an import and an output hash", fnname)
		}
		contentHashHstr, ok := args[len(importSpecs)-1].(hscript.String)
		if !ok {
			return nil, errors.Errorf("%s: output hash must be a string", fnname)
		}
		contentHash = string(contentHashHstr)
		importSpecs = args[0 : len(importSpecs)-1]
	}

	builder := hscript.NewList([]hscript.Value{
		hscript.String("#!"),
		Placeholder{"builtins"},
		hscript.String("/runcmds\n"),
	})

	malformedArgError := func(idx int) error {
		return errors.Errorf("%s: argument %d should be of the form [\"importpath\", \"url\" | package]", fnname, idx)
	}

	for argIdx, imp := range importSpecs {
		switch imp := imp.(type) {
		case hscript.String:
			importSpec := string(imp)
			importSpecWithScheme := importSpec

			if !strings.HasPrefix(importSpecWithScheme, "hpkg://") {
				importSpecWithScheme = "hpkg://" + importSpec
			}

			importUrl, err := url.Parse(importSpecWithScheme)
			if err != nil {
				return nil, errors.Wrapf(err, "%s", fnname)
			}

			if importUrl.Fragment == "" {
				return nil, errors.Errorf("%s: empty #version specifier for import %q", fnname, importSpec)
			}

			importPath := importUrl.Host + importUrl.Path

			err = addBuilderFragmentForUrlImport(mirrors, currentDir, importPath, importUrl.String(), "pkgs.tgz", builder)
			if err != nil {
				return nil, errors.Wrapf(err, "%s", fnname)
			}

		case *hscript.List:
			if imp.Len() != 2 {
				return nil, malformedArgError(argIdx)
			}

			himportPathVal := imp.Index(0)
			himportPathStr, ok := himportPathVal.(hscript.String)
			if !ok {
				return nil, malformedArgError(argIdx)
			}
			importPath := string(himportPathStr)
			if strings.HasPrefix(importPath, "/") {
				importPath = importPath[1:]
			}

			switch importContent := imp.Index(1).(type) {
			case hscript.String:
				err := addBuilderFragmentForUrlImport(mirrors, currentDir, importPath, string(importContent), "", builder)
				if err != nil {
					return nil, errors.Wrapf(err, "%s", fnname)
				}

			case *hscript.List, *hscript.Dict:
				// We are importing from a package.
				builder.Append(Placeholder{"builtins"})
				builder.Append(hscript.String(fmt.Sprintf("/mkdir -p %q\n", "${out}/"+filepath.Dir(importPath))))
				builder.Append(Placeholder{"builtins"})
				// We choose to copy instead of link, so the package content hash does not depend on the package path.
				// when copying we also skip the .hermes_pkg file as that contains the store path.
				builder.Append(hscript.String("/copy --skip \"[^\\.]+\\.hermes_pkg$\" \""))
				builder.Append(importContent)
				builder.Append(hscript.String(fmt.Sprintf("\" %q\n", "${out}/"+importPath)))
			default:
				return nil, malformedArgError(argIdx)
			}
		default:
			return nil, errors.Errorf("%s: positional arguments must match \"import-spec\" | [\"import-path\", \"url\"| pkg]", fnname)
		}
	}

	d := &hscript.Dict{}
	d.SetKey(hscript.String("name"), hscript.String("pkg-tree"))
	d.SetKey(hscript.String("builder"), builder)
	d.SetKey(hscript.String("content"), hscript.String(contentHash))
	return d, nil
}

func fetchBuiltin(thread *hscript.Thread, fn *hscript.Builtin, args hscript.Tuple, kwargs []hscript.Tuple) (hscript.Value, error) {
	mirrors := thread.Local("mirror_db").(*MirrorMap)
	currentDir := thread.Local("current_dir").(string)

	fetchUrl := ""
	hash := ""
	// hscript naming convention.
	file_name := ""
	unpack := false
	unpack_unwrap := true
	unpack_type := ""

	err := hscript.UnpackArgs(
		fn.Name(), args, kwargs,
		"url?", &fetchUrl,
		"hash?", &hash,
		"file_name?", &file_name,
		"unpack?", &unpack,
		"unpack_unwrap?", &unpack_unwrap,
		"unpack_type?", &unpack_type,
	)
	if err != nil {
		return nil, err
	}

	err = processAndValidateFetchUrl(mirrors, currentDir, &hash, &fetchUrl, &file_name, &unpack_type, &unpack, &unpack_unwrap)
	if err != nil {
		return nil, errors.Wrapf(err, "%s", fn.Name())
	}

	urlArg := ""
	if fetchUrl != "" {
		urlArg = " " + strconv.Quote("--url="+fetchUrl)
	}

	hashArg := ""
	if hash != "" {
		hashArg = " " + strconv.Quote("--hash="+hash)
	}

	var builder *hscript.List

	if unpack {

		unwrapArg := ""
		if !unpack_unwrap {
			unwrapArg = " --no-unwrap"
		}

		unpackTypeArg := ""
		if unpack_type != "" {
			unpackTypeArg = " " + strconv.Quote("--type="+unpack_type)
		}

		builder = hscript.NewList([]hscript.Value{
			hscript.String("#!"), Placeholder{"builtins"}, hscript.String("/runcmds\n"),
			Placeholder{"builtins"},
			hscript.String(
				fmt.Sprintf("/fetch%s%s %q\n",
					urlArg,
					hashArg,
					"--out="+file_name,
				),
			),
			Placeholder{"builtins"},
			hscript.String(
				fmt.Sprintf("/unpack%s%s %q %q\n",
					unwrapArg,
					unpackTypeArg,
					"--dest=${out}",
					file_name,
				),
			),
		})

	} else {

		builder = hscript.NewList([]hscript.Value{
			hscript.String("#!"), Placeholder{"builtins"}, hscript.String("/runcmds\n"),
			Placeholder{"builtins"},
			hscript.String(
				fmt.Sprintf("/fetch%s%s %q\n",
					urlArg,
					hashArg,
					"--out="+filepath.Join("${out}", file_name),
				),
			),
		})

	}

	return builder, nil
}