Skip to content

Merge setting.InitXXX into one function with options #24389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions cmd/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ func runGenerateActionsRunnerToken(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()

setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})

scope := c.String("scope")

Expand Down
3 changes: 1 addition & 2 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ func confirm() (bool, error) {
}

func initDB(ctx context.Context) error {
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
setting.LoadDBSetting()
setting.InitSQLLog(false)

Expand Down
3 changes: 1 addition & 2 deletions cmd/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ func runRecreateTable(ctx *cli.Context) error {
golog.SetPrefix("")
golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))

setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
setting.LoadDBSetting()

setting.Log.EnableXORMLog = ctx.Bool("debug")
Expand Down
3 changes: 1 addition & 2 deletions cmd/dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,7 @@ func runDump(ctx *cli.Context) error {
}
fileName += "." + outType
}
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})

// make sure we are logging to the console no matter what the configuration tells us do to
// FIXME: don't use CfgProvider directly
Expand Down
5 changes: 3 additions & 2 deletions cmd/embedded.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,9 @@ func initEmbeddedExtractor(c *cli.Context) error {
log.DelNamedLogger(log.DEFAULT)

// Read configuration file
setting.InitProviderAllowEmpty()
setting.LoadCommonSettings()
setting.Init(&setting.Options{
AllowEmpty: true,
})

patterns, err := compileCollectPatterns(c.Args())
if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions cmd/mailer.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ func runSendMail(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()

setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})

