Skip to content

Commit 3ad5e74

Browse files
committed
Add (simple) support for quoted multiline variables in .env files
Signed-off-by: Midas Lambrichts <midaslamb@gmail.com>
1 parent af8a349 commit 3ad5e74

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

stores/dotenv/store.go

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package dotenv //import "github.com/getsops/sops/v3/stores/dotenv"
33
import (
44
"bytes"
55
"fmt"
6+
"slices"
67
"sort"
78
"strings"
89

@@ -76,7 +77,32 @@ func (store *Store) LoadPlainFile(in []byte) (sops.TreeBranches, error) {
7677
var branches sops.TreeBranches
7778
var branch sops.TreeBranch
7879

79-
for _, line := range bytes.Split(in, []byte("\n")) {
80+
var lines [][]byte
81+
var inQuotes = false
82+
var currentQuoteChar byte = '"'
83+
var lastSplit = -1
84+
85+
for pos, char := range in {
86+
switch char {
87+
case '"', '\'', '`':
88+
if inQuotes {
89+
if currentQuoteChar == char {
90+
inQuotes = false
91+
}
92+
} else {
93+
inQuotes = true
94+
currentQuoteChar = char
95+
}
96+
case '\n':
97+
if !inQuotes {
98+
var line = in[lastSplit+1 : pos]
99+
lines = append(lines, line)
100+
lastSplit = pos
101+
}
102+
}
103+
}
104+
105+
for _, line := range lines {
80106
if len(line) == 0 {
81107
continue
82108
}
@@ -141,8 +167,15 @@ func (store *Store) EmitPlainFile(in sops.TreeBranches) ([]byte, error) {
141167
if comment, ok := item.Key.(sops.Comment); ok {
142168
line = fmt.Sprintf("#%s\n", comment.Value)
143169
} else {
144-
value := strings.Replace(item.Value.(string), "\n", "\\n", -1)
170+
stringValue := item.Value.(string)
171+
var value string
172+
if len(stringValue) == 0 || !slices.Contains([]byte{'"', '\'', '`'}, stringValue[0]) {
173+
value = strings.Replace(stringValue, "\n", "\\n", -1)
174+
} else {
175+
value = item.Value.(string)
176+
}
145177
line = fmt.Sprintf("%s=%s\n", item.Key, value)
178+
146179
}
147180
buffer.WriteString(line)
148181
}

stores/dotenv/store_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ VAR2=val2
1414
#comment
1515
VAR3_unencrypted=val3
1616
VAR4=val4\nval4
17+
VAR5="val5quoted"
18+
VAR6="val6
19+
quoted
20+
multiline"
21+
VAR7='val7
22+
multiline'
23+
VAR8='val8"
24+
mixing
25+
"quotes'
1726
`, "\n"))
1827

1928
var BRANCH = sops.TreeBranch{
@@ -37,6 +46,22 @@ var BRANCH = sops.TreeBranch{
3746
Key: "VAR4",
3847
Value: "val4\nval4",
3948
},
49+
sops.TreeItem{
50+
Key: "VAR5",
51+
Value: "\"val5quoted\"",
52+
},
53+
sops.TreeItem{
54+
Key: "VAR6",
55+
Value: "\"val6\nquoted\nmultiline\"",
56+
},
57+
sops.TreeItem{
58+
Key: "VAR7",
59+
Value: "'val7\nmultiline'",
60+
},
61+
sops.TreeItem{
62+
Key: "VAR8",
63+
Value: "'val8\"\nmixing\n\"quotes'",
64+
},
4065
}
4166

4267
func TestLoadPlainFile(t *testing.T) {

0 commit comments

Comments
 (0)