Skip to content
This repository has been archived by the owner on Jan 15, 2023. It is now read-only.

Commit

Permalink
fix: sort markers by key to avoid random processing
Browse files Browse the repository at this point in the history
  • Loading branch information
saitho committed Jun 11, 2020
1 parent 02a2d1e commit 8b345f0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
22 changes: 16 additions & 6 deletions src/nginx/nginx.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"path"
"regexp"
"sort"
"strings"
)

Expand All @@ -31,7 +32,16 @@ func CreateOrUpdateServerBlock(filename string, content string, m Config, marker
/// ReplaceMarkers replaces all markers in given content
func ReplaceMarkers(content string, markers map[string]string) string {
var re *regexp.Regexp
for key, value := range markers {

// Sort keys to avoid random order
keys := make([]string, 0, len(markers))
for k := range markers {
keys = append(keys, k)
}
sort.Strings(keys)

for _, key := range keys {
value := markers[key]
re, _ = regexp.Compile("{#\\s*" + key + "\\s*#}") // {#marker#}
content = re.ReplaceAllString(content, value)
re, _ = regexp.Compile("{~\\s*" + key + "\\s*~}") // {~marker~}
Expand All @@ -43,16 +53,16 @@ func ReplaceMarkers(content string, markers map[string]string) string {
}

/// ProcessMarkers resolves array values into single string replaces
func ProcessMarkers(markers map[string]interface{}, markers_split map[string]interface{}) map[string]string {
markers_split_keys := make([]string, 0, len(markers_split))
for k := range markers_split {
markers_split_keys = append(markers_split_keys, k)
func ProcessMarkers(markers map[string]interface{}, markersSplit map[string]interface{}) map[string]string {
markersSplitKeys := make([]string, 0, len(markersSplit))
for k := range markersSplit {
markersSplitKeys = append(markersSplitKeys, k)
}

output := make(map[string]string)
for key, value := range markers {
stringValue := value.(string)
splitChar := markers_split[key]
splitChar := markersSplit[key]
if splitChar == nil || splitChar.(string) == "" {
output[key] = regexp.QuoteMeta(stringValue)
continue
Expand Down
2 changes: 0 additions & 2 deletions src/nginx/nginx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ func TestMarkers(t *testing.T) {
assert.Equal(t, "Marker is bar with bar2", text)
text = ReplaceMarkers("Marker is {* foo *} with {* fooArr[1] *}", processedMarkers)
assert.Equal(t, "Marker is bar with bar2", text)
text = ReplaceMarkers("Marker is {# foo #} with {# fooArr[1] #}", processedMarkers)
assert.Equal(t, "Marker is bar with bar2", text)
text = ReplaceMarkers("Marker is {# foo #} with {# fooArr[99] #}", processedMarkers)
assert.Equal(t, "Marker is bar with ", text)
}

0 comments on commit 8b345f0

Please sign in to comment.