-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.go
More file actions
415 lines (382 loc) · 10 KB
/
Copy pathformat.go
File metadata and controls
415 lines (382 loc) · 10 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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package cmd
import (
"encoding/json"
"fmt"
"io"
"os"
"reflect"
"sort"
"strings"
"github.com/quantcli/crono-export-cli/internal/cronoapi"
"github.com/spf13/cobra"
)
type recordKind int
const (
kindServings recordKind = iota
kindNutrition
kindBiometrics
kindExercises
kindNotes
)
// AddFormatFlags registers --format on every export subcommand, per the
// quantcli shared contract §4.
// https://github.com/quantcli/common/blob/main/CONTRACT.md#4-output-format
func AddFormatFlags(cmd *cobra.Command) {
cmd.Flags().String("format", "markdown",
"Output format: markdown (default, fitdown-style) or json")
}
// ValidateExportFlags is a PreRunE that fails fast on bad --format or date
// flags before any network call is made. Without this, a typo in --format
// would burn a Cronometer login attempt against the rate limit.
func ValidateExportFlags(cmd *cobra.Command, _ []string) error {
if _, err := chosenFormat(cmd); err != nil {
return err
}
return nil
}
func chosenFormat(cmd *cobra.Command) (string, error) {
f, _ := cmd.Flags().GetString("format")
switch f {
case "", "markdown", "md":
return "markdown", nil
case "json":
return "json", nil
default:
return "", fmt.Errorf("unknown --format %q (use markdown or json)", f)
}
}
// emit writes v in the format chosen on cmd. kind tells the markdown
// renderer which layout to use.
func emit(cmd *cobra.Command, kind recordKind, v any) error {
f, err := chosenFormat(cmd)
if err != nil {
return err
}
if f == "json" {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(v)
}
return renderMarkdown(os.Stdout, kind, v)
}
func renderMarkdown(w io.Writer, kind recordKind, v any) error {
switch kind {
case kindServings:
recs, _ := v.(cronoapi.ServingRecords)
return renderServings(w, recs)
case kindBiometrics:
recs, _ := v.(cronoapi.BiometricRecords)
return renderBiometrics(w, recs)
case kindExercises:
recs, _ := v.(cronoapi.ExerciseRecords)
return renderExercises(w, recs)
case kindNutrition:
rows, _ := v.([]map[string]any)
return renderNutrition(w, rows)
case kindNotes:
rows, _ := v.([]map[string]any)
return renderNotes(w, rows)
}
return fmt.Errorf("renderMarkdown: unknown kind %d", kind)
}
// ---- shared helpers ---------------------------------------------------
// noteEmpty writes a friendly "no records" note to stderr so humans see it,
// while keeping stdout clean per the contract's "data only on stdout" rule.
// w is ignored — kept for the renderer signatures.
func noteEmpty(_ io.Writer) error {
fmt.Fprintln(os.Stderr, "(no records in window)")
return nil
}
// emptyValueFor returns the typed empty value for a record kind. Used
// when the caller knows there are no records (e.g. inverted date range)
// and wants to emit them without making a network call.
func emptyValueFor(kind recordKind) any {
switch kind {
case kindServings:
return cronoapi.ServingRecords{}
case kindBiometrics:
return cronoapi.BiometricRecords{}
case kindExercises:
return cronoapi.ExerciseRecords{}
case kindNutrition, kindNotes:
return []map[string]any{}
}
return nil
}
// fmtFloat trims trailing zeros so 1.95 → "1.95" and 100.000 → "100".
func fmtFloat(f float64) string {
s := strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.4f", f), "0"), ".")
if s == "" || s == "-" {
return "0"
}
return s
}
// strippedSuffix splits a CamelCase Go field name like "EnergyKcal" or
// "B12Mg" into ("Energy","kcal") or ("B12","mg"). Order matters: longer
// suffixes first so we don't strip "g" out of "Mg".
func strippedSuffix(field string) (name, unit string) {
for _, suf := range []struct{ go_, display string }{
{"Kcal", "kcal"},
{"Mg", "mg"},
{"Ug", "µg"},
{"IU", "IU"},
{"G", "g"},
} {
if strings.HasSuffix(field, suf.go_) && len(field) > len(suf.go_) {
return field[:len(field)-len(suf.go_)], suf.display
}
}
return field, ""
}
// ---- servings ---------------------------------------------------------
func renderServings(w io.Writer, recs cronoapi.ServingRecords) error {
if len(recs) == 0 {
return noteEmpty(w)
}
// Group by local calendar date.
byDate := map[string][]cronoapi.ServingRecord{}
for _, r := range recs {
d := r.RecordedTime.Format("2006-01-02")
byDate[d] = append(byDate[d], r)
}
dates := make([]string, 0, len(byDate))
for d := range byDate {
dates = append(dates, d)
}
sort.Strings(dates)
for di, d := range dates {
if di > 0 {
fmt.Fprintln(w)
}
fmt.Fprintf(w, "## %s\n\n", d)
for _, r := range byDate[d] {
renderServingRecord(w, r)
}
}
fmt.Fprintln(w, "_zero-valued nutrients omitted; use --format json for the full row_")
return nil
}
func renderServingRecord(w io.Writer, r cronoapi.ServingRecord) {
header := fmt.Sprintf("### %s · %s", strDefault(r.Group, "—"), r.FoodName)
if r.QuantityValue != 0 || r.QuantityUnits != "" {
header += fmt.Sprintf(" (%s %s)", fmtFloat(r.QuantityValue), r.QuantityUnits)
}
fmt.Fprintln(w, header)
v := reflect.ValueOf(r)
t := v.Type()
skip := map[string]bool{
"RecordedTime": true,
"Group": true,
"FoodName": true,
"QuantityValue": true,
"QuantityUnits": true,
"Category": true,
}
for i := 0; i < t.NumField(); i++ {
fname := t.Field(i).Name
if skip[fname] {
continue
}
if v.Field(i).Kind() != reflect.Float64 {
continue
}
val := v.Field(i).Float()
if val == 0 {
continue
}
name, unit := strippedSuffix(fname)
if unit != "" {
fmt.Fprintf(w, "- %s: %s %s\n", name, fmtFloat(val), unit)
} else {
fmt.Fprintf(w, "- %s: %s\n", name, fmtFloat(val))
}
}
fmt.Fprintln(w)
}
func strDefault(s, fallback string) string {
if s == "" {
return fallback
}
return s
}
// ---- biometrics -------------------------------------------------------
func renderBiometrics(w io.Writer, recs cronoapi.BiometricRecords) error {
if len(recs) == 0 {
return noteEmpty(w)
}
byDate := map[string][]cronoapi.BiometricRecord{}
for _, r := range recs {
d := r.RecordedTime.Format("2006-01-02")
byDate[d] = append(byDate[d], r)
}
dates := make([]string, 0, len(byDate))
for d := range byDate {
dates = append(dates, d)
}
sort.Strings(dates)
for di, d := range dates {
if di > 0 {
fmt.Fprintln(w)
}
fmt.Fprintf(w, "## %s\n", d)
for _, r := range byDate[d] {
unit := r.Unit
if unit != "" {
unit = " " + unit
}
fmt.Fprintf(w, "- %s: %s%s\n", r.Metric, fmtFloat(r.Amount), unit)
}
}
return nil
}
// ---- exercises --------------------------------------------------------
func renderExercises(w io.Writer, recs cronoapi.ExerciseRecords) error {
if len(recs) == 0 {
return noteEmpty(w)
}
byDate := map[string][]cronoapi.ExerciseRecord{}
for _, r := range recs {
d := r.RecordedTime.Format("2006-01-02")
byDate[d] = append(byDate[d], r)
}
dates := make([]string, 0, len(byDate))
for d := range byDate {
dates = append(dates, d)
}
sort.Strings(dates)
for di, d := range dates {
if di > 0 {
fmt.Fprintln(w)
}
fmt.Fprintf(w, "## %s\n", d)
for _, r := range byDate[d] {
parts := []string{r.Exercise}
if r.Minutes != 0 {
parts = append(parts, fmtFloat(r.Minutes)+" min")
}
if r.CaloriesBurned != 0 {
parts = append(parts, fmtFloat(r.CaloriesBurned)+" kcal")
}
line := strings.Join(parts, ", ")
if r.Group != "" {
line += fmt.Sprintf(" (%s)", r.Group)
}
fmt.Fprintf(w, "- %s\n", line)
}
}
return nil
}
// ---- nutrition (daily totals, string-keyed CSV) ----------------------
func renderNutrition(w io.Writer, rows []map[string]any) error {
if len(rows) == 0 {
return noteEmpty(w)
}
// Sort by Date asc.
sort.SliceStable(rows, func(i, j int) bool {
return cellString(rows[i]["Date"]) < cellString(rows[j]["Date"])
})
for di, row := range rows {
if di > 0 {
fmt.Fprintln(w)
}
date := cellString(row["Date"])
if date == "" {
date = "(unknown date)"
}
fmt.Fprintf(w, "## %s\n", date)
keys := make([]string, 0, len(row))
for k := range row {
if k == "Date" {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := row[k]
if isZeroish(v) {
continue
}
fmt.Fprintf(w, "- %s: %s\n", k, cellString(v))
}
}
fmt.Fprintln(w)
fmt.Fprintln(w, "_zero-valued nutrients omitted; use --format json for the full row_")
return nil
}
// cellString renders a coerced CSV cell back to a display string. Floats
// drop trailing zeros so "1.5" stays "1.5" and "100" stays "100".
func cellString(v any) string {
switch x := v.(type) {
case nil:
return ""
case string:
return x
case float64:
return fmtFloat(x)
case bool:
if x {
return "true"
}
return "false"
default:
return fmt.Sprintf("%v", x)
}
}
// isZeroish reports whether a coerced CSV value should be hidden from the
// markdown output: nil, empty string, or numeric zero. "false" / "true" /
// arbitrary text is rendered.
func isZeroish(v any) bool {
switch x := v.(type) {
case nil:
return true
case string:
return x == ""
case float64:
return x == 0
}
return false
}
// ---- notes ------------------------------------------------------------
func renderNotes(w io.Writer, rows []map[string]any) error {
if len(rows) == 0 {
return noteEmpty(w)
}
dateKey := pickKey(rows[0], "Day", "Date")
noteKey := pickKey(rows[0], "Note", "Notes", "Comment")
timeKey := pickKey(rows[0], "Time")
for di, row := range rows {
if di > 0 {
fmt.Fprintln(w)
}
date := cellString(row[dateKey])
if date == "" {
date = "(unknown date)"
}
header := "## " + date
if t := cellString(row[timeKey]); t != "" {
header += " " + t
}
fmt.Fprintln(w, header)
if note := strings.TrimSpace(cellString(row[noteKey])); note != "" {
fmt.Fprintln(w, note)
} else {
// Fall back to dumping all non-empty fields if we can't find a Note column.
for k, v := range row {
if k == dateKey || k == timeKey || isZeroish(v) {
continue
}
fmt.Fprintf(w, "- %s: %s\n", k, cellString(v))
}
}
}
return nil
}
func pickKey(row map[string]any, candidates ...string) string {
for _, c := range candidates {
if _, ok := row[c]; ok {
return c
}
}
return ""
}