This repository has been archived by the owner on May 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
72 lines (60 loc) · 1.54 KB
/
env.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
package env
import (
"errors"
"fmt"
basestrings "strings"
"syscall"
"github.com/jedib0t/go-pretty/table"
"github.com/jedib0t/go-pretty/text"
"github.com/ppcamp/go-xtendlib/interfaces"
)
var (
ErrFlagRequired error = errors.New("the flag is required")
)
func fromEnv(envVar string) (string, bool) {
envVar = basestrings.TrimSpace(envVar)
return syscall.Getenv(envVar)
}
// isEmpty check if the value has the same value as an unitialized variable
func isEmpty[T interfaces.Ordered](value T) bool {
var r T
return r == value
}
type Flag interface {
Apply() error
fmt.Stringer
Name() string
CurrentValue() any
IsRequired() bool
DefaultValue() any
}
type Flags []Flag
// Parse the passed flags
func Parse(flags Flags) error {
for _, v := range flags {
if err := v.Apply(); err != nil {
return fmt.Errorf("fail to parse %w", err)
}
}
return nil
}
func (s Flags) String() string {
t := table.NewWriter()
t.SetTitle("\nFlags\n")
t.AppendHeader(table.Row{"Var Name", "Required", "Default Value", "Current Value"})
style := table.StyleLight
style.Format.Header = text.FormatDefault
t.SetStyle(style)
t.SetColumnConfigs([]table.ColumnConfig{
{WidthMax: 6, ColorsHeader: []text.Color{text.BgCyan}},
{WidthMax: 3, ColorsHeader: []text.Color{text.BgCyan}},
{WidthMax: 10, ColorsHeader: []text.Color{text.BgCyan}},
{WidthMax: 10, ColorsHeader: []text.Color{text.BgCyan}},
})
for _, flag := range s {
t.AppendRows([]table.Row{
{flag.Name(), flag.IsRequired(), flag.DefaultValue(), flag.CurrentValue()},
})
}
return t.Render()
}