-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
179 lines (165 loc) · 4 KB
/
server.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
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
package main
import (
"cuelang.org/go/cue"
"cuelang.org/go/cue/load"
"cuelang.org/go/encoding/yaml"
"fmt"
"io/fs"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
var dir string
var roots map[string]bool
var rootsList []string
var pathSplitter = func(c rune) bool {
return c == '/'
}
func ServeCueFiles() {
roots = make(map[string]bool)
var dir string
if s := os.Getenv("CUE_DIR"); s != "" {
dir = s
} else {
s, err := filepath.Abs("./")
if err != nil {
panic(err)
}
dir = s
}
if err := os.Chdir(dir); err != nil {
panic(err)
}
var files []fs.FileInfo
if f, err := ioutil.ReadDir(dir); err == nil {
files = f
} else {
panic(err)
}
for _, file := range files {
if file.IsDir() && !strings.HasPrefix(file.Name(), ".") {
roots[file.Name()] = true
}
}
for dirname := range roots {
rootsList = append(rootsList, dirname)
}
http.HandleFunc("/", handler)
log.Printf("Starting cue server for dir %s\n", dir)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
defer func() {
if e := recover(); e != nil {
log.Printf("Recovered from %v\n", e)
http.Error(w, "Internal error occurred", http.StatusInternalServerError)
}
}()
pathComponents := strings.FieldsFunc(r.URL.Path, pathSplitter)
if len(pathComponents) < 1 {
http.Error(w,
fmt.Sprintf("Invalid path. Available roots are %v", rootsList), http.StatusBadRequest)
return
}
root := pathComponents[0]
log.Printf("root is %s", root)
if !roots[root] {
http.Error(w,
fmt.Sprintf(`Cannot find root "%s", available ones are %v`, root, rootsList),
http.StatusBadRequest)
return
}
var tags []string
for key, values := range r.URL.Query() {
if len(values) != 1 {
http.Error(w,
fmt.Sprintf(`tag must have exactly one value, key: "%s", values: %v"`, key, values),
http.StatusBadRequest)
return
}
tags = append(tags, fmt.Sprintf("%s=%s", key, values[0]))
}
cut := getDir(dir, pathComponents)
// https://pkg.go.dev/cuelang.org/go/cue
config := load.Config{
Context: nil,
ModuleRoot: dir,
Module: "",
Package: "",
Dir: filepath.Join(pathComponents[0:cut]...),
Tags: tags,
TagVars: nil,
AllCUEFiles: false,
Tests: false,
Tools: false,
DataFiles: false,
StdRoot: "",
ParseFile: nil,
Overlay: nil,
Stdin: nil,
}
instances := load.Instances(nil, &config)
if l := len(instances); l != 1 {
http.Error(w,
fmt.Sprintf("can only evaluate exactly 1 cue instance, received %v", l),
http.StatusBadRequest,
)
}
instance := instances[0]
var value cue.Value
if v := ctx.BuildInstance(instance); v.Err() == nil {
value = v
} else {
http.Error(w,
fmt.Sprintf("Failed to build cue instance, error: %v.", v.Err().Error()),
http.StatusBadRequest,
)
return
}
var selectors []cue.Selector
for _, seg := range pathComponents[cut:] {
if strings.HasPrefix(seg, "_") {
// https://github.com/cuelang/cue/issues/880
// id format: module/dir:package
selectors = append(selectors, cue.Hid(seg, instance.ID()))
} else if strings.HasPrefix(seg, "#") {
// character `#` must url encode to `%23`
selectors = append(selectors, cue.Def(seg))
} else {
selectors = append(selectors, cue.Str(seg))
}
}
path := cue.MakePath(selectors...)
value = value.LookupPath(path)
var result []byte
var resultErr error
if list, err := value.List(); err != nil {
result, resultErr = yaml.Encode(value)
} else {
result, resultErr = yaml.EncodeStream(list)
}
if resultErr != nil {
http.Error(w, resultErr.Error(), http.StatusBadRequest)
return
}
_, _ = w.Write(result)
}
// navigate down file path according to pathComponents
func getDir(root string, pathComponents []string) int {
var i int = 1
for i <= len(pathComponents) {
comps := append([]string{root}, pathComponents[0:i]...)
cur := filepath.Join(comps...)
if _, err := os.Stat(cur); os.IsNotExist(err) {
break
} else if err == nil {
i++
} else {
panic(err)
}
}
return i - 1
}