Skip to content

Commit 377a0a2

Browse files
authored
Merge setting.InitXXX into one function with options (#24389)
This PR will merge 3 Init functions on setting packages as 1 and introduce an options struct.
1 parent a2fe68e commit 377a0a2

File tree

28 files changed

+103
-136
lines changed

28 files changed

+103
-136
lines changed

cmd/actions.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,7 @@ func runGenerateActionsRunnerToken(c *cli.Context) error {
4242
ctx, cancel := installSignals()
4343
defer cancel()
4444

45-
setting.InitProviderFromExistingFile()
46-
setting.LoadCommonSettings()
45+
setting.Init(&setting.Options{})
4746

4847
scope := c.String("scope")
4948

cmd/cmd.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@ func confirm() (bool, error) {
5757
}
5858

5959
func initDB(ctx context.Context) error {
60-
setting.InitProviderFromExistingFile()
61-
setting.LoadCommonSettings()
60+
setting.Init(&setting.Options{})
6261
setting.LoadDBSetting()
6362
setting.InitSQLLog(false)
6463

cmd/doctor.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,7 @@ func runRecreateTable(ctx *cli.Context) error {
8787
golog.SetPrefix("")
8888
golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
8989

90-
setting.InitProviderFromExistingFile()
91-
setting.LoadCommonSettings()
90+
setting.Init(&setting.Options{})
9291
setting.LoadDBSetting()
9392

9493
setting.Log.EnableXORMLog = ctx.Bool("debug")

cmd/dump.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,7 @@ func runDump(ctx *cli.Context) error {
185185
}
186186
fileName += "." + outType
187187
}
188-
setting.InitProviderFromExistingFile()
189-
setting.LoadCommonSettings()
188+
setting.Init(&setting.Options{})
190189

191190
// make sure we are logging to the console no matter what the configuration tells us do to
192191
// FIXME: don't use CfgProvider directly

cmd/embedded.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,9 @@ func initEmbeddedExtractor(c *cli.Context) error {
106106
log.DelNamedLogger(log.DEFAULT)
107107

108108
// Read configuration file
109-
setting.InitProviderAllowEmpty()
110-
setting.LoadCommonSettings()
109+
setting.Init(&setting.Options{
110+
AllowEmpty: true,
111+
})
111112

112113
patterns, err := compileCollectPatterns(c.Args())
113114
if err != nil {

cmd/mailer.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@ func runSendMail(c *cli.Context) error {
1616
ctx, cancel := installSignals()
1717
defer cancel()
1818

19-
setting.InitProviderFromExistingFile()
20-
setting.LoadCommonSettings()
19+
setting.Init(&setting.Options{})
2120

2221
if err := argsSet(c, "title"); err != nil {
2322
return err

cmd/main_test.go

-6
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,8 @@ import (
77
"testing"
88

99
"code.gitea.io/gitea/models/unittest"
10-
"code.gitea.io/gitea/modules/setting"
1110
)
1211

13-
func init() {
14-
setting.SetCustomPathAndConf("", "", "")
15-
setting.InitProviderAndLoadCommonSettingsForTest()
16-
}
17-
1812
func TestMain(m *testing.M) {
1913
unittest.MainTest(m, &unittest.TestOptions{
2014
GiteaRootPath: "..",

cmd/restore_repo.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ func runRestoreRepository(c *cli.Context) error {
5151
ctx, cancel := installSignals()
5252
defer cancel()
5353

54-
setting.InitProviderFromExistingFile()
55-
setting.LoadCommonSettings()
54+
setting.Init(&setting.Options{})
5655
var units []string
5756
if s := c.String("units"); s != "" {
5857
units = strings.Split(s, ",")

cmd/serv.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,7 @@ func setup(ctx context.Context, debug bool) {
6262
} else {
6363
_ = log.NewLogger(1000, "console", "console", `{"level":"fatal","stacktracelevel":"NONE","stderr":true}`)
6464
}
65-
setting.InitProviderFromExistingFile()
66-
setting.LoadCommonSettings()
65+
setting.Init(&setting.Options{})
6766
if debug {
6867
setting.RunMode = "dev"
6968
}

cmd/web.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,7 @@ func runWeb(ctx *cli.Context) error {
177177

178178
log.Info("Global init")
179179
// Perform global initialization
180-
setting.InitProviderFromExistingFile()
181-
setting.LoadCommonSettings()
180+
setting.Init(&setting.Options{})
182181
routers.GlobalInitInstalled(graceful.GetManager().HammerContext())
183182

184183
// We check that AppDataPath exists here (it should have been created during installation)

models/asymkey/main_test.go

-6
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,8 @@ import (
88
"testing"
99

1010
"code.gitea.io/gitea/models/unittest"
11-
"code.gitea.io/gitea/modules/setting"
1211
)
1312

14-
func init() {
15-
setting.SetCustomPathAndConf("", "", "")
16-
setting.InitProviderAndLoadCommonSettingsForTest()
17-
}
18-
1913
func TestMain(m *testing.M) {
2014
unittest.MainTest(m, &unittest.TestOptions{
2115
GiteaRootPath: filepath.Join("..", ".."),

models/dbfs/main_test.go

-6
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,8 @@ import (
88
"testing"
99

1010
"code.gitea.io/gitea/models/unittest"
11-
"code.gitea.io/gitea/modules/setting"
1211
)
1312

14-
func init() {
15-
setting.SetCustomPathAndConf("", "", "")
16-
setting.InitProviderAndLoadCommonSettingsForTest()
17-
}
18-
1913
func TestMain(m *testing.M) {
2014
unittest.MainTest(m, &unittest.TestOptions{
2115
GiteaRootPath: filepath.Join("..", ".."),

models/issues/main_test.go

-6
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99

1010
issues_model "code.gitea.io/gitea/models/issues"
1111
"code.gitea.io/gitea/models/unittest"
12-
"code.gitea.io/gitea/modules/setting"
1312

1413
_ "code.gitea.io/gitea/models"
1514
_ "code.gitea.io/gitea/models/repo"
@@ -18,11 +17,6 @@ import (
1817
"github.com/stretchr/testify/assert"
1918
)
2019

21-
func init() {
22-
setting.SetCustomPathAndConf("", "", "")
23-
setting.InitProviderAndLoadCommonSettingsForTest()
24-
}
25-
2620
func TestFixturesAreConsistent(t *testing.T) {
2721
assert.NoError(t, unittest.PrepareTestDatabase())
2822
unittest.CheckConsistencyFor(t,

models/main_test.go

-6
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,12 @@ import (
1111
repo_model "code.gitea.io/gitea/models/repo"
1212
"code.gitea.io/gitea/models/unittest"
1313
user_model "code.gitea.io/gitea/models/user"
14-
"code.gitea.io/gitea/modules/setting"
1514

1615
_ "code.gitea.io/gitea/models/system"
1716

1817
"github.com/stretchr/testify/assert"
1918
)
2019

21-
func init() {
22-
setting.SetCustomPathAndConf("", "", "")
23-
setting.InitProviderAndLoadCommonSettingsForTest()
24-
}
25-
2620
// TestFixturesAreConsistent assert that test fixtures are consistent
2721
func TestFixturesAreConsistent(t *testing.T) {
2822
assert.NoError(t, unittest.PrepareTestDatabase())

models/migrations/base/tests.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ func MainTest(m *testing.M) {
150150
setting.AppDataPath = tmpDataPath
151151

152152
setting.SetCustomPathAndConf("", "", "")
153-
setting.InitProviderAndLoadCommonSettingsForTest()
153+
unittest.InitSettings()
154154
if err = git.InitFull(context.Background()); err != nil {
155155
fmt.Printf("Unable to InitFull: %v\n", err)
156156
os.Exit(1)

models/unittest/testdb.go

+22
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@ package unittest
66
import (
77
"context"
88
"fmt"
9+
"log"
910
"os"
1011
"path/filepath"
12+
"strings"
1113
"testing"
1214

1315
"code.gitea.io/gitea/models/db"
1416
system_model "code.gitea.io/gitea/models/system"
17+
"code.gitea.io/gitea/modules/auth/password/hash"
1518
"code.gitea.io/gitea/modules/base"
1619
"code.gitea.io/gitea/modules/git"
1720
"code.gitea.io/gitea/modules/setting"
@@ -39,6 +42,22 @@ func fatalTestError(fmtStr string, args ...interface{}) {
3942
os.Exit(1)
4043
}
4144

45+
// InitSettings initializes config provider and load common setttings for tests
46+
func InitSettings(extraConfigs ...string) {
47+
setting.Init(&setting.Options{
48+
AllowEmpty: true,
49+
ExtraConfig: strings.Join(extraConfigs, "\n"),
50+
})
51+
52+
if err := setting.PrepareAppDataPath(); err != nil {
53+
log.Fatalf("Can not prepare APP_DATA_PATH: %v", err)
54+
}
55+
// register the dummy hash algorithm function used in the test fixtures
56+
_ = hash.Register("dummy", hash.NewDummyHasher)
57+
58+
setting.PasswordHashAlgo, _ = hash.SetDefaultPasswordHashAlgorithm("dummy")
59+
}
60+
4261
// TestOptions represents test options
4362
type TestOptions struct {
4463
GiteaRootPath string
@@ -50,6 +69,9 @@ type TestOptions struct {
5069
// MainTest a reusable TestMain(..) function for unit tests that need to use a
5170
// test database. Creates the test database, and sets necessary settings.
5271
func MainTest(m *testing.M, testOpts *TestOptions) {
72+
setting.SetCustomPathAndConf("", "", "")
73+
InitSettings()
74+
5375
var err error
5476

5577
giteaRoot = testOpts.GiteaRootPath

modules/doctor/doctor.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@ func (w *wrappedLevelLogger) Log(skip int, level log.Level, format string, v ...
4444
}
4545

4646
func initDBDisableConsole(ctx context.Context, disableConsole bool) error {
47-
setting.InitProviderFromExistingFile()
48-
setting.LoadCommonSettings()
47+
setting.Init(&setting.Options{})
4948
setting.LoadDBSetting()
5049
setting.InitSQLLog(disableConsole)
5150
if err := db.InitEngine(ctx); err != nil {

modules/doctor/paths.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,7 @@ func checkConfigurationFiles(ctx context.Context, logger log.Logger, autofix boo
6666
return err
6767
}
6868

69-
setting.InitProviderFromExistingFile()
70-
setting.LoadCommonSettings()
69+
setting.Init(&setting.Options{})
7170

7271
configurationFiles := []configurationFile{
7372
{"Configuration File Path", setting.CustomConf, false, true, false},

modules/markup/html_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@ var localMetas = map[string]string{
2828
}
2929

3030
func TestMain(m *testing.M) {
31-
setting.InitProviderAllowEmpty()
32-
setting.LoadCommonSettings()
31+
setting.Init(&setting.Options{
32+
AllowEmpty: true,
33+
})
3334
if err := git.InitSimple(context.Background()); err != nil {
3435
log.Fatal("git init failed, err: %v", err)
3536
}

modules/markup/markdown/markdown_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,9 @@ var localMetas = map[string]string{
3333
}
3434

3535
func TestMain(m *testing.M) {
36-
setting.InitProviderAllowEmpty()
37-
setting.LoadCommonSettings()
36+
setting.Init(&setting.Options{
37+
AllowEmpty: true,
38+
})
3839
if err := git.InitSimple(context.Background()); err != nil {
3940
log.Fatal("git init failed, err: %v", err)
4041
}

modules/setting/config_provider.go

+25-20
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,9 @@ type ConfigProvider interface {
3535
}
3636

3737
type iniFileConfigProvider struct {
38+
opts *Options
3839
*ini.File
39-
filepath string // the ini file path
40-
newFile bool // whether the file has not existed previously
41-
allowEmpty bool // whether not finding configuration files is allowed (only true for the tests)
40+
newFile bool // whether the file has not existed previously
4241
}
4342

4443
// NewEmptyConfigProvider create a new empty config provider
@@ -66,41 +65,47 @@ func newConfigProviderFromData(configContent string) (ConfigProvider, error) {
6665
}, nil
6766
}
6867

68+
type Options struct {
69+
CustomConf string // the ini file path
70+
AllowEmpty bool // whether not finding configuration files is allowed (only true for the tests)
71+
ExtraConfig string
72+
DisableLoadCommonSettings bool
73+
}
74+
6975
// newConfigProviderFromFile load configuration from file.
7076
// NOTE: do not print any log except error.
71-
func newConfigProviderFromFile(customConf string, allowEmpty bool, extraConfig string) (*iniFileConfigProvider, error) {
77+
func newConfigProviderFromFile(opts *Options) (*iniFileConfigProvider, error) {
7278
cfg := ini.Empty()
7379
newFile := true
7480

75-
if customConf != "" {
76-
isFile, err := util.IsFile(customConf)
81+
if opts.CustomConf != "" {
82+
isFile, err := util.IsFile(opts.CustomConf)
7783
if err != nil {
78-
return nil, fmt.Errorf("unable to check if %s is a file. Error: %v", customConf, err)
84+
return nil, fmt.Errorf("unable to check if %s is a file. Error: %v", opts.CustomConf, err)
7985
}
8086
if isFile {
81-
if err := cfg.Append(customConf); err != nil {
82-
return nil, fmt.Errorf("failed to load custom conf '%s': %v", customConf, err)
87+
if err := cfg.Append(opts.CustomConf); err != nil {
88+
return nil, fmt.Errorf("failed to load custom conf '%s': %v", opts.CustomConf, err)
8389
}
8490
newFile = false
8591
}
8692
}
8793

88-
if newFile && !allowEmpty {
94+
if newFile && !opts.AllowEmpty {
8995
return nil, fmt.Errorf("unable to find configuration file: %q, please ensure you are running in the correct environment or set the correct configuration file with -c", CustomConf)
9096
}
9197

92-
if extraConfig != "" {
93-
if err := cfg.Append([]byte(extraConfig)); err != nil {
98+
if opts.ExtraConfig != "" {
99+
if err := cfg.Append([]byte(opts.ExtraConfig)); err != nil {
94100
return nil, fmt.Errorf("unable to append more config: %v", err)
95101
}
96102
}
97103

98104
cfg.NameMapper = ini.SnackCase
99105
return &iniFileConfigProvider{
100-
File: cfg,
101-
filepath: customConf,
102-
newFile: newFile,
103-
allowEmpty: allowEmpty,
106+
opts: opts,
107+
File: cfg,
108+
newFile: newFile,
104109
}, nil
105110
}
106111

@@ -123,8 +128,8 @@ func (p *iniFileConfigProvider) DeleteSection(name string) error {
123128

124129
// Save save the content into file
125130
func (p *iniFileConfigProvider) Save() error {
126-
if p.filepath == "" {
127-
if !p.allowEmpty {
131+
if p.opts.CustomConf == "" {
132+
if !p.opts.AllowEmpty {
128133
return fmt.Errorf("custom config path must not be empty")
129134
}
130135
return nil
@@ -135,8 +140,8 @@ func (p *iniFileConfigProvider) Save() error {
135140
return fmt.Errorf("failed to create '%s': %v", CustomConf, err)
136141
}
137142
}
138-
if err := p.SaveTo(p.filepath); err != nil {
139-
return fmt.Errorf("failed to save '%s': %v", p.filepath, err)
143+
if err := p.SaveTo(p.opts.CustomConf); err != nil {
144+
return fmt.Errorf("failed to save '%s': %v", p.opts.CustomConf, err)
140145
}
141146

142147
// Change permissions to be more restrictive

0 commit comments

Comments
 (0)