Skip to content
This repository was archived by the owner on Aug 17, 2020. It is now read-only.

Commit 5f0fb89

Browse files
committed
Removes old env package and changed to use the new config package
1 parent 663bb47 commit 5f0fb89

File tree

13 files changed

+136
-250
lines changed

13 files changed

+136
-250
lines changed

agent/agent.go

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import (
1919
"github.com/opentracing/opentracing-go"
2020

2121
"go.undefinedlabs.com/scopeagent/config"
22-
"go.undefinedlabs.com/scopeagent/env"
2322
scopeError "go.undefinedlabs.com/scopeagent/errors"
2423
"go.undefinedlabs.com/scopeagent/instrumentation"
2524
"go.undefinedlabs.com/scopeagent/runner"
@@ -64,6 +63,8 @@ var (
6463

6564
testingModeFrequency = time.Second
6665
nonTestingModeFrequency = time.Minute
66+
67+
cfg = config.Get()
6768
)
6869

6970
func WithApiKey(apiKey string) Option {
@@ -194,13 +195,13 @@ func NewAgent(options ...Option) (*Agent, error) {
194195
agent.logger = log.New(ioutil.Discard, "", 0)
195196
}
196197

197-
agent.debugMode = agent.debugMode || env.ScopeDebug.Value
198+
agent.debugMode = agent.debugMode || *cfg.Debug
198199

199200
configProfile := GetConfigCurrentProfile()
200201

201202
if agent.apiKey == "" || agent.apiEndpoint == "" {
202-
if dsn, set := env.ScopeDsn.Tuple(); set && dsn != "" {
203-
dsnApiKey, dsnApiEndpoint, dsnErr := parseDSN(dsn)
203+
if cfg.Dsn != nil && *cfg.Dsn != "" {
204+
dsnApiKey, dsnApiEndpoint, dsnErr := parseDSN(*cfg.Dsn)
204205
if dsnErr != nil {
205206
agent.logger.Printf("Error parsing dsn value: %v\n", dsnErr)
206207
} else {
@@ -213,8 +214,8 @@ func NewAgent(options ...Option) (*Agent, error) {
213214
}
214215

215216
if agent.apiKey == "" {
216-
if apiKey, set := env.ScopeApiKey.Tuple(); set && apiKey != "" {
217-
agent.apiKey = apiKey
217+
if cfg.ApiKey != nil && *cfg.ApiKey != "" {
218+
agent.apiKey = *cfg.ApiKey
218219
} else if configProfile != nil {
219220
agent.logger.Println("API key found in the native app configuration")
220221
agent.apiKey = configProfile.ApiKey
@@ -226,12 +227,13 @@ func NewAgent(options ...Option) (*Agent, error) {
226227
}
227228

228229
if agent.apiEndpoint == "" {
229-
if endpoint, set := env.ScopeApiEndpoint.Tuple(); set && endpoint != "" {
230-
agent.apiEndpoint = endpoint
230+
if cfg.ApiEndpoint != nil && *cfg.ApiEndpoint != "" {
231+
agent.apiEndpoint = *cfg.ApiEndpoint
231232
} else if configProfile != nil {
232233
agent.logger.Println("API endpoint found in the native app configuration")
233234
agent.apiEndpoint = configProfile.ApiEndpoint
234235
} else {
236+
endpoint := "https://app.scope.dev"
235237
agent.logger.Printf("using default endpoint: %v\n", endpoint)
236238
agent.apiEndpoint = endpoint
237239
}
@@ -271,13 +273,19 @@ func NewAgent(options ...Option) (*Agent, error) {
271273
agent.metadata[tags.GoVersion] = runtime.Version()
272274

273275
// Service name
274-
addElementToMapIfEmpty(agent.metadata, tags.Service, env.ScopeService.Value)
276+
if cfg.Service != nil {
277+
addElementToMapIfEmpty(agent.metadata, tags.Service, *cfg.Service)
278+
}
275279

276280
// Configurations
277-
addElementToMapIfEmpty(agent.metadata, tags.ConfigurationKeys, env.ScopeConfiguration.Value)
281+
if cfg.Configuration != nil {
282+
addElementToMapIfEmpty(agent.metadata, tags.ConfigurationKeys, cfg.Configuration)
283+
}
278284

279285
// Metadata
280-
addToMapIfEmpty(agent.metadata, env.ScopeMetadata.Value)
286+
if cfg.Metadata != nil {
287+
addToMapIfEmpty(agent.metadata, cfg.Metadata)
288+
}
281289

282290
// Git data
283291
addToMapIfEmpty(agent.metadata, getGitInfoFromEnv())
@@ -292,26 +300,26 @@ func NewAgent(options ...Option) (*Agent, error) {
292300
agent.metadata[tags.Dependencies] = getDependencyMap()
293301

294302
// Expand '~' in source root
295-
var sourceRoot string
296303
if sRoot, ok := agent.metadata[tags.SourceRoot]; ok {
297304
if sRootEx, err := homedir.Expand(sRoot.(string)); err == nil {
298-
sourceRoot = sRootEx
299305
agent.metadata[tags.SourceRoot] = sRootEx
300306
}
301307
}
302308

303309
if !agent.testingMode {
304-
if env.ScopeTestingMode.IsSet {
305-
agent.testingMode = env.ScopeTestingMode.Value
310+
if cfg.TestingMode != nil {
311+
agent.testingMode = *cfg.TestingMode
306312
} else {
307313
agent.testingMode = agent.metadata[tags.CI].(bool)
308314
}
309315
}
310316

311-
if agent.failRetriesCount == 0 {
312-
agent.failRetriesCount = env.ScopeTestingFailRetries.Value
317+
if agent.failRetriesCount == 0 && cfg.Instrumentation.TestsFrameworks.FailRetries != nil {
318+
agent.failRetriesCount = *cfg.Instrumentation.TestsFrameworks.FailRetries
319+
}
320+
if cfg.Instrumentation.TestsFrameworks.PanicAsFail != nil {
321+
agent.panicAsFail = agent.panicAsFail || *cfg.Instrumentation.TestsFrameworks.PanicAsFail
313322
}
314-
agent.panicAsFail = agent.panicAsFail || env.ScopeTestingPanicAsFail.Value
315323

316324
if agent.debugMode {
317325
agent.logMetadata()
@@ -339,10 +347,7 @@ func NewAgent(options ...Option) (*Agent, error) {
339347
})
340348
instrumentation.SetTracer(agent.tracer)
341349
instrumentation.SetLogger(agent.logger)
342-
if err := config.Load(path.Join(sourceRoot, "scope.yml")); err != nil {
343-
agent.logger.Println(err)
344-
}
345-
if agent.setGlobalTracer || env.ScopeTracerGlobal.Value {
350+
if agent.setGlobalTracer || (cfg.Tracer.Global != nil && *cfg.Tracer.Global) {
346351
opentracing.SetGlobalTracer(agent.Tracer())
347352
}
348353

@@ -408,8 +413,8 @@ func generateAgentID() string {
408413
}
409414

410415
func getLogPath() (string, error) {
411-
if env.ScopeLoggerRoot.IsSet {
412-
return env.ScopeLoggerRoot.Value, nil
416+
if cfg.Logger.Root != nil {
417+
return *cfg.Logger.Root, nil
413418
}
414419

415420
logFolder := ""

agent/agent_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"testing"
99
"time"
1010

11-
"go.undefinedlabs.com/scopeagent/env"
11+
"go.undefinedlabs.com/scopeagent/config"
1212
"go.undefinedlabs.com/scopeagent/tags"
1313
)
1414

@@ -133,7 +133,9 @@ func sameElements(a, b []string) bool {
133133
}
134134

135135
func TestTildeExpandRaceMetadata(t *testing.T) {
136-
env.ScopeSourceRoot.Value = "~/scope"
136+
cfg := config.Get()
137+
sroot := "~/scope"
138+
cfg.SourceRoot = &sroot
137139
agent, err := NewAgent(WithApiKey("123"), WithTestingModeEnabled())
138140
if err != nil {
139141
t.Fatal(err)

agent/git.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88

99
"github.com/google/uuid"
1010

11-
"go.undefinedlabs.com/scopeagent/env"
1211
"go.undefinedlabs.com/scopeagent/tags"
1312
)
1413

@@ -62,6 +61,10 @@ func getGitData() *GitData {
6261
}
6362

6463
func getGitDiff() *GitDiff {
64+
if cfg.Instrumentation.DiffSummary != nil && !*cfg.Instrumentation.DiffSummary {
65+
return nil
66+
}
67+
6568
var diff string
6669
if diffBytes, err := exec.Command("git", "diff", "--numstat").Output(); err == nil {
6770
diff = string(diffBytes)
@@ -128,17 +131,17 @@ func getGitInfoFromGitFolder() map[string]interface{} {
128131
func getGitInfoFromEnv() map[string]interface{} {
129132
gitInfo := map[string]interface{}{}
130133

131-
if repository, set := env.ScopeRepository.Tuple(); set && repository != "" {
132-
gitInfo[tags.Repository] = repository
134+
if cfg.Repository != nil && *cfg.Repository != "" {
135+
gitInfo[tags.Repository] = *cfg.Repository
133136
}
134-
if commit, set := env.ScopeCommitSha.Tuple(); set && commit != "" {
135-
gitInfo[tags.Commit] = commit
137+
if cfg.CommitSha != nil && *cfg.CommitSha != "" {
138+
gitInfo[tags.Commit] = *cfg.CommitSha
136139
}
137-
if sourceRoot, set := env.ScopeSourceRoot.Tuple(); set && sourceRoot != "" {
138-
gitInfo[tags.SourceRoot] = sourceRoot
140+
if cfg.SourceRoot != nil && *cfg.SourceRoot != "" {
141+
gitInfo[tags.SourceRoot] = *cfg.SourceRoot
139142
}
140-
if branch, set := env.ScopeBranch.Tuple(); set && branch != "" {
141-
gitInfo[tags.Branch] = branch
143+
if cfg.Branch != nil && *cfg.Branch != "" {
144+
gitInfo[tags.Branch] = *cfg.Branch
142145
}
143146

144147
return gitInfo

config/types.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ type (
44
ScopeConfig struct {
55
Dsn *string `env:"SCOPE_DSN"`
66
ApiKey *string `env:"SCOPE_APIKEY"`
7-
ApiEndpoint *string `env:"SCOPE_API_ENDPOINT" default:"https://app.scope.dev"`
7+
ApiEndpoint *string `env:"SCOPE_API_ENDPOINT"`
88
Service *string `yaml:"service" env:"SCOPE_SERVICE" default:"default"`
99
Repository *string `yaml:"repository" env:"SCOPE_REPOSITORY"`
1010
CommitSha *string `yaml:"commit_sha" env:"SCOPE_COMMIT_SHA"`
@@ -17,12 +17,13 @@ type (
1717
Instrumentation InstrumentationConfig `yaml:"instrumentation"`
1818
Tracer TracerConfig `yaml:"tracer"`
1919
Debug *bool `env:"SCOPE_DEBUG" default:"false"`
20+
ConfigPath *string
21+
LoadError error
2022
}
2123
LoggerConfig struct {
2224
Root *string `yaml:"root" env:"SCOPE_LOGGER_ROOT, SCOPE_LOG_ROOT_PATH"`
2325
}
2426
InstrumentationConfig struct {
25-
Enabled *bool `yaml:"enabled" env:"SCOPE_INSTRUMENTATION_ENABLED" default:"true"`
2627
DiffSummary *bool `yaml:"diff_summary" env:"SCOPE_INSTRUMENTATION_DIFF_SUMMARY" default:"true"`
2728
TestsFrameworks InstrumentationTestsFrameworksConfig `yaml:"tests_frameworks"`
2829
DB InstrumentationDatabaseConfig `yaml:"db"`

config/vars.go

Lines changed: 54 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package config
22

33
import (
4+
"errors"
5+
"fmt"
6+
"github.com/undefinedlabs/go-env"
7+
"gopkg.in/yaml.v2"
48
"io/ioutil"
59
"os"
10+
"path/filepath"
611
"sync"
7-
8-
env "github.com/undefinedlabs/go-env"
9-
"gopkg.in/yaml.v2"
1012
)
1113

1214
var (
@@ -15,31 +17,63 @@ var (
1517
)
1618

1719
func Get() *ScopeConfig {
20+
// We check is already loaded with a reader lock
1821
m.RLock()
19-
defer m.RUnlock()
20-
21-
return current
22-
}
22+
if current != nil {
23+
defer m.RUnlock()
24+
return current
25+
}
26+
m.RUnlock()
2327

24-
func Load(filePath string) error {
28+
// Is not loaded we block to load it
2529
m.Lock()
2630
defer m.Unlock()
27-
28-
file, err := os.Open(filePath)
31+
if current != nil {
32+
return current
33+
}
34+
var config ScopeConfig
35+
content, path, err := readConfigurationFile()
36+
if err == nil {
37+
config.ConfigPath = path
38+
_ = yaml.Unmarshal(content, &config)
39+
if config.Metadata != nil {
40+
for k, v := range config.Metadata {
41+
if str, ok := v.(string); ok {
42+
config.Metadata[k] = os.ExpandEnv(str)
43+
}
44+
}
45+
}
46+
} else {
47+
config.LoadError = err
48+
}
49+
_, err = env.UnmarshalFromEnviron(&config)
2950
if err != nil {
30-
return err
51+
config.LoadError = err
3152
}
32-
content, err := ioutil.ReadAll(file)
53+
current = &config
54+
return current
55+
}
56+
57+
func readConfigurationFile() ([]byte, *string, error) {
58+
dir, err := os.Getwd()
3359
if err != nil {
34-
return err
60+
return nil, nil, err
3561
}
62+
for {
63+
rel, _ := filepath.Rel("/", dir)
64+
// Exit the loop once we reach the basePath.
65+
if rel == "." {
66+
break
67+
}
3668

37-
var config ScopeConfig
38-
yamlErr := yaml.Unmarshal(content, &config)
39-
_, envErr := env.UnmarshalFromEnviron(&config)
40-
if yamlErr != nil && envErr != nil {
41-
return envErr
69+
path := fmt.Sprintf("%v/scope.yml", dir)
70+
dat, err := ioutil.ReadFile(path)
71+
if err == nil {
72+
return dat, &path, nil
73+
}
74+
75+
// Going up!
76+
dir += "/.."
4277
}
43-
current = &config
44-
return nil
78+
return nil, nil, errors.New("configuration not found")
4579
}

0 commit comments

Comments
 (0)