forked from 1Password/shell-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv_var_importer.go
50 lines (42 loc) · 1.48 KB
/
env_var_importer.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
package importer
import (
"context"
"os"
"github.com/1Password/shell-plugins/sdk"
)
// TryAllEnvVars tries the specified environment variables one by one and adds import candidates with
// the specified field for each environment variable that is set.
func TryAllEnvVars(fieldName sdk.FieldName, possibleEnvVarNames ...string) sdk.Importer {
return func(ctx context.Context, in sdk.ImportInput, out *sdk.ImportOutput) {
for _, envVarName := range possibleEnvVarNames {
attempt := out.NewAttempt(SourceEnvVars(envVarName))
if value := os.Getenv(envVarName); value != "" {
attempt.AddCandidate(sdk.ImportCandidate{
Fields: map[sdk.FieldName]string{
fieldName: value,
},
})
}
}
}
}
// TryEnvVarPair tries the specified environment variables and adds an import candidate if at least
// one environment variable is set.
func TryEnvVarPair(pairPossibilities map[string]sdk.FieldName) sdk.Importer {
return func(ctx context.Context, in sdk.ImportInput, out *sdk.ImportOutput) {
var envVarNames []string
candidateFields := make(map[sdk.FieldName]string)
for possibleEnvVarName, fieldName := range pairPossibilities {
if value := os.Getenv(possibleEnvVarName); value != "" {
candidateFields[fieldName] = value
}
envVarNames = append(envVarNames, possibleEnvVarName)
}
attempt := out.NewAttempt(SourceEnvVars(envVarNames...))
if len(candidateFields) > 0 {
attempt.AddCandidate(sdk.ImportCandidate{
Fields: candidateFields,
})
}
}
}