WriteProjectEnvFile writes the passed envText into the envFilePath .env file changing items in envMap changed in envText there
(envFilePath string, envMap map[string]string, envText string)
| 28 | // WriteProjectEnvFile writes the passed envText into the envFilePath .env file |
| 29 | // changing items in envMap changed in envText there |
| 30 | func WriteProjectEnvFile(envFilePath string, envMap map[string]string, envText string) error { |
| 31 | for k, v := range envMap { |
| 32 | v = EscapeEnvFileValue(v) |
| 33 | // If the item is already in envText, use regex to replace it |
| 34 | // otherwise, append it to the envText. |
| 35 | // (^|[\r\n]+) - first group $1 matches the start of a line or newline characters |
| 36 | // #*[ \t]* - matches optional comments with spaces/tabs, i.e. find lines like '# FOO=BAR' |
| 37 | // (%s) - second group $2 matches the variable name (QuoteMeta escapes dots and other |
| 38 | // regex special chars, e.g. for CodeIgniter's "database.default.hostname") |
| 39 | // [ \t]*=[ \t]* - matches equals sign with optional spaces/tabs |
| 40 | exp := regexp.MustCompile(fmt.Sprintf(`(^|[\r\n]+)#*[ \t]*(%s)[ \t]*=[ \t]*(.*)`, regexp.QuoteMeta(k))) |
| 41 | if exp.MatchString(envText) { |
| 42 | // To insert a literal $ in the output, use $$ in the template. |
| 43 | // See https://pkg.go.dev/regexp?utm_source=godoc#Regexp.Expand |
| 44 | v = strings.ReplaceAll(v, `$`, `$$`) |
| 45 | // Remove comments with whitespaces here using only $1 and $2 groups |
| 46 | envText = exp.ReplaceAllString(envText, fmt.Sprintf(`$1$2=%s`, v)) |
| 47 | } else { |
| 48 | envText = strings.TrimSuffix(envText, "\n") |
| 49 | if envText != "" { |
| 50 | envText = fmt.Sprintf("%s\n%s=%s\n", envText, k, v) |
| 51 | } else { |
| 52 | envText = fmt.Sprintf("%s=%s\n", k, v) |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | err := fileutil.TemplateStringToFile(envText, nil, envFilePath) |
| 57 | if err != nil { |
| 58 | return err |
| 59 | } |
| 60 | return nil |
| 61 | } |
| 62 | |
| 63 | // EscapeEnvFileValue escapes the value so it can be used in an .env file |
| 64 | // The value is wrapped in double quotes for correct work with spaces. |