core/app/environment.go
core/app/environment.goBrowse 1970 files
693 tokens
2,699 bytes
Token encoding: o200k_base
Snapshot 21a254f
← Back to SKILL.md
1package app2 3import (4 "fmt"5 "os"6 "regexp"7 "strings"8)9 10type Environment struct {11 Variables map[string]string12}13 14func NewEnvironment(variables *map[string]string) *Environment {15 if variables == nil {16 variables = &map[string]string{}17 }18 19 return &Environment{Variables: *variables}20}21 22// FromEnvs collects variables from the given environment variable names23func FromEnvs(envs []string) (*Environment, error) {24 env := NewEnvironment(nil)25 re := regexp.MustCompile(`(?s)([A-Za-z0-9_+\-]*)(?:=?)(.*)`)26 27 for _, e := range envs {28 matches := re.FindStringSubmatch(e)29 if len(matches) < 3 {30 continue31 }32 33 name := matches[1]34 value := matches[2]35 36 if value == "" {37 // A bare NAME inherits from the process env; NAME= is skipped.38 if !strings.Contains(e, "=") {39 if v, ok := os.LookupEnv(name); ok {40 env.SetVariable(name, v)41 }42 }43 } else {44 env.SetVariable(name, value)45 }46 }47 48 return env, nil49}50 51// GetVariable returns the value of the given variable name52func (e *Environment) GetVariable(name string) string {53 return e.Variables[name]54}55 56// SetVariable stores a variable in the Environment57func (e *Environment) SetVariable(name, value string) {58 e.Variables[name] = value59}60 61// ConfigVariable returns the RAILPACK_ prefixed version of a variable name62func (e *Environment) ConfigVariable(name string) string {63 return fmt.Sprintf("RAILPACK_%s", name)64}65 66// returns the value of a RAILPACK_ prefixed variable with newlines removed67// Returns both the value and the name of the config variable68func (e *Environment) GetConfigVariable(name string) (string, string) {69 configVar := e.ConfigVariable(name)70 71 if val, exists := e.Variables[configVar]; exists {72 return strings.TrimSpace(val), configVar73 }74 return "", ""75}76 77// GetConfigVariableList returns a space-separated config variable as a list78// Returns both the list and the name of the config variable79func (e *Environment) GetConfigVariableList(name string) ([]string, string) {80 val, configVar := e.GetConfigVariable(name)81 if val == "" {82 return nil, ""83 }84 return strings.Split(val, " "), configVar85}86 87// checks if a RAILPACK_ prefixed variable is set to "1" or "true"88func (e *Environment) IsConfigVariableTruthy(name string) bool {89 if val, _ := e.GetConfigVariable(name); val != "" {90 lowerVal := strings.ToLower(val)91 return lowerVal == "1" || lowerVal == "true"92 }93 return false94}95 96// GetSecretsWithPrefix returns all secrets that have the given prefix97func (e *Environment) GetSecretsWithPrefix(prefix string) []string {98 secrets := []string{}99 for secretName := range e.Variables {100 if strings.HasPrefix(secretName, prefix) {101 secrets = append(secrets, secretName)102 }103 }104 return secrets105}106