MCPcopy Index your code
hub / github.com/ddev/ddev / WriteProjectEnvFile

Function WriteProjectEnvFile

pkg/ddevapp/envfile.go:30–61  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

28// WriteProjectEnvFile writes the passed envText into the envFilePath .env file
29// changing items in envMap changed in envText there
30func 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.

Callers 12

shopware6PostStartActionFunction · 0.92
TestWriteProjectEnvFileFunction · 0.92
dotenv-set.goFile · 0.92
symfonyPostStartActionFunction · 0.85
asteriosPostStartActionFunction · 0.85
shopware6PostStartActionFunction · 0.85
cakephpPostStartActionFunction · 0.85
updateCraftCMSDotEnvFunction · 0.85
laravelPostStartActionFunction · 0.85
wpBedrockPostStartActionFunction · 0.85

Calls 2

TemplateStringToFileFunction · 0.92
EscapeEnvFileValueFunction · 0.85

Tested by 2

shopware6PostStartActionFunction · 0.74
TestWriteProjectEnvFileFunction · 0.74