-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
formats.go
293 lines (246 loc) · 6.51 KB
/
formats.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
/*
Copyright © 2014–2020 Thomas Michael Edwards. All rights reserved.
Use of this source code is governed by a Simplified BSD License which
can be found in the LICENSE file.
*/
package main
import (
// standard packages
"bytes"
"encoding/json"
"errors"
"log"
"os"
"path/filepath"
"strings"
// external packages
"github.com/Masterminds/semver/v3"
)
type twine2FormatJSON struct {
Name string `json:"name"`
Version string `json:"version"`
// Description string `json:"description"`
// Author string `json:"author"`
// Image string `json:"image"`
// URL string `json:"url"`
// License string `json:"license"`
Proofing bool `json:"proofing"`
Source string `json:"source"`
// Setup string `json:"-"`
}
type storyFormat struct {
id string
filename string
twine2 bool
name string
version string
proofing bool
}
func (f *storyFormat) isTwine1Style() bool {
return !f.twine2
}
func (f *storyFormat) isTwine2Style() bool {
return f.twine2
}
func (f *storyFormat) getStoryFormatData(source []byte) (*twine2FormatJSON, error) {
if !f.twine2 {
return nil, errors.New("Not a Twine 2 style story format.")
}
// get the JSON chunk from the source
first := bytes.Index(source, []byte("{"))
last := bytes.LastIndex(source, []byte("}"))
if first == -1 || last == -1 {
return nil, errors.New("Could not find Twine 2 style story format JSON chunk.")
}
source = source[first : last+1]
// parse the JSON
data := &twine2FormatJSON{}
if err := json.Unmarshal(source, data); err != nil {
/*
START Harlowe malformed JSON chunk workaround
TODO: Remove this workaround that attempts to handle Harlowe's
broken JSON chunk.
NOTE: This worksaround is only possible because, currently,
Harlowe's "setup" property is the last entry in the chunk.
*/
if strings.HasPrefix(strings.ToLower(f.id), "harlowe") {
if i := bytes.LastIndex(source, []byte(`,"setup": function`)); i != -1 {
// cut the "setup" property and its invalid value
j := len(source) - 1
source = append(source[:i], source[j:]...)
return f.getStoryFormatData(source)
}
}
/*
If we've reached this point, either the format is not Harlowe
or we cannot find the start of its "setup" property, so just
return the JSON decoding error as normal.
END Harlowe malformed JSON chunk workaround
*/
return nil, errors.New("Could not decode story format JSON chunk.")
}
return data, nil
}
func (f *storyFormat) unmarshalMetadata() error {
if !f.twine2 {
return nil
}
var (
data *twine2FormatJSON
source []byte
err error
)
// read in the story format
if source, err = fileReadAllAsUTF8(f.filename); err != nil {
return err
}
// load various bits of metadata from the JSON
if data, err = f.getStoryFormatData(source); err != nil {
return err
}
f.name = data.Name
f.version = data.Version
f.proofing = data.Proofing
return nil
}
func (f *storyFormat) source() []byte {
var (
source []byte
err error
)
// read in the story format
if source, err = fileReadAllAsUTF8(f.filename); err != nil {
log.Fatalf("error: format %s", err.Error())
}
// if in Twine 2 style, extract the actual source from the JSON
if f.twine2 {
var data *twine2FormatJSON
if data, err = f.getStoryFormatData(source); err != nil {
log.Fatalf("error: format %s: %s", f.id, err.Error())
}
source = []byte(data.Source)
}
return source
}
type storyFormatsMap map[string]*storyFormat
func newStoryFormatsMap(searchPaths []string) storyFormatsMap {
var (
baseFilenames = []string{"format.js", "header.html"}
formats = make(storyFormatsMap)
)
for _, searchDirname := range searchPaths {
if info, err := os.Stat(searchDirname); err != nil || !info.IsDir() {
continue
}
d, err := os.Open(searchDirname)
if err != nil {
continue
}
baseDirnames, err := d.Readdirnames(0)
if err != nil {
continue
}
for _, baseDirname := range baseDirnames {
formatDirname := filepath.Join(searchDirname, baseDirname)
if info, err := os.Stat(formatDirname); err != nil || !info.IsDir() {
continue
}
for _, baseFilename := range baseFilenames {
formatFilename := filepath.Join(formatDirname, baseFilename)
if info, err := os.Stat(formatFilename); err == nil && info.Mode().IsRegular() {
f := &storyFormat{
id: baseDirname,
filename: formatFilename,
twine2: baseFilename == "format.js",
}
if err := f.unmarshalMetadata(); err != nil {
log.Printf("warning: format %s: Skipping format; %s", f.id, err.Error())
continue
}
formats[baseDirname] = f
break
}
}
}
}
return formats
}
func (m storyFormatsMap) isEmpty() bool {
return len(m) == 0
}
func (m storyFormatsMap) getIDFromTwine2Name(name string) string {
var (
found *semver.Version
id string
)
for _, f := range m {
if !f.twine2 {
continue
}
if f.name == name {
if have, err := semver.NewVersion(f.version); err == nil {
if found == nil || have.GreaterThan(found) {
found = have
id = f.id
}
}
}
}
return id
}
func (m storyFormatsMap) getIDFromTwine2NameAndVersion(name, version string) string {
var (
wanted *semver.Version
found *semver.Version
id string
)
if v, err := semver.NewVersion(version); err == nil {
wanted = v
} else {
log.Printf("warning: format %q: Auto-selecting greatest version; Could not parse version %q.", name, version)
}
for _, f := range m {
if !f.twine2 {
continue
}
if f.name == name {
if have, err := semver.NewVersion(f.version); err == nil {
if wanted == nil || have.Major() == wanted.Major() && have.Compare(wanted) > -1 {
if found == nil || have.GreaterThan(found) {
found = have
id = f.id
}
}
}
}
}
return id
}
func (m storyFormatsMap) hasByID(id string) bool {
_, ok := m[id]
return ok
}
func (m storyFormatsMap) hasByTwine2Name(name string) bool {
_, ok := m[m.getIDFromTwine2Name(name)]
return ok
}
func (m storyFormatsMap) hasByTwine2NameAndVersion(name, version string) bool {
_, ok := m[m.getIDFromTwine2NameAndVersion(name, version)]
return ok
}
func (m storyFormatsMap) getByID(id string) *storyFormat {
return m[id]
}
func (m storyFormatsMap) getByTwine2Name(name string) *storyFormat {
return m[m.getIDFromTwine2Name(name)]
}
func (m storyFormatsMap) getByTwine2NameAndVersion(name, version string) *storyFormat {
return m[m.getIDFromTwine2NameAndVersion(name, version)]
}
func (m storyFormatsMap) ids() []string {
var ids []string
for id := range m {
ids = append(ids, id)
}
return ids
}