1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-11-24 08:57:03 -05:00

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 <wxiaoguang@gmail.com>
(cherry picked from commit 80d7288ea4)
This commit is contained in:
Giteabot 2023-08-13 00:19:33 +08:00 committed by Earl Warren
parent 82e5247a43
commit 0c8a96896f
No known key found for this signature in database
GPG key ID: 0579CB2928A78A00
2 changed files with 21 additions and 0 deletions

View file

@ -4,6 +4,7 @@
package setting package setting
import ( import (
"bytes"
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
@ -133,6 +134,11 @@ func EnvironmentToConfig(cfg ConfigProvider, envs []string) (changed bool) {
log.Error("Error reading file for %s : %v", envKey, envValue, err) log.Error("Error reading file for %s : %v", envKey, envValue, err)
continue continue
} }
if bytes.HasSuffix(fileContent, []byte("\r\n")) {
fileContent = fileContent[:len(fileContent)-2]
} else if bytes.HasSuffix(fileContent, []byte("\n")) {
fileContent = fileContent[:len(fileContent)-1]
}
keyValue = string(fileContent) keyValue = string(fileContent)
} }

View file

@ -106,4 +106,19 @@ key = old
changed = EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile}) changed = EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
assert.True(t, changed) assert.True(t, changed)
assert.Equal(t, "value-from-file", cfg.Section("sec").Key("key").String()) assert.Equal(t, "value-from-file", cfg.Section("sec").Key("key").String())
cfg, _ = NewConfigProviderFromData("")
_ = os.WriteFile(tmpFile, []byte("value-from-file\n"), 0o644)
EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
assert.Equal(t, "value-from-file", cfg.Section("sec").Key("key").String())
cfg, _ = NewConfigProviderFromData("")
_ = os.WriteFile(tmpFile, []byte("value-from-file\r\n"), 0o644)
EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
assert.Equal(t, "value-from-file", cfg.Section("sec").Key("key").String())
cfg, _ = NewConfigProviderFromData("")
_ = os.WriteFile(tmpFile, []byte("value-from-file\n\n"), 0o644)
EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile})
assert.Equal(t, "value-from-file\n", cfg.Section("sec").Key("key").String())
} }