Repository navigation
Expand file tree
/
Copy pathmanifest.go
More file actions
327 lines (318 loc) · 9.05 KB
/
Copy pathmanifest.go
File metadata and controls
327 lines (318 loc) · 9.05 KB
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
package packageinfo
import (
"encoding/json"
"fmt"
"io"
"io/fs"
"path/filepath"
"sort"
"strings"
"unicode/utf8"
)
type Text map[string]string
const MaxPackageMetadataBytes = 64 << 20
func metadataCost(v any) int64 {
cost := int64(32)
switch x := v.(type) {
case string:
cost += int64(len(x))
case json.Number:
cost += int64(len(x))
case map[string]any:
for k, v := range x {
cost += int64(len(k)) + metadataCost(v)
}
case []any:
for _, v := range x {
cost += metadataCost(v)
}
}
return cost
}
func TextValue(v any) (Text, bool) {
if s, ok := v.(string); ok {
return Text{"_": s}, true
}
m, ok := v.(map[string]any)
if !ok {
return nil, false
}
t := Text{}
for k, v := range m {
s, ok := v.(string)
if !ok {
return nil, false
}
t[k] = s
}
_, ok = t["_"]
return t, ok
}
type Dependency struct {
ID string `json:"id"`
Version Version `json:"version"`
}
type Contribution struct {
Category string `json:"category"`
ID string `json:"id"`
Path string `json:"path,omitempty"`
Entry map[string]any `json:"entry"`
*SingerDeclaration
}
type PackageManifest struct {
Identity
FormatVersion Version `json:"formatVersion"`
RuntimeLevel int `json:"runtimeLevel"`
CompatVersion Version `json:"compatVersion"`
Dependencies []Dependency `json:"dependencies"`
Contributions []Contribution `json:"contributions"`
Name Text `json:"name,omitempty"`
Description Text `json:"description,omitempty"`
Vendor Text `json:"vendor,omitempty"`
License Text `json:"license,omitempty"`
Readme Text `json:"readme,omitempty"`
URL *string `json:"url,omitempty"`
Manifest map[string]any `json:"manifest"`
Diagnostics []string `json:"diagnostics,omitempty"`
}
func readObject(files fs.FS, name string) (map[string]any, error) {
f, err := files.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if !st.Mode().IsRegular() {
return nil, fmt.Errorf("The path %s is not a regular file.", name)
}
b, err := io.ReadAll(io.LimitReader(f, MaxJSONBytes+1))
if err != nil {
return nil, err
}
m, err := DecodeJSON(b)
if err != nil {
return nil, fmt.Errorf("%s: %w", name, err)
}
return m, nil
}
func versionField(m map[string]any, k string) (Version, error) {
s, ok := m[k].(string)
if !ok {
return Version{}, fmt.Errorf("The field %s must be a version string.", k)
}
return ParseVersion(s)
}
func positiveInteger(v any) (int64, bool) {
n, ok := v.(json.Number)
if !ok {
return 0, false
}
i, err := n.Int64()
return i, err == nil && i > 0
}
// Reads package metadata and returns the manifest or an error for invalid declarations or references.
// The root argument specifies a fully qualified lexical root for variable expansion.
func Load(files fs.FS, root string) (PackageManifest, error) {
var p PackageManifest
root = filepath.Clean(root)
if !filepath.IsAbs(root) || !utf8.ValidString(root) || strings.ContainsRune(root, 0) || strings.Contains(root, "\\") && filepath.Separator != '\\' {
return p, fmt.Errorf("The package root must be a representable, fully qualified path.")
}
raw, err := readObject(files, "desc.json")
if err != nil {
return p, err
}
p.FormatVersion, err = versionField(raw, "$version")
if err != nil {
return p, err
}
one, _ := ParseVersion("1")
if p.FormatVersion.Compare(one) != 0 {
return p, fmt.Errorf("The manifest format is unsupported.")
}
level, ok := positiveInteger(raw["runtimeLevel"])
if !ok || level != 1 {
return p, fmt.Errorf("The runtimeLevel value is unsupported or invalid.")
}
p.RuntimeLevel = 1
m, scope, err := expandDocument(raw, map[string]string{"root": root, "dir": root})
if err != nil {
return p, err
}
p.Manifest = m
metadataRemaining := int64(MaxPackageMetadataBytes) - metadataCost(m)
if metadataRemaining < 0 {
return p, fmt.Errorf("The package metadata exceeds a resource limit.")
}
p.ID, ok = m["id"].(string)
if !ok || !IsValidPackageIdentifier(p.ID) {
return p, fmt.Errorf("The package ID is invalid.")
}
p.Version, err = versionField(m, "version")
if err != nil {
return p, err
}
p.CompatVersion = p.Version
if _, ok := m["compatVersion"]; ok {
p.CompatVersion, err = versionField(m, "compatVersion")
if err != nil {
return p, err
}
}
if p.CompatVersion.Compare(p.Version) > 0 {
return p, fmt.Errorf("The compatVersion value exceeds the package version.")
}
for _, field := range []string{"name", "vendor", "description", "license", "readme"} {
if v, exists := m[field]; exists {
t, ok := TextValue(v)
if !ok {
return p, fmt.Errorf("The multilingual field %s is invalid.", field)
}
switch field {
case "name":
p.Name = t
case "vendor":
p.Vendor = t
case "description":
p.Description = t
case "license", "readme":
for language, value := range t {
name, err := directFile(files, root, value)
if err != nil {
return p, fmt.Errorf("%s: %w", field, err)
}
t[language] = filepath.Join(root, filepath.FromSlash(name))
}
if field == "license" {
p.License = t
} else {
p.Readme = t
}
}
}
}
if v, ok := m["url"]; ok {
url, ok := v.(string)
if !ok {
return p, fmt.Errorf("The url field must be a string.")
}
p.URL = &url
}
p.Dependencies = []Dependency{}
p.Contributions = []Contribution{}
if v, exists := m["dependencies"]; exists {
a, ok := v.([]any)
if !ok {
return p, fmt.Errorf("The dependencies field must be an array.")
}
seen := map[string]bool{}
for _, v := range a {
d, ok := v.(map[string]any)
if !ok {
return p, fmt.Errorf("Each dependency must be an object.")
}
id, ok := d["id"].(string)
if !ok || !IsValidPackageIdentifier(id) || seen[id] || id == p.ID {
return p, fmt.Errorf("The dependency %q is invalid, duplicate, or self-referential.", id)
}
seen[id] = true
version, err := versionField(d, "version")
if err != nil {
return p, err
}
p.Dependencies = append(p.Dependencies, Dependency{id, version})
}
}
if value, exists := m["contributions"]; exists {
categories, ok := value.(map[string]any)
if !ok {
return p, fmt.Errorf("The contributions field must be an object.")
}
keys := make([]string, 0, len(categories))
for c := range categories {
keys = append(keys, c)
}
sort.Strings(keys)
for _, category := range keys {
if !ValidDottedID(category) {
return p, fmt.Errorf("The category %q is invalid.", category)
}
a, ok := categories[category].([]any)
if !ok {
return p, fmt.Errorf("The contribution category %s must contain an array.", category)
}
seen := map[string]bool{}
for _, v := range a {
entry, ok := v.(map[string]any)
if !ok {
return p, fmt.Errorf("Each contribution must be an object.")
}
id, ok := entry["id"].(string)
if !ok || !IsValidGenericIdentifier(id) || seen[id] {
return p, fmt.Errorf("The contribution ID %q is invalid or duplicate.", id)
}
seen[id] = true
c := Contribution{Category: category, ID: id, Entry: entry}
if v, exists := entry["path"]; exists {
value, ok := v.(string)
if !ok && category == "singer" {
return p, fmt.Errorf("The contribution path must be a string.")
}
if ok {
c.Path, err = directFile(files, root, value)
if err != nil {
return p, err
}
}
}
if category == "singer" {
if c.Path == "" {
return p, fmt.Errorf("Singer contribution %q requires a declaration path.", id)
}
diagnostics, err := loadSingerContribution(files, root, scope, &c, &metadataRemaining)
if err != nil {
return p, err
}
p.Diagnostics = append(p.Diagnostics, diagnostics...)
}
p.Contributions = append(p.Contributions, c)
}
}
}
return p, nil
}
func directFile(files fs.FS, root, value string) (string, error) {
if strings.ContainsRune(value, 0) || value == "" {
return "", fmt.Errorf("The direct file path is invalid.")
}
value = strings.ReplaceAll(value, "\\", "/")
if filepath.Separator == '\\' && strings.HasPrefix(value, "/") && !strings.HasPrefix(value, "//") {
value = filepath.ToSlash(filepath.VolumeName(root)) + value
}
if filepath.VolumeName(filepath.FromSlash(value)) != "" && !filepath.IsAbs(filepath.FromSlash(value)) {
return "", fmt.Errorf("The drive-relative file reference %q is ambiguous.", value)
}
resolved := filepath.Clean(filepath.Join(root, filepath.FromSlash(value)))
if filepath.IsAbs(filepath.FromSlash(value)) {
resolved = filepath.Clean(filepath.FromSlash(value))
}
relative, err := filepath.Rel(root, resolved)
if err != nil {
return "", err
}
name := filepath.ToSlash(relative)
if !fs.ValidPath(name) || name == "." || strings.Contains(name, ":") {
return "", fmt.Errorf("The direct file reference %q is outside the package.", value)
}
st, err := fs.Stat(files, name)
if err != nil {
return "", err
}
if !st.Mode().IsRegular() {
return "", fmt.Errorf("The direct reference %q is not a regular file.", value)
}
return name, nil
}