1
1
mirror of https://github.com/drone-plugins/github-actions synced 2024-11-15 02:56:25 +01:00
github.com-drone-plugins-gi.../utils/env.go

56 lines
1.2 KiB
Go
Raw Normal View History

2021-10-07 13:29:35 +02:00
package utils
import (
"os"
"strings"
2021-10-07 14:34:00 +02:00
"github.com/joho/godotenv"
2021-10-07 13:29:35 +02:00
"github.com/pkg/errors"
)
func CreateEnvAndSecretFile(envFile, secretFile string, secrets []string) error {
envVars := getEnvVars()
2021-10-07 14:34:00 +02:00
actionEnvVars := make(map[string]string)
2021-10-07 13:29:35 +02:00
for key, val := range envVars {
if !strings.HasPrefix(key, "PLUGIN_") && !Exists(secrets, key) {
2021-10-07 14:34:00 +02:00
actionEnvVars[key] = val
2021-10-07 13:29:35 +02:00
}
}
2021-10-07 14:34:00 +02:00
secretEnvVars := make(map[string]string)
2021-10-07 13:29:35 +02:00
for _, secretName := range secrets {
if os.Getenv(secretName) != "" {
2021-10-07 14:34:00 +02:00
secretEnvVars[secretName] = os.Getenv(secretName)
2021-10-07 13:29:35 +02:00
}
}
2021-10-07 14:34:00 +02:00
if err := godotenv.Write(actionEnvVars, envFile); err != nil {
2021-10-07 13:29:35 +02:00
return errors.Wrap(err, "failed to write environment variables file")
}
2021-10-07 14:34:00 +02:00
if err := godotenv.Write(secretEnvVars, secretFile); err != nil {
2021-10-07 13:29:35 +02:00
return errors.Wrap(err, "failed to write secret variables file")
}
return nil
}
// Return environment variables set in a map format
func getEnvVars() map[string]string {
m := make(map[string]string)
for _, e := range os.Environ() {
if i := strings.Index(e, "="); i >= 0 {
m[e[:i]] = e[i+1:]
}
}
return m
}
func Exists(slice []string, val string) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}