-
Notifications
You must be signed in to change notification settings - Fork 221
/
state.go
80 lines (65 loc) · 2.29 KB
/
state.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
// Package state implements setters and getters for command contexts.
package state
import (
"context"
"path/filepath"
"github.com/superfly/flyctl/internal/config"
)
type contextKeyType int
const (
_ contextKeyType = iota
hostnameKey
workDirKey
userHomeDirKey
configDirKey
)
// WithHostname returns a copy of ctx that carries hostname.
func WithHostname(ctx context.Context, hostname string) context.Context {
return set(ctx, hostnameKey, hostname)
}
// Hostname returns the hostname ctx carries. It panics in case ctx carries no
// hostname.
func Hostname(ctx context.Context) string {
return get(ctx, hostnameKey).(string)
}
// WithWorkingDirectory derives a Context that carries the given working
// directory from ctx.
func WithWorkingDirectory(ctx context.Context, wd string) context.Context {
return set(ctx, workDirKey, wd)
}
// WorkingDirectory returns the working directory ctx carries. It panics in case
// ctx carries no working directory.
func WorkingDirectory(ctx context.Context) string {
return get(ctx, workDirKey).(string)
}
// WithUserHomeDirectory derives a Context that carries the given user home
// directory from ctx.
func WithUserHomeDirectory(ctx context.Context, uhd string) context.Context {
return set(ctx, userHomeDirKey, uhd)
}
// UserHomeDirectory returns the user home directory ctx carries. It panics in
// case ctx carries no user home directory.
func UserHomeDirectory(ctx context.Context) string {
return get(ctx, userHomeDirKey).(string)
}
// WithConfigDir derives a Context that carries the given config directory from
// ctx.
func WithConfigDirectory(ctx context.Context, cd string) context.Context {
return set(ctx, configDirKey, cd)
}
// ConfigDirectory returns the config directory ctx carries. It panics in case
// ctx carries no config directory.
func ConfigDirectory(ctx context.Context) string {
return get(ctx, configDirKey).(string)
}
// ConfigFile returns the config file ctx carries. It panics in case
// ctx carries no config directory.
func ConfigFile(ctx context.Context) string {
return filepath.Join(ConfigDirectory(ctx), config.FileName)
}
func get(ctx context.Context, key contextKeyType) interface{} {
return ctx.Value(key)
}
func set(ctx context.Context, key contextKeyType, val interface{}) context.Context {
return context.WithValue(ctx, key, val)
}