moth/pkg/transpile/mothball.go

90 lines
2.0 KiB
Go
Raw Permalink Normal View History

2020-09-08 17:49:02 -06:00
package transpile
2019-09-02 19:47:24 -06:00
2020-09-04 18:28:23 -06:00
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"io"
2020-09-15 16:42:31 -06:00
"os/exec"
2020-09-04 18:28:23 -06:00
)
// Mothball packages a Category up for a production server run.
2020-10-12 17:44:44 -06:00
func Mothball(c Category, w io.Writer) error {
zf := zip.NewWriter(w)
2020-09-04 18:28:23 -06:00
inv, err := c.Inventory()
if err != nil {
2020-10-12 17:44:44 -06:00
return err
2020-09-04 18:28:23 -06:00
}
2020-10-12 17:44:44 -06:00
puzzlesTxt := new(bytes.Buffer)
answersTxt := new(bytes.Buffer)
2020-09-04 18:28:23 -06:00
for _, points := range inv {
fmt.Fprintln(puzzlesTxt, points)
puzzlePath := fmt.Sprintf("%d/puzzle.json", points)
pw, err := zf.Create(puzzlePath)
if err != nil {
2020-10-12 17:44:44 -06:00
return err
2020-09-04 18:28:23 -06:00
}
puzzle, err := c.Puzzle(points)
if err != nil {
2020-10-12 17:44:44 -06:00
return fmt.Errorf("Puzzle %d: %s", points, err)
2020-09-04 18:28:23 -06:00
}
// Record answers in answers.txt
for _, answer := range puzzle.Answers {
fmt.Fprintln(answersTxt, points, answer)
}
2020-09-15 16:42:31 -06:00
// Remove answers and debugging from puzzle object
2020-09-04 18:28:23 -06:00
puzzle.Answers = []string{}
2020-09-15 16:42:31 -06:00
puzzle.Debug.Errors = []string{}
puzzle.Debug.Hints = []string{}
puzzle.Debug.Log = []string{}
2020-09-04 18:28:23 -06:00
// Write out Puzzle object
penc := json.NewEncoder(pw)
if err := penc.Encode(puzzle); err != nil {
2020-10-12 17:44:44 -06:00
return fmt.Errorf("Puzzle %d: %s", points, err)
2020-09-04 18:28:23 -06:00
}
// Write out all attachments and scripts
attachments := append(puzzle.Pre.Attachments, puzzle.Pre.Scripts...)
for _, att := range attachments {
attPath := fmt.Sprintf("%d/%s", points, att)
aw, err := zf.Create(attPath)
if err != nil {
2020-10-12 17:44:44 -06:00
return err
2020-09-04 18:28:23 -06:00
}
ar, err := c.Open(points, att)
2020-09-15 16:42:31 -06:00
if exerr, ok := err.(*exec.ExitError); ok {
2020-10-12 17:44:44 -06:00
return fmt.Errorf("Puzzle %d: %s: %s: %s", points, att, err, string(exerr.Stderr))
2020-09-15 16:42:31 -06:00
} else if err != nil {
2020-10-12 17:44:44 -06:00
return fmt.Errorf("Puzzle %d: %s: %s", points, att, err)
2020-09-04 18:28:23 -06:00
}
if _, err := io.Copy(aw, ar); err != nil {
2020-10-12 17:44:44 -06:00
return fmt.Errorf("Puzzle %d: %s: %s", points, att, err)
2020-09-04 18:28:23 -06:00
}
}
}
2020-10-12 17:44:44 -06:00
pf, err := zf.Create("puzzles.txt")
if err != nil {
return err
}
puzzlesTxt.WriteTo(pf)
af, err := zf.Create("answers.txt")
if err != nil {
return err
}
answersTxt.WriteTo(af)
2020-09-04 18:28:23 -06:00
zf.Close()
2020-10-12 17:44:44 -06:00
return nil
2020-09-04 18:28:23 -06:00
}