moth/cmd/transpile/puzzle.go

252 lines
5.2 KiB
Go
Raw Normal View History

package main
import (
"bufio"
"bytes"
2020-08-28 17:41:17 -06:00
"context"
"encoding/json"
"fmt"
"io"
2020-09-01 20:12:57 -06:00
"log"
"net/mail"
2020-09-01 20:12:57 -06:00
"os"
2020-08-28 17:41:17 -06:00
"os/exec"
"strconv"
"strings"
2020-08-28 17:41:17 -06:00
"time"
2020-08-14 20:26:04 -06:00
"github.com/russross/blackfriday"
2020-08-28 17:41:17 -06:00
"github.com/spf13/afero"
2020-08-14 20:26:04 -06:00
"gopkg.in/yaml.v2"
)
2020-09-01 20:12:57 -06:00
// NewPuzzleDir returns a new PuzzleDir for points.
func NewPuzzleDir(fs afero.Fs, points int) *PuzzleDir {
pd := &PuzzleDir{
fs: NewBasePathFs(fs, strconv.Itoa(points)),
2020-08-28 17:41:17 -06:00
}
// BUG(neale): Doesn't yet handle "puzzle.py" or "mkpuzzle"
2020-09-01 20:12:57 -06:00
return pd
2019-08-17 13:09:09 -06:00
}
2020-09-01 20:12:57 -06:00
// PuzzleDir is a single puzzle's directory.
type PuzzleDir struct {
fs afero.Fs
mkpuzzle bool
}
2020-09-01 20:12:57 -06:00
// Open returns a newly-opened file.
func (pd *PuzzleDir) Open(name string) (io.ReadCloser, error) {
// BUG(neale): You cannot open generated files in puzzles, only files actually on the disk
if _, err := pd.fs.Stat(""
return pd.fs.Open(name)
}
2020-09-01 20:12:57 -06:00
// Export returns a Puzzle struct for the current puzzle.
func (pd *PuzzleDir) Export() (Puzzle, error) {
p, staticErr := pd.exportStatic()
if staticErr == nil {
return p, nil
2019-08-17 16:00:15 -06:00
}
2020-08-28 17:41:17 -06:00
2020-09-01 20:12:57 -06:00
// Only fall through if the static files don't exist. Otherwise, report the error.
if !os.IsNotExist(staticErr) {
return p, staticErr
}
2019-08-17 13:09:09 -06:00
2020-09-01 20:12:57 -06:00
if p, cmdErr := pd.exportCommand(); cmdErr == nil {
return p, nil
} else if os.IsNotExist(cmdErr) {
// If the command doesn't exist either, report the non-existence of the static file instead.
return p, staticErr
} else {
return p, cmdErr
}
}
2020-09-01 20:12:57 -06:00
func (pd *PuzzleDir) exportStatic() (Puzzle, error) {
r, err := pd.fs.Open("puzzle.md")
2020-08-28 17:41:17 -06:00
if err != nil {
2020-08-31 16:37:51 -06:00
var err2 error
2020-09-01 20:12:57 -06:00
if r, err2 = pd.fs.Open("puzzle.moth"); err2 != nil {
return Puzzle{}, err
2020-08-31 16:37:51 -06:00
}
2020-08-28 17:41:17 -06:00
}
defer r.Close()
headerBuf := new(bytes.Buffer)
2020-09-01 20:12:57 -06:00
headerParser := rfc822HeaderParser
2020-08-28 17:41:17 -06:00
headerEnd := ""
scanner := bufio.NewScanner(r)
lineNo := 0
for scanner.Scan() {
line := scanner.Text()
2020-08-28 17:41:17 -06:00
lineNo++
if lineNo == 1 {
if line == "---" {
2020-09-01 20:12:57 -06:00
headerParser = yamlHeaderParser
headerEnd = "---"
continue
}
}
if line == headerEnd {
2020-08-28 17:41:17 -06:00
headerBuf.WriteRune('\n')
break
}
headerBuf.WriteString(line)
headerBuf.WriteRune('\n')
}
2019-08-17 13:09:09 -06:00
bodyBuf := new(bytes.Buffer)
for scanner.Scan() {
line := scanner.Text()
2020-08-28 17:41:17 -06:00
lineNo++
bodyBuf.WriteString(line)
bodyBuf.WriteRune('\n')
}
2019-08-17 13:09:09 -06:00
2020-09-01 20:12:57 -06:00
puzzle, err := headerParser(headerBuf)
if err != nil {
return puzzle, err
}
2020-08-14 20:26:04 -06:00
2019-08-17 16:00:15 -06:00
// Markdownify the body
2020-09-01 20:12:57 -06:00
if puzzle.Pre.Body != "" {
if bodyBuf.Len() > 0 {
return puzzle, fmt.Errorf("Puzzle body present in header and in moth body")
}
} else {
puzzle.Pre.Body = string(blackfriday.Run(bodyBuf.Bytes()))
2020-08-28 17:41:17 -06:00
}
2020-09-01 20:12:57 -06:00
return puzzle, nil
2020-08-28 17:41:17 -06:00
}
2020-09-01 20:12:57 -06:00
func (pd *PuzzleDir) exportCommand() (Puzzle, error) {
bfs, ok := pd.fs.(*BasePathFs)
2020-08-28 17:41:17 -06:00
if !ok {
2020-09-01 20:12:57 -06:00
return Puzzle{}, fmt.Errorf("Fs won't resolve real paths for %v", pd)
2020-08-28 17:41:17 -06:00
}
mkpuzzlePath, err := bfs.RealPath("mkpuzzle")
if err != nil {
2020-09-01 20:12:57 -06:00
return Puzzle{}, err
2020-08-28 17:41:17 -06:00
}
2020-09-01 20:12:57 -06:00
log.Print(mkpuzzlePath)
2020-08-28 17:41:17 -06:00
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, mkpuzzlePath)
stdout, err := cmd.Output()
if err != nil {
2020-09-01 20:12:57 -06:00
return Puzzle{}, err
2019-08-17 13:09:09 -06:00
}
2020-08-28 17:41:17 -06:00
jsdec := json.NewDecoder(bytes.NewReader(stdout))
jsdec.DisallowUnknownFields()
2020-09-01 20:12:57 -06:00
puzzle := Puzzle{}
if err := jsdec.Decode(&puzzle); err != nil {
return Puzzle{}, err
2020-08-28 17:41:17 -06:00
}
2020-09-01 20:12:57 -06:00
return puzzle, nil
2020-08-28 17:41:17 -06:00
}
2020-09-01 20:12:57 -06:00
func legacyAttachmentParser(val []string) []Attachment {
ret := make([]Attachment, len(val))
for idx, txt := range val {
parts := strings.SplitN(txt, " ", 3)
cur := Attachment{}
cur.FilesystemPath = parts[0]
if len(parts) > 1 {
cur.Filename = parts[1]
} else {
cur.Filename = cur.FilesystemPath
}
if (len(parts) > 2) && (parts[2] == "hidden") {
cur.Listed = false
} else {
cur.Listed = true
}
ret[idx] = cur
}
return ret
}
// Puzzle contains everything about a puzzle.
type Puzzle struct {
Pre struct {
Authors []string
Attachments []Attachment
Scripts []Attachment
AnswerPattern string
Body string
}
Post struct {
Objective string
Success struct {
Acceptable string
Mastery string
}
KSAs []string
}
Debug struct {
Log []string
Errors []string
Hints []string
Summary string
}
Answers []string
}
// Attachment carries information about an attached file.
type Attachment struct {
Filename string // Filename presented as part of puzzle
FilesystemPath string // Filename in backing FS (URL, mothball, or local FS)
Listed bool // Whether this file is listed as an attachment
}
func yamlHeaderParser(r io.Reader) (Puzzle, error) {
p := Puzzle{}
decoder := yaml.NewDecoder(r)
decoder.SetStrict(true)
err := decoder.Decode(&p)
return p, err
}
func rfc822HeaderParser(r io.Reader) (Puzzle, error) {
p := Puzzle{}
m, err := mail.ReadMessage(r)
if err != nil {
return p, fmt.Errorf("Parsing RFC822 headers: %v", err)
}
for key, val := range m.Header {
key = strings.ToLower(key)
switch key {
case "author":
p.Pre.Authors = val
case "pattern":
p.Pre.AnswerPattern = val[0]
case "script":
p.Pre.Scripts = legacyAttachmentParser(val)
case "file":
p.Pre.Attachments = legacyAttachmentParser(val)
case "answer":
p.Answers = val
case "summary":
p.Debug.Summary = val[0]
case "hint":
p.Debug.Hints = val
case "ksa":
p.Post.KSAs = val
default:
return p, fmt.Errorf("Unknown header field: %s", key)
}
}
return p, nil
}