Skip to content

Commit a7bea72

Browse files
committed
add human readable time field
1 parent 32c46fe commit a7bea72

File tree

2 files changed

+58
-38
lines changed

2 files changed

+58
-38
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package framework
33
import (
44
"bytes"
55
"context"
6+
"encoding/json"
67
"errors"
78
"fmt"
89
"github.com/davecgh/go-spew/spew"
@@ -18,6 +19,7 @@ import (
1819
"strings"
1920
"testing"
2021
"text/template"
22+
"time"
2123
)
2224

2325
const (
@@ -297,3 +299,59 @@ func applyEnvConfig(prefix string, input interface{}) error {
297299
}
298300
return nil
299301
}
302+
303+
func UseCache() bool {
304+
return os.Getenv("CTF_USE_CACHED_OUTPUTS") == "true"
305+
}
306+
307+
func getBaseConfigPath() (string, error) {
308+
configs := os.Getenv("CTF_CONFIGS")
309+
if configs == "" {
310+
return "", fmt.Errorf("no %s env var is provided, you should provide at least one test promtailConfig in TOML", EnvVarTestConfigs)
311+
}
312+
return strings.Split(configs, ",")[0], nil
313+
}
314+
315+
func Store[T any](cfg *T) error {
316+
if UseCache() {
317+
return nil
318+
}
319+
baseConfigPath, err := getBaseConfigPath()
320+
if err != nil {
321+
return err
322+
}
323+
cachedOutName := fmt.Sprintf("%s-cache.toml", strings.Replace(baseConfigPath, ".toml", "", -1))
324+
L.Info().Str("OutputFile", cachedOutName).Msg("Storing configuration output")
325+
d, err := toml.Marshal(cfg)
326+
if err != nil {
327+
return err
328+
}
329+
return os.WriteFile(filepath.Join(DefaultConfigDir, cachedOutName), d, os.ModePerm)
330+
}
331+
332+
// JSONStrDuration is JSON friendly duration that can be parsed from "1h2m0s" Go format
333+
type JSONStrDuration struct {
334+
time.Duration
335+
}
336+
337+
func (d *JSONStrDuration) MarshalJSON() ([]byte, error) {
338+
return json.Marshal(d.String())
339+
}
340+
341+
func (d *JSONStrDuration) UnmarshalJSON(b []byte) error {
342+
var v interface{}
343+
if err := json.Unmarshal(b, &v); err != nil {
344+
return err
345+
}
346+
switch value := v.(type) {
347+
case string:
348+
var err error
349+
d.Duration, err = time.ParseDuration(value)
350+
if err != nil {
351+
return err
352+
}
353+
return nil
354+
default:
355+
return errors.New("invalid duration")
356+
}
357+
}

framework/output.go

Lines changed: 0 additions & 38 deletions
This file was deleted.

0 commit comments

Comments
 (0)