if err := argsSet(c, "title"); err != nil {
return err
Expand Down
6 changes: 0 additions & 6 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,8 @@ import (
"testing"

"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
)

func init() {
setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAndLoadCommonSettingsForTest()
}

func TestMain(m *testing.M) {
unittest.MainTest(m, &unittest.TestOptions{
GiteaRootPath: "..",
Expand Down
3 changes: 1 addition & 2 deletions cmd/restore_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ func runRestoreRepository(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()

setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
var units []string
if s := c.String("units"); s != "" {
units = strings.Split(s, ",")
Expand Down
3 changes: 1 addition & 2 deletions cmd/serv.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ func setup(ctx context.Context, debug bool) {
} else {
_ = log.NewLogger(1000, "console", "console", `{"level":"fatal","stacktracelevel":"NONE","stderr":true}`)
}
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
if debug {
setting.RunMode = "dev"
}
Expand Down
3 changes: 1 addition & 2 deletions cmd/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,7 @@ func runWeb(ctx *cli.Context) error {

log.Info("Global init")
// Perform global initialization
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
routers.GlobalInitInstalled(graceful.GetManager().HammerContext())

// We check that AppDataPath exists here (it should have been created during installation)
Expand Down
6 changes: 0 additions & 6 deletions models/asymkey/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,8 @@ import (
"testing"

"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
)

func init() {
setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAndLoadCommonSettingsForTest()
}

func TestMain(m *testing.M) {
unittest.MainTest(m, &unittest.TestOptions{
GiteaRootPath: filepath.Join("..", ".."),
Expand Down
6 changes: 0 additions & 6 deletions models/dbfs/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,8 @@ import (
"testing"

"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
)

func init() {
setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAndLoadCommonSettingsForTest()
}

func TestMain(m *testing.M) {
unittest.MainTest(m, &unittest.TestOptions{
GiteaRootPath: filepath.Join("..", ".."),
Expand Down
6 changes: 0 additions & 6 deletions models/issues/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (

issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"

_ "code.gitea.io/gitea/models"
_ "code.gitea.io/gitea/models/repo"
Expand All @@ -18,11 +17,6 @@ import (
"github.com/stretchr/testify/assert"
)

func init() {
setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAndLoadCommonSettingsForTest()
}

func TestFixturesAreConsistent(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
unittest.CheckConsistencyFor(t,
Expand Down
6 changes: 0 additions & 6 deletions models/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,12 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"

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

"github.com/stretchr/testify/assert"
)

func init() {
setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAndLoadCommonSettingsForTest()
}

// TestFixturesAreConsistent assert that test fixtures are consistent
func TestFixturesAreConsistent(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
Expand Down
2 changes: 1 addition & 1 deletion models/migrations/base/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ func MainTest(m *testing.M) {
setting.AppDataPath = tmpDataPath

setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAndLoadCommonSettingsForTest()
unittest.InitSettings()
if err = git.InitFull(context.Background()); err != nil {
fmt.Printf("Unable to InitFull: %v\n", err)
os.Exit(1)
Expand Down
22 changes: 22 additions & 0 deletions models/unittest/testdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ package unittest
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"testing"

"code.gitea.io/gitea/models/db"
system_model "code.gitea.io/gitea/models/system"
"code.gitea.io/gitea/modules/auth/password/hash"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
Expand Down Expand Up @@ -39,6 +42,22 @@ func fatalTestError(fmtStr string, args ...interface{}) {
os.Exit(1)
}

// InitSettings initializes config provider and load common setttings for tests
func InitSettings(extraConfigs ...string) {
setting.Init(&setting.Options{
AllowEmpty: true,
ExtraConfig: strings.Join(extraConfigs, "\n"),
})

if err := setting.PrepareAppDataPath(); err != nil {
log.Fatalf("Can not prepare APP_DATA_PATH: %v", err)
}
// register the dummy hash algorithm function used in the test fixtures
_ = hash.Register("dummy", hash.NewDummyHasher)

setting.PasswordHashAlgo, _ = hash.SetDefaultPasswordHashAlgorithm("dummy")
}

// TestOptions represents test options
type TestOptions struct {
GiteaRootPath string
Expand All @@ -50,6 +69,9 @@ type TestOptions struct {
// MainTest a reusable TestMain(..) function for unit tests that need to use a
// test database. Creates the test database, and sets necessary settings.
func MainTest(m *testing.M, testOpts *TestOptions) {
setting.SetCustomPathAndConf("", "", "")
InitSettings()

var err error

giteaRoot = testOpts.GiteaRootPath
Expand Down
3 changes: 1 addition & 2 deletions modules/doctor/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ func (w *wrappedLevelLogger) Log(skip int, level log.Level, format string, v ...
}

func initDBDisableConsole(ctx context.Context, disableConsole bool) error {
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
setting.LoadDBSetting()
setting.InitSQLLog(disableConsole)
if err := db.InitEngine(ctx); err != nil {
Expand Down
3 changes: 1 addition & 2 deletions modules/doctor/paths.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ func checkConfigurationFiles(ctx context.Context, logger log.Logger, autofix boo
return err
}

setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})

configurationFiles := []configurationFile{
{"Configuration File Path", setting.CustomConf, false, true, false},
Expand Down
5 changes: 3 additions & 2 deletions modules/markup/html_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ var localMetas = map[string]string{
}

func TestMain(m *testing.M) {
setting.InitProviderAllowEmpty()
setting.LoadCommonSettings()
setting.Init(&setting.Options{
AllowEmpty: true,
})
if err := git.InitSimple(context.Background()); err != nil {
log.Fatal("git init failed, err: %v", err)
}
Expand Down
5 changes: 3 additions & 2 deletions modules/markup/markdown/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ var localMetas = map[string]string{
}

func TestMain(m *testing.M) {
setting.InitProviderAllowEmpty()
setting.LoadCommonSettings()
setting.Init(&setting.Options{
AllowEmpty: true,
})
if err := git.InitSimple(context.Background()); err != nil {
log.Fatal("git init failed, err: %v", err)
}
Expand Down
45 changes: 25 additions & 20 deletions modules/setting/config_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@ type ConfigProvider interface {
}

type iniFileConfigProvider struct {
opts *Options
*ini.File
filepath string // the ini file path
newFile bool // whether the file has not existed previously
allowEmpty bool // whether not finding configuration files is allowed (only true for the tests)
newFile bool // whether the file has not existed previously
}

// NewEmptyConfigProvider create a new empty config provider
Expand Down Expand Up @@ -66,41 +65,47 @@ func newConfigProviderFromData(configContent string) (ConfigProvider, error) {
}, nil
}

type Options struct {
CustomConf string // the ini file path
AllowEmpty bool // whether not finding configuration files is allowed (only true for the tests)
ExtraConfig string
DisableLoadCommonSettings bool
}

// newConfigProviderFromFile load configuration from file.
// NOTE: do not print any log except error.
func newConfigProviderFromFile(customConf string, allowEmpty bool, extraConfig string) (*iniFileConfigProvider, error) {
func newConfigProviderFromFile(opts *Options) (*iniFileConfigProvider, error) {
cfg := ini.Empty()
newFile := true

if customConf != "" {
isFile, err := util.IsFile(customConf)
if opts.CustomConf != "" {
isFile, err := util.IsFile(opts.CustomConf)
if err != nil {
return nil, fmt.Errorf("unable to check if %s is a file. Error: %v", customConf, err)
return nil, fmt.Errorf("unable to check if %s is a file. Error: %v", opts.CustomConf, err)
}
if isFile {
if err := cfg.Append(customConf); err != nil {
return nil, fmt.Errorf("failed to load custom conf '%s': %v", customConf, err)
if err := cfg.Append(opts.CustomConf); err != nil {
return nil, fmt.Errorf("failed to load custom conf '%s': %v", opts.CustomConf, err)
}
newFile = false
}
}

if newFile && !allowEmpty {
if newFile && !opts.AllowEmpty {
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)
}

if extraConfig != "" {
if err := cfg.Append([]byte(extraConfig)); err != nil {
if opts.ExtraConfig != "" {
if err := cfg.Append([]byte(opts.ExtraConfig)); err != nil {
return nil, fmt.Errorf("unable to append more config: %v", err)
}
}

cfg.NameMapper = ini.SnackCase
return &iniFileConfigProvider{
File: cfg,
filepath: customConf,
newFile: newFile,
allowEmpty: allowEmpty,
opts: opts,
File: cfg,
newFile: newFile,
}, nil
}

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

// Save save the content into file
func (p *iniFileConfigProvider) Save() error {
if p.filepath == "" {
if !p.allowEmpty {
if p.opts.CustomConf == "" {
if !p.opts.AllowEmpty {
return fmt.Errorf("custom config path must not be empty")
}
return nil
Expand All @@ -135,8 +140,8 @@ func (p *iniFileConfigProvider) Save() error {
return fmt.Errorf("failed to create '%s': %v", CustomConf, err)
}
}
if err := p.SaveTo(p.filepath); err != nil {
return fmt.Errorf("failed to save '%s': %v", p.filepath, err)
if err := p.SaveTo(p.opts.CustomConf); err != nil {
return fmt.Errorf("failed to save '%s': %v", p.opts.CustomConf, err)
}

// Change permissions to be more restrictive
Expand Down
Loading