This repository has been archived by the owner on Nov 26, 2024. It is now read-only.
forked from bytecodealliance/go-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
89 lines (77 loc) · 2.27 KB
/
load.go
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
package wit
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
)
// LoadJSON loads a [WIT] JSON file from path.
// If path is "" or "-", it reads from os.Stdin.
//
// [WIT]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md
func LoadJSON(path string) (*Resolve, error) {
r := reader(path)
if r != nil {
return DecodeJSON(r)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return DecodeJSON(f)
}
// LoadWIT loads [WIT] data from path by processing it through [wasm-tools].
// This will fail if wasm-tools is not in $PATH.
// If path is "" or "-", it reads from os.Stdin.
//
// [WIT]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md
// [wasm-tools]: https://crates.io/crates/wasm-tools
func LoadWIT(path string) (*Resolve, error) {
r := reader(path)
return loadWIT(path, r)
}
// ParseWIT parses [WIT] data from a buffer by processing it through [wasm-tools].
// This will fail if wasm-tools is not in $PATH.
//
// [WIT]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md
// [wasm-tools]: https://crates.io/crates/wasm-tools
func ParseWIT(buffer []byte) (*Resolve, error) {
r := bytes.NewReader(buffer)
return loadWIT("", r)
}
// loadWIT loads WIT data from path or reader by processing it through wasm-tools.
// It accepts either a path or an io.Reader as input, but not both.
// If the path is not "" and "-", it will be used as the input file.
// Otherwise, the reader will be used as the input.
func loadWIT(path string, reader io.Reader) (*Resolve, error) {
if (path != "" && path != "-") && reader != nil {
return nil, errors.New("cannot set both path and reader; provide only one")
}
wasmTools, err := exec.LookPath("wasm-tools")
if err != nil {
return nil, err
}
var stdout, stderr bytes.Buffer
cmdArgs := []string{"component", "wit", "-j", "--all-features"}
if path != "" && path != "-" {
cmdArgs = append(cmdArgs, path)
}
cmd := exec.Command(wasmTools, cmdArgs...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
cmd.Stdin = reader
if err := cmd.Run(); err != nil {
fmt.Fprint(os.Stderr, stderr.String())
return nil, err
}
return DecodeJSON(&stdout)
}
func reader(path string) io.ReadCloser {
if path == "" || path == "-" {
return os.Stdin
}
return nil
}