Skip to content

Commit

Permalink
Add (simple) support for quoted multiline variables in .env files
Browse files Browse the repository at this point in the history
Signed-off-by: Midas Lambrichts <[email protected]>
  • Loading branch information
MidasLamb committed Feb 4, 2025
1 parent af8a349 commit 3ad5e74
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
37 changes: 35 additions & 2 deletions stores/dotenv/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package dotenv //import "github.com/getsops/sops/v3/stores/dotenv"
import (
"bytes"
"fmt"
"slices"
"sort"
"strings"

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

for _, line := range bytes.Split(in, []byte("\n")) {
var lines [][]byte
var inQuotes = false
var currentQuoteChar byte = '"'
var lastSplit = -1

for pos, char := range in {
switch char {
case '"', '\'', '`':
if inQuotes {
if currentQuoteChar == char {
inQuotes = false
}
} else {
inQuotes = true
currentQuoteChar = char
}
case '\n':
if !inQuotes {
var line = in[lastSplit+1 : pos]
lines = append(lines, line)
lastSplit = pos
}
}
}

for _, line := range lines {
if len(line) == 0 {
continue
}
Expand Down Expand Up @@ -141,8 +167,15 @@ func (store *Store) EmitPlainFile(in sops.TreeBranches) ([]byte, error) {
if comment, ok := item.Key.(sops.Comment); ok {
line = fmt.Sprintf("#%s\n", comment.Value)
} else {
value := strings.Replace(item.Value.(string), "\n", "\\n", -1)
stringValue := item.Value.(string)
var value string
if len(stringValue) == 0 || !slices.Contains([]byte{'"', '\'', '`'}, stringValue[0]) {
value = strings.Replace(stringValue, "\n", "\\n", -1)
} else {
value = item.Value.(string)
}
line = fmt.Sprintf("%s=%s\n", item.Key, value)

}
buffer.WriteString(line)
}
Expand Down
25 changes: 25 additions & 0 deletions stores/dotenv/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ VAR2=val2
#comment
VAR3_unencrypted=val3
VAR4=val4\nval4
VAR5="val5quoted"
VAR6="val6
quoted
multiline"
VAR7='val7
multiline'
VAR8='val8"
mixing
"quotes'
`, "\n"))

var BRANCH = sops.TreeBranch{
Expand All @@ -37,6 +46,22 @@ var BRANCH = sops.TreeBranch{
Key: "VAR4",
Value: "val4\nval4",
},
sops.TreeItem{
Key: "VAR5",
Value: "\"val5quoted\"",
},
sops.TreeItem{
Key: "VAR6",
Value: "\"val6\nquoted\nmultiline\"",
},
sops.TreeItem{
Key: "VAR7",
Value: "'val7\nmultiline'",
},
sops.TreeItem{
Key: "VAR8",
Value: "'val8\"\nmixing\n\"quotes'",
},
}

func TestLoadPlainFile(t *testing.T) {
Expand Down

0 comments on commit 3ad5e74

Please sign in to comment.