-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmesosys.go
More file actions
297 lines (256 loc) · 8.04 KB
/
mesosys.go
File metadata and controls
297 lines (256 loc) · 8.04 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"reflect"
"regexp"
"strings"
"sync"
"unicode"
"go.opentelemetry.io/otel"
)
/*
This is the refactored v2 API
All files in the pattern `*sys[_test].go` belong to this version.
*/
// Mesostic contains all data and their transformation for a single poem
type Mesostic struct {
MU sync.Mutex
Date string `json:"date"`
Source io.Reader `json:"source"` // Source JSON
SourceData interface{} `json:"source_raw"` // Source data, decoded from JSON
SourceTxt string `json:"source_txt"` // Raw text to transform
Title string `json:"title"` // The poem title
Spine []string `json:"spine"` // The poem spine
SpineIdx int `json:"spine_idx"` // Current spine char
Width int `json:"width"` // Longest line length
WWidth int `json:"west_width"` // Longest westline length
MLines []string `json:"lines"` // Mesostic lines
MLinesIdx int `json:"lines_idx"` // Current line
MLineCt int `json:"line_count"` // Total lines
LineWest []string `json:"line_west"` // Used for alignment
LineEast []string `json:"line_east"` // Used for alignment
EmptyLine []int `json:"empty_line"` // Line address for empty space
Poem string `json:"poem"` // Final multi-line poem
}
func NewMesostic(ctx context.Context, title, source string, data interface{}) *Mesostic {
ctx, span := otel.Tracer("mesostic/new").Start(ctx, "NewMesostic")
defer span.End()
m := &Mesostic{
MU: sync.Mutex{},
Date: "",
Source: strings.NewReader(source),
SourceData: data,
SourceTxt: "",
Title: title,
Spine: make([]string, 0),
SpineIdx: 0,
Width: 0,
MLines: make([]string, 0),
MLinesIdx: 0,
MLineCt: 0,
LineWest: make([]string, 0),
LineEast: make([]string, 0),
EmptyLine: make([]int, 0),
Poem: "",
}
// If the EnvVar is set, use it. No default so this can be left unset.
newspine := envVar("HPSCHD_SPINESTRING", "")
// Keep whitespace as the default
m.ParseSpine(ctx, newspine, true)
m.ParseSourceJSON(ctx, data)
return m
}
// BuildMeso takes the populated struct and builds the final poem
// replaces mesoMain
func (m *Mesostic) BuildMeso(ctx context.Context) string {
ctx, span := otel.Tracer("mesostic/mesosys").Start(ctx, "BuildMeso")
defer span.End()
m.MU.Lock()
defer m.MU.Unlock()
var mesostic string
// Split the source text up into (hopefully) usable blocks
re := regexp.MustCompile(`[,.;:]`)
sourceLines := re.Split(m.SourceTxt, -1)
// Run the lines through a mesostic algorithm
for _, sl := range sourceLines {
if m.FormatLine(ctx, sl) {
// Increase the index address, wrapping if it reaches the end of the Spine String
m.SpineIdx = (m.SpineIdx + 1) % len(m.Spine)
} else {
m.EmptyLine = append(m.EmptyLine, m.MLinesIdx)
}
// Advance line every time
m.MLinesIdx++
}
// Pull all elements together into final mesostic lines
m.FormatFullLines(ctx)
// Build and return the full test
for _, ml := range m.MLines {
mesostic += "\n" + ml
}
m.Poem = mesostic
return mesostic
}
// FormatFullLines builds the final line entries
// Caller holds the lock
func (m *Mesostic) FormatFullLines(ctx context.Context) bool {
ctx, span := otel.Tracer("mesostic/mesosys").Start(ctx, "FormatFullLines")
defer span.End()
var line string
for i, lw := range m.LineWest {
east := m.LineEast[i]
west := strings.Repeat(" ", m.WWidth-len(lw)) + lw
line = west + east
// This should be the only place m.MLines is modified
m.MLines = append(m.MLines, line)
}
return true
}
func isStruct(i interface{}) bool {
v := reflect.ValueOf(i)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
return v.Kind() == reflect.Struct
}
// FormatLine creates the mesostic line,
// without operating on the Spine String itself
// Caller holds the lock
func (m *Mesostic) FormatLine(ctx context.Context, line string) bool {
ctx, span := otel.Tracer("mesostic/mesosys").Start(ctx, "FormatLine")
defer span.End()
if len(m.Spine) == 0 {
span.RecordError(fmt.Errorf("no spinestring found"))
slog.Error("No spinestring found!",
slog.String("line", line),
slog.String("date", m.Date),
slog.String("spine", strings.Join(m.Spine, " ")),
slog.String("source_title", m.Title))
return false
}
ssChar := m.Spine[m.SpineIdx]
nxChar := m.Spine[(m.SpineIdx+1)%len(m.Spine)]
chars := make(map[string][]string)
lowerline := strings.ToLower(line)
// Step through each rune in the line
mode := "west"
for _, c := range lowerline {
char := string(c)
if char != ssChar { // Not the Spine String, either side of it
// If the next char in the SS is found,
// drop from here and start the next line
if mode == "east" && char == nxChar {
break
}
chars[mode] = append(chars[mode], char)
} else if char == ssChar { // This is the Spine String
// If this is a repeat of the SS char,
// drop from here and start the next line
if mode == "east" {
break
}
// Uppercase the SpineString character
char = strings.ToUpper(char)
chars[mode] = append(chars[mode], char)
mode = "east"
}
}
// Any line that makes it through with mode=west isn't used.
// Return 'false' without formatting a line.
if mode == "west" {
return false
}
// Record each side of the Spine String as west|east lines
var westline, eastline string
westline = strings.TrimSpace(strings.Join(chars["west"], ""))
// Now, if west is empty, it contained whitespace,
// so make the entire line whitespace.
if westline == "" {
eastline = ""
} else {
// Not using TrimSpace here because we want the front space
// when the SpineString appears at the end of the previous word.
eastline = strings.Join(chars["east"], "")
}
// Append the new lines
m.LineWest = append(m.LineWest, westline)
m.LineEast = append(m.LineEast, eastline)
// Record the widest line.
// This allows the mesostic to be printed as a function of the widest line,
// which keeps the SpineString centered down the exact middle of the poem.
mline := westline + eastline
m.Width = wider(len(mline), m.Width)
m.WWidth = wider(len(westline), m.WWidth)
return true
}
func wider(a, b int) int {
if a > b {
return a
}
return b
}
// ParseSourceJSON validates and transforms the raw text into usable entry text (???)
// It takes a pointer to the struct for decoding.
func (m *Mesostic) ParseSourceJSON(ctx context.Context, ps interface{}) bool {
ctx, span := otel.Tracer("mesostic/new").Start(ctx, "ParseSourceJSON")
defer span.End()
m.MU.Lock()
defer m.MU.Unlock()
if !isStruct(ps) {
err := fmt.Errorf("not a recognized JSON target")
span.RecordError(err)
slog.Error("not a recognized JSON target")
return false
}
decoder := json.NewDecoder(m.Source)
if err := decoder.Decode(&ps); err != nil {
span.RecordError(err)
slog.Error("Mesostic.JSON.Decoder Error", slog.Any("error", err))
return false
}
return true
}
// ParseSpine changes the Title into a lowercase slice without whitespace
//
// When set to a non-empty value, /ss/ overrides m.Title
func (m *Mesostic) ParseSpine(ctx context.Context, ss string, keepSpace bool) bool {
ctx, span := otel.Tracer("mesostic/new").Start(ctx, "ParseSpine")
defer span.End()
m.MU.Lock()
defer m.MU.Unlock()
var spine string
maxLen := 32
// Set the title as the spinestring if /ss/ is empty,
// always cut the spinestring off at maxLen
if ss == "" {
slog.Debug("Empty spine, using title", slog.String("title", m.Title))
if len(m.Title) > maxLen {
spine = m.Title[:maxLen]
} else {
spine = m.Title
}
} else {
slog.Debug("Spine from configuration", slog.String("spine", ss))
if len(ss) > maxLen {
spine = ss[:maxLen]
} else {
spine = ss
}
}
for _, c := range spine {
if !keepSpace {
// Create the Spine by removing whitespace and setting all lowercase
if !unicode.IsSpace(c) {
m.Spine = append(m.Spine, strings.ToLower(string(c)))
}
} else {
// Keep all whitespace
m.Spine = append(m.Spine, strings.ToLower(string(c)))
}
}
return true
}