forked from cdnjs/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
202 lines (173 loc) · 4.77 KB
/
main.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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/cdnjs/tools/cloudstorage"
"github.com/cdnjs/tools/packages"
"github.com/cdnjs/tools/sentry"
"github.com/cdnjs/tools/util"
"cloud.google.com/go/storage"
)
var (
// initialize standard debug logger
logger = util.GetStandardLogger()
// default context (no logger prefix)
defaultCtx = util.ContextWithEntries(util.GetStandardEntries("", logger)...)
)
func init() {
sentry.Init()
}
func encodeJSON(pkgs []*packages.Package) (string, error) {
out := struct {
Packages []*packages.Package `json:"packages"`
}{
pkgs,
}
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(&out)
return buffer.String(), err
}
func generatePackageWorker(jobs <-chan string, results chan<- *packages.Package) {
for f := range jobs {
// create context with file path prefix, standard debug logger
ctx := util.ContextWithEntries(util.GetStandardEntries(f, logger)...)
p, err := packages.ReadNonHumanJSONFile(ctx, f)
if err != nil {
util.Printf(ctx, "error while processing non-human-readable package: %s\n", err)
results <- nil
return
}
for _, version := range p.Versions() {
if !hasSRI(p, version) {
util.Printf(ctx, "version %s needs SRI calculation\n", version)
sriFileMap := p.CalculateVersionSRIs(version)
bytes, jsonErr := json.Marshal(sriFileMap)
util.Check(jsonErr)
writeSRIJSON(p, version, bytes)
}
}
util.Printf(ctx, "OK\n")
p.Assets = p.GetAssets()
results <- p
}
}
func main() {
defer sentry.PanicHandler()
var missingAuto, missingRepo bool
flag.BoolVar(&missingAuto, "missing-auto", false, "autoupdate can be missing")
flag.BoolVar(&missingRepo, "missing-repo", false, "repository can be missing")
flag.Parse()
if util.IsDebug() {
fmt.Println("Running in debug mode")
}
switch subcommand := flag.Arg(0); subcommand {
case "set":
{
ctx := defaultCtx
bkt, err := cloudstorage.GetAssetsBucket(ctx)
util.Check(err)
obj := bkt.Object("package.min.js")
w := obj.NewWriter(ctx)
_, err = io.Copy(w, os.Stdin)
util.Check(err)
util.Check(w.Close())
util.Check(obj.ACL().Set(ctx, storage.AllUsers, storage.RoleReader))
fmt.Println("Uploaded package.min.js")
}
case "generate":
{
files, err := filepath.Glob(path.Join(util.GetCDNJSLibrariesPath(), "*", "package.json"))
util.Check(err)
numJobs := len(files)
if numJobs == 0 {
panic("cannot find packages")
}
jobs := make(chan string, numJobs)
results := make(chan *packages.Package, numJobs)
// spawn workers
for w := 1; w <= runtime.NumCPU()*10; w++ {
go generatePackageWorker(jobs, results)
}
// submit jobs; packages to encode
for _, f := range files {
jobs <- f
}
close(jobs)
// collect results
out := make([]*packages.Package, 0)
for i := 1; i <= numJobs; i++ {
if res := <-results; res != nil {
out = append(out, res)
}
}
str, err := encodeJSON(out)
util.Check(err)
fmt.Println(string(str))
}
case "human":
{
fmt.Println(packages.HumanReadableSchemaString)
}
case "non-human":
{
fmt.Println(packages.NonHumanReadableSchemaString)
}
case "validate-human":
{
for _, path := range flag.Args()[1:] {
validateHuman(path, missingAuto, missingRepo)
}
}
default:
panic(fmt.Sprintf("unknown subcommand: `%s`", subcommand))
}
}
func validateHuman(pckgPath string, missingAuto, missingRepo bool) {
// create context with file path prefix, checker logger
ctx := util.ContextWithEntries(util.GetStandardEntries(pckgPath, logger)...)
var errs []string
_, readerr := packages.ReadHumanJSONFile(ctx, pckgPath)
if readerr != nil {
if invalidHumanErr, ok := readerr.(packages.InvalidSchemaError); ok {
// output all schema errors
for _, resErr := range invalidHumanErr.Result.Errors() {
if missingAuto && resErr.String() == "(root): autoupdate is required" {
continue
}
if missingRepo && resErr.String() == "(root): repository is required" {
continue
}
errs = append(errs, resErr.String())
}
} else {
errs = append(errs, readerr.Error())
}
}
if len(errs) > 0 {
util.Infof(ctx, strings.Join(errs, ",")+"\n")
}
}
func hasSRI(p *packages.Package, version string) bool {
sriPath := path.Join(util.GetSRIsPath(), *p.Name, version+".json")
_, statErr := os.Stat(sriPath)
return !os.IsNotExist(statErr)
}
func writeSRIJSON(p *packages.Package, version string, content []byte) {
sriDir := path.Join(util.GetSRIsPath(), *p.Name)
if _, err := os.Stat(sriDir); os.IsNotExist(err) {
util.Check(os.MkdirAll(sriDir, 0777))
}
sriFilename := path.Join(sriDir, version+".json")
util.Check(ioutil.WriteFile(sriFilename, content, 0777))
}