This repository has been archived by the owner on Apr 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
environment.go
200 lines (177 loc) · 6.31 KB
/
environment.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
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
package sprbox
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
)
// EnvVarKey is the environment variable that
// determine the build environment in sprbox.
const EnvVarKey = "BUILD_ENV"
var (
// BUILDENV define the current environment.
// Can be defined by code or, since it is an exported string,
// can be interpolated with -ldflags at build/run time:
// go build -ldflags "-X github.com/oblq/goms/env.TAG=develop" -v -o ./api_bin ./api
//
// If TAG is empty then the environment variable 'BUILD_ENV' will be used.
//
// If also the 'BUILD_ENV' environment variable is empty,
// if you have setup the VCS var, then the git.BranchName will be used.
// Git-Flow automatic environment selection based on branch name is also supported.
// Here the default environment RegEx, you can customize them as you want:
// - Production exps: Exps{"production", "master"}
// - Staging exps: Exps{"staging", "release/*", "hotfix/*"}
// - Testing exps: Exps{"testing", "test"}
// - Development exps: Exps{"development", "develop", "dev", "feature/*"}
// - Local exps: Exps{"local"}
BUILDENV = ""
// VCS is the project version control system.
// By default it uses the working directory.
VCS = NewRepository("./")
privateTAG = ""
mutex sync.Mutex
)
// Default environment's configuration
var (
Production = &Environment{id: "production", exps: []string{"production", "master"}, RunCompiled: true}
Staging = &Environment{id: "staging", exps: []string{"staging", "release/*", "hotfix/*"}, RunCompiled: true}
Testing = &Environment{id: "testing", exps: []string{"testing", "test"}, RunCompiled: false}
Development = &Environment{id: "development", exps: []string{"development", "develop", "dev", "feature/*"}, RunCompiled: false}
Local = &Environment{id: "local", exps: []string{"local"}, RunCompiled: false}
)
func init() {
Production.compileExps()
Staging.compileExps()
Testing.compileExps()
Development.compileExps()
Local.compileExps()
}
var testingRegexp = regexp.MustCompile(`_test|(\.test$)|_Test`)
var inferredBy string
// Env returns the current selected environment by
// matching the privateTAG variable against the environments RegEx.
func Env() *Environment {
mutex.Lock()
defer mutex.Unlock()
// loading tag
if len(BUILDENV) > 0 {
privateTAG = BUILDENV
inferredBy = fmt.Sprintf("'%s', inferred from 'BUILDENV' var, set manually.", privateTAG)
//return
} else if privateTAG = os.Getenv(EnvVarKey); len(privateTAG) > 0 {
inferredBy = fmt.Sprintf("'%s', inferred from '%s' environment variable.", privateTAG, EnvVarKey)
//return
} else if VCS != nil {
if VCS.Error == nil {
privateTAG = VCS.BranchName
inferredBy = fmt.Sprintf("<empty>, inferred from git.BranchName (%s).", VCS.BranchName)
//return
}
} else if testingRegexp.MatchString(os.Args[0]) {
privateTAG = Testing.ID()
inferredBy = fmt.Sprintf("'%s', inferred from the running file name (%s).", privateTAG, os.Args[0])
//return
} else {
inferredBy = "<empty>, default environment is 'local'."
}
switch {
case Production.MatchTag(privateTAG):
return Production
case Staging.MatchTag(privateTAG):
return Staging
case Testing.MatchTag(privateTAG):
return Testing
case Development.MatchTag(privateTAG):
return Development
case Local.MatchTag(privateTAG):
return Local
default:
return Local
}
}
// EnvSubDir returns <path>/<environment>
func EnvSubDir(path string) string {
return filepath.Join(path, Env().ID())
}
// CompiledPath returns the path base if RunCompiled == true
// for the environment in use so that static files can
// stay side by side with the executable
// while it is possible to have a different location when the
// program is launched with `go run`.
// This allow to manage multiple packages in one project during development,
// for instance using a config path in the parent dir, side by side with
// the packages, while having the same config folder side by side with
// the executable where needed.
//
// Can be used in:
// sprbox.LoadToolBox(&myToolBox, sprbox.CompiledPath("../config"))
//
// Example:
// sprbox.Development.RunCompiled = false
// sprbox.BUILDENV = sprbox.Development.ID()
// sprbox.CompiledPath("../static_files/config") // -> "../static_files/config"
//
// sprbox.Development.RunCompiled = true
// sprbox.BUILDENV = sprbox.Development.ID()
// sprbox.CompiledPath("../static_files/config") // -> "config"
//
// By default only Production and Staging environments have RunCompiled = true.
func CompiledPath(path string) string {
if Env().RunCompiled {
return filepath.Base(path)
}
return path
}
// Environment struct.
type Environment struct {
id string
exps []string
regexp *regexp.Regexp
// RunCompiled true means that the program run from
// a precompiled binary for that environment.
// CompiledPath() returns the path base if RunCompiled == true
// so that static files can stay side by side with the executable
// while it is possible to have a different location when the
// program is launched with `go run`.
//
// By default only Production and Staging environments have RunCompiled = true.
RunCompiled bool
}
// MatchTag check if the passed tag match that environment,
// a tag may be the branch name or the machine hostname or whatever you want.
func (e *Environment) MatchTag(tag string) bool {
return e.regexp.MatchString(tag)
}
// AppendExp add a regular expression to match that environment.
func (e *Environment) AppendExp(exp string) {
e.exps = append(e.exps, exp)
e.compileExps()
}
// SetExps set regular expressions to match that environment.
func (e *Environment) SetExps(exps []string) {
e.exps = exps
e.compileExps()
}
func (e *Environment) compileExps() {
regex := "(" + strings.Join(e.exps, ")|(") + ")"
e.regexp = regexp.MustCompile(regex)
}
// ID returns the environment id,
// which are also a valid tag for the current environment.
func (e *Environment) ID() string {
return e.id
}
// Info return some environment info.
func (e *Environment) Info() string {
return fmt.Sprintf("%s - tag: %s\n", strings.ToUpper(e.ID()), inferredBy)
}
// PrintInfo print some environment info in console.
func (e *Environment) PrintInfo() {
info := fmt.Sprintf("%s - tag: %s\n", green(strings.ToUpper(e.ID())), inferredBy)
envLog := kvLogger{}
envLog.Println("Environment:", info)
//envLog.Println("Config path:", ansi.Green(ConfigPathByEnv(configPath))+"\n")
}