From 0c8a96896f41df68eb4605e4852df674cb03d6f2 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Sun, 13 Aug 2023 00:19:33 +0800 Subject: [PATCH] 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 (cherry picked from commit 80d7288ea45ea69060eb41709f188c09b33ca266) --- modules/setting/config_env.go | 6 ++++++ modules/setting/config_env_test.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/modules/setting/config_env.go b/modules/setting/config_env.go index 4acb977936..137dfaa385 100644 --- a/modules/setting/config_env.go +++ b/modules/setting/config_env.go @@ -4,6 +4,7 @@ package setting import ( + "bytes" "os" "regexp" "strconv" @@ -133,6 +134,11 @@ func EnvironmentToConfig(cfg ConfigProvider, envs []string) (changed bool) { log.Error("Error reading file for %s : %v", envKey, envValue, err) 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) } diff --git a/modules/setting/config_env_test.go b/modules/setting/config_env_test.go index 96689aee18..adeb17244d 100644 --- a/modules/setting/config_env_test.go +++ b/modules/setting/config_env_test.go @@ -106,4 +106,19 @@ key = old changed = EnvironmentToConfig(cfg, []string{"GITEA__sec__key__FILE=" + tmpFile}) assert.True(t, changed) 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()) }