/
step.go
373 lines (335 loc) · 9.5 KB
/
step.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
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
// Copyright 2020 The play-with-go.dev Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"strings"
"github.com/play-with-go/preguide/internal/types"
"github.com/play-with-go/preguide/sanitisers"
"mvdan.cc/sh/v3/syntax"
)
type langSteps struct {
Steps map[string]step
bashScript string
Hash string
steps []step
}
func (l *langSteps) UnmarshalJSON(b []byte) error {
type noUnmarshal langSteps
var v struct {
Steps map[string]json.RawMessage
*noUnmarshal
}
v.noUnmarshal = (*noUnmarshal)(l)
if err := json.Unmarshal(b, &v); err != nil {
return fmt.Errorf("failed to unmarshal langSteps into wrapper: %v", err)
}
if len(v.Steps) > 0 && l.Steps == nil {
l.Steps = make(map[string]step)
}
for stepName, stepBytes := range v.Steps {
s, err := unmarshalStep(stepBytes)
if err != nil {
return fmt.Errorf("failed to unmarshal step for step %v: %v", stepName, err)
}
l.Steps[stepName] = s
}
return nil
}
func unmarshalStep(r json.RawMessage) (step, error) {
var discrim struct {
StepType StepType
}
if err := json.Unmarshal(r, &discrim); err != nil {
return nil, fmt.Errorf("failed to unmarshal disciminator type: %v", err)
}
var s step
switch discrim.StepType {
case StepTypeCommand:
s = new(commandStep)
case StepTypeUpload:
s = new(uploadStep)
default:
panic(fmt.Errorf("unknown StepType: %v", discrim.StepType))
}
if err := json.Unmarshal(r, &s); err != nil {
return nil, fmt.Errorf("failed to unmarshal %T: %v", s, err)
}
return s, nil
}
func newLangSteps() *langSteps {
return &langSteps{
Steps: make(map[string]step),
}
}
type step interface {
name() string
order() int
terminal() string
setorder(int)
render(mode, io.Writer)
renderCompat(mode, io.Writer)
renderLog(mode, io.Writer)
setOutputFrom(step)
}
type commandStep struct {
// Extract once we have a solution to cuelang.org/issue/376
StepType StepType
Name string
Order int
Terminal string
Stmts []*commandStmt
}
func newCommandStep(cs commandStep) *commandStep {
cs.StepType = StepTypeCommand
return &cs
}
func (c *commandStep) name() string {
return c.Name
}
func (c *commandStep) order() int {
return c.Order
}
func (c *commandStep) terminal() string {
return c.Terminal
}
func (c *commandStep) setorder(i int) {
c.Order = i
}
type commandStmt struct {
Negated bool
CmdStr string
ExitCode int
Output string
outputFence string
sanitisers []sanitisers.Sanitiser
}
// commandStepFromCommand takes a string value that is a sequence of shell
// statements and returns a commandStep with the individual parsed statements,
// or an error in case s cannot be parsed
func (gc *genCmd) commandStepFromCommand(s *types.Command) (*commandStep, error) {
r := strings.NewReader(s.Source)
f, err := syntax.NewParser().Parse(r, "")
if err != nil {
return nil, fmt.Errorf("failed to parse command string %q: %v", s, err)
}
res := newCommandStep(commandStep{
Name: s.Name,
Terminal: s.Terminal,
})
return gc.commadStepFromSyntaxFile(res, f)
}
// commandStepFromCommandFile takes a path to a file that contains a sequence of shell
// statements and returns a commandStep with the individual parsed statements,
// or an error in case path cannot be read or parsed
func (gc *genCmd) commandStepFromCommandFile(s *types.CommandFile) (*commandStep, error) {
byts, err := ioutil.ReadFile(s.Path)
if err != nil {
return nil, fmt.Errorf("failed to read %v: %v", s.Path, err)
}
r := bytes.NewReader(byts)
f, err := syntax.NewParser().Parse(r, "")
if err != nil {
return nil, fmt.Errorf("failed to parse commands from %v: %v", s.Path, err)
}
res := newCommandStep(commandStep{
Name: s.Name,
Terminal: s.Terminal,
})
return gc.commadStepFromSyntaxFile(res, f)
}
// commadStepFromSyntaxFile takes a *mvdan.cc/sh/syntax.File and returns a
// commandStep with the individual statements, or an error in case any of the
// statements cannot be printed as string values
func (gc *genCmd) commadStepFromSyntaxFile(res *commandStep, f *syntax.File) (*commandStep, error) {
res.StepType = StepTypeCommand
for i, stmt := range f.Stmts {
// Capture whether this statement is negated or not
negated := stmt.Negated
// Set to not negated because we need to capture the exit code.
// Handling of the exit code and negated happens in the generated
// bash script
stmt.Negated = false
var sb strings.Builder
if err := gc.stmtPrinter.Print(&sb, stmt); err != nil {
return res, fmt.Errorf("failed to print statement %v: %v", i, err)
}
var sanitiers []sanitisers.Sanitiser
for _, d := range stmtSanitisers {
if san := d(gc.sanitiserHelper, stmt); san != nil {
sanitiers = append(sanitiers, san)
}
}
res.Stmts = append(res.Stmts, &commandStmt{
CmdStr: sb.String(),
Negated: negated,
sanitisers: sanitiers,
})
}
return res, nil
}
func (c *commandStep) render(mode mode, w io.Writer) {
switch mode {
case modeJekyll:
fmt.Fprintf(w, "```.%v\n", c.Terminal)
case modeGitHub:
fmt.Fprintf(w, "```\n")
}
var cmds bytes.Buffer
enc := base64.NewEncoder(base64.StdEncoding, &cmds)
if len(c.Stmts) > 0 {
var stmt *commandStmt
for _, stmt = range c.Stmts {
fmt.Fprintf(enc, "%s\n", stmt.CmdStr)
fmt.Fprintf(w, "$ %s\n", stmt.CmdStr)
fmt.Fprintf(w, "%s", stmt.Output)
}
// Output a trailing newline if the last block of output did not include one
// otherwise the closing code block fence will not render properly
if stmt.Output != "" && stmt.Output[len(stmt.Output)-1] != '\n' {
fmt.Fprintf(w, "\n")
}
}
fmt.Fprintf(w, "```")
enc.Close()
switch mode {
case modeJekyll:
fmt.Fprintf(w, "\n{:data-command-src=%q}", cmds.Bytes())
}
}
func (c *commandStep) renderCompat(mode mode, w io.Writer) {
c.render(mode, w)
}
func (c *commandStep) renderLog(mode mode, w io.Writer) {
if len(c.Stmts) > 0 {
var stmt *commandStmt
for _, stmt = range c.Stmts {
fmt.Fprintf(w, "$ %s\n", stmt.CmdStr)
fmt.Fprintf(w, "%s", stmt.Output)
}
// Output a trailing newline if the last block of output did not include one
// otherwise the closing code block fence will not render properly
if stmt.Output != "" && stmt.Output[len(stmt.Output)-1] != '\n' {
fmt.Fprintf(w, "\n")
}
}
}
func (c *commandStep) setOutputFrom(s step) {
oc, ok := s.(*commandStep)
if !ok {
panic(fmt.Errorf("expected a *commandStep; got %T", s))
}
for i, s := range oc.Stmts {
c.Stmts[i].ExitCode = s.ExitCode
c.Stmts[i].Output = s.Output
}
}
type uploadStep struct {
// Extract once we have a solution to cuelang.org/issue/376
StepType StepType
Name string
Order int
Terminal string
Language string
Renderer types.Renderer
Source string
Target string
}
func newUploadStep(u uploadStep) *uploadStep {
u.StepType = StepTypeUpload
return &u
}
func (u *uploadStep) name() string {
return u.Name
}
func (u *uploadStep) order() int {
return u.Order
}
func (u *uploadStep) terminal() string {
return u.Terminal
}
func (u *uploadStep) setorder(i int) {
u.Order = i
}
func (u *uploadStep) UnmarshalJSON(b []byte) error {
type noUnmarshall uploadStep
var uv struct {
*noUnmarshall
Renderer json.RawMessage
}
uv.noUnmarshall = (*noUnmarshall)(u)
if err := json.Unmarshal(b, &uv); err != nil {
return fmt.Errorf("failed to unmarshal wrapped uploadStep: %v", err)
}
r, err := types.UnmarshalRenderer(uv.Renderer)
if err != nil {
return err
}
u.Renderer = r
return nil
}
func (gc *genCmd) uploadStepFromUpload(u *types.Upload) (*uploadStep, error) {
res := newUploadStep(uploadStep{
Name: u.Name,
Terminal: u.Terminal,
Language: u.Language,
Renderer: u.Renderer,
Target: u.Target,
Source: u.Source,
})
return res, nil
}
func (gc *genCmd) uploadStepFromUploadFile(u *types.UploadFile) (*uploadStep, error) {
byts, err := ioutil.ReadFile(u.Path)
if err != nil {
return nil, fmt.Errorf("failed to read %v: %v", u.Path, err)
}
res := newUploadStep(uploadStep{
Name: u.Name,
Terminal: u.Terminal,
Language: u.Language,
Renderer: u.Renderer,
Target: u.Target,
Source: string(byts),
})
return res, nil
}
func (u *uploadStep) render(mode mode, w io.Writer) {
renderedSource, err := u.Renderer.Render(u.Source)
check(err, "failed to render upload step: %v", err)
fmt.Fprintf(w, "```%v\n", u.Language)
fmt.Fprintf(w, "%s\n", renderedSource)
fmt.Fprintf(w, "```")
var source, target bytes.Buffer
srcEnc := base64.NewEncoder(base64.StdEncoding, &source)
srcEnc.Write([]byte(u.Source))
srcEnc.Close()
// Workaround github.com/play-with-go/play-with-go/issues/44 by encoding the
// target as base64 in case it contains any {{.BLAH}} templates. The
// frontend half of this workaround will do the decoding before any
// attempted replacement of the substitution happens.
targetEnc := base64.NewEncoder(base64.StdEncoding, &target)
targetEnc.Write([]byte(u.Target))
targetEnc.Close()
switch mode {
case modeJekyll:
fmt.Fprintf(w, "\n{:data-upload-path=%q data-upload-src=%q data-upload-term=%q}", target.Bytes(), source.Bytes(), "."+u.Terminal)
}
}
func (u *uploadStep) renderCompat(mode mode, w io.Writer) {
fmt.Fprintf(w, "```.%v\n", u.Terminal)
source := strings.ReplaceAll(u.Source, "\t", " ")
fmt.Fprintf(w, "cat <<'EOD' > %v\n%s\nEOD\n", u.Target, source)
fmt.Fprintf(w, "```")
}
func (u *uploadStep) renderLog(mode mode, w io.Writer) {
fmt.Fprintf(w, "$ cat <<EOD > %v\n%s\nEOD\n", u.Target, u.Source)
}
func (u *uploadStep) setOutputFrom(s step) {
}