Skip to content

Commit 80d7288

Browse files
GiteaBotwxiaoguang
andauthored
Remove last newline from config file (#26468) (#26471)
Backport #26468 by @wxiaoguang When users put the secrets into a file (GITEA__sec__KEY__FILE), the newline sometimes is different to avoid (eg: echo/vim/...) So the last newline could be removed when reading, it makes the users easier to maintain the secret files. Co-authored-by: wxiaoguang <[email protected]>
1 parent 2d1202b commit 80d7288

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

modules/setting/config_env.go

+6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package setting
55

66
import (
7+
"bytes"
78
"os"
89
"regexp"
910
"strconv"
@@ -131,6 +132,11 @@ func EnvironmentToConfig(cfg ConfigProvider, envs []string) (changed bool) {
131132
log.Error("Error reading file for %s : %v", envKey, envValue, err)
132133
continue
133134
}
135+
if bytes.HasSuffix(fileContent, []byte("\r\n")) {
136+
fileContent = fileContent[:len(fileContent)-2]
137+
} else if bytes.HasSuffix(fileContent, []byte("\n")) {
138+
fileContent = fileContent[:len(fileContent)-1]
139+
}
134140
keyValue = string(fileContent)
135141
}
136142

modules/setting/config_env_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -99,4 +99,19 @@ key = old
9999
changed = EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
100100
assert.True(t, changed)
101101
assert.Equal(t, "value-from-file", cfg.Section("sec").Key("key").String())
102+
103+
cfg, _ = NewConfigProviderFromData("")
104+
_ = os.WriteFile(tmpFile, []byte("value-from-file\n"), 0o644)
105+
EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
106+
assert.Equal(t, "value-from-file", cfg.Section("sec").Key("key").String())
107+
108+
cfg, _ = NewConfigProviderFromData("")
109+
_ = os.WriteFile(tmpFile, []byte("value-from-file\r\n"), 0o644)
110+
EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
111+
assert.Equal(t, "value-from-file", cfg.Section("sec").Key("key").String())
112+
113+
cfg, _ = NewConfigProviderFromData("")
114+
_ = os.WriteFile(tmpFile, []byte("value-from-file\n\n"), 0o644)
115+
EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
116+
assert.Equal(t, "value-from-file\n", cfg.Section("sec").Key("key").String())
102117
}

0 commit comments

Comments
 (0)