-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime.go
116 lines (103 loc) · 2.51 KB
/
runtime.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
package ma
import (
"fmt"
"regexp"
"time"
"github.com/bzimmer/smugmug"
"github.com/hashicorp/go-metrics"
"github.com/rs/zerolog/log"
"github.com/spf13/afero"
"github.com/urfave/cli/v2"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
// RuntimeKey in app metadata
const RuntimeKey = "github.com/bzimmer/ma#RuntimeKey"
// Runtime for access to runtime components
type Runtime struct {
// Encoder encodes a struct
Encoder Encoder
// Smugmug returns a smugmug client
Smugmug SmugmugFunc
// Sink for metrics
Sink *metrics.InmemSink
// Metrics for capturing metrics
Metrics *metrics.Metrics
// Fs for file access
Fs afero.Fs
// Grab for bulk querying images
Grab Grab
// Language for title case
Language language.Tag
// Start time of the execution
Start time.Time
}
// SmugmugFunc returns a smugmug client
// panics if credentials are not provided
type SmugmugFunc func() *smugmug.Client
// Encoder encodes a struct to a specific format
type Encoder interface {
// Encode writes the encoding of v
Encode(v any) error
}
func runtime(c *cli.Context) *Runtime {
switch t := c.App.Metadata[RuntimeKey].(type) {
case *Runtime:
return t
default:
panic("incorrect context")
}
}
func albumOrNode(c *cli.Context) error {
node := c.Bool("node")
album := c.Bool("album")
if !(album || node) {
if err := c.Set("node", "true"); err != nil {
return err
}
if err := c.Set("album", "true"); err != nil {
return err
}
}
return nil
}
// Metrics (if enabled) emits the metrics as json
func Metrics(c *cli.Context) error {
if len(c.App.Metadata) == 0 {
return nil
}
runtime(c).Metrics.AddSample(
[]string{"elapsed"}, float32(time.Since(runtime(c).Start).Milliseconds()))
data := runtime(c).Sink.Data()
for i := range data {
for key, val := range data[i].Counters {
log.Info().
Int("count", val.Count).
Str("metric", key).
Msg("counters")
}
for key, val := range data[i].Samples {
as := val.AggregateSample
log.Info().
Int("count", val.Count).
Str("metric", key).
Float64("min", as.Min).
Float64("max", as.Max).
Float64("mean", as.Mean()).
Float64("stddev", as.Stddev()).
Msg("samples")
}
}
return nil
}
func titlecase(c *cli.Context, s string) string {
title := cases.Title(runtime(c).Language)
return title.String(s)
}
var imageRE = regexp.MustCompile(`[a-zA-Z0-9]+-\d+`)
type InvalidVersionError struct {
ImageKey string
}
func (x *InvalidVersionError) Error() string {
return fmt.Sprintf("no version specified for image key {%s}", x.ImageKey)
}