Skip to content

Commit b7794fb

Browse files
authored
feat!: remove global level configuration file (#252)
* feat: remove global level configuration file * update readme
1 parent 853c80c commit b7794fb

File tree

6 files changed

+42
-93
lines changed

6 files changed

+42
-93
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,8 @@ author: Bob
200200
# Language of the question description: zh or en
201201
language: zh
202202
code:
203-
# Language of code generated for questions: go, python, ...
204-
# (will be override by project config and flag --lang)
203+
# Language of code generated for questions: go, cpp, python, java...
204+
# (will be overridden by command line flag -l/--lang)
205205
lang: go
206206
# The default template to generate filename (without extension), e.g. {{.Id}}.{{.Slug}}
207207
# Available attributes: Id, Slug, Title, Difficulty, Lang, SlugIsMeaningful

README_zh.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,8 +193,8 @@ author: Bob
193193
# Language of the question description: zh or en
194194
language: zh
195195
code:
196-
# Language of code generated for questions: go, python, ...
197-
# (will be override by project config and flag --lang)
196+
# Language of code generated for questions: go, cpp, python, java...
197+
# (will be overridden by command line flag -l/--lang)
198198
lang: go
199199
# The default template to generate filename (without extension), e.g. {{.Id}}.{{.Slug}}
200200
# Available attributes: Id, Slug, Title, Difficulty, Lang, SlugIsMeaningful

cmd/debug.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,19 +55,18 @@ var debugCmd = &cobra.Command{
5555
Run: func(cmd *cobra.Command, args []string) {
5656
cfg := config.Get()
5757
cwd, _ := os.Getwd()
58-
projectConfig, err := os.ReadFile(cfg.ProjectConfigFile())
58+
projectConfig, err := os.ReadFile(cfg.ConfigFile())
5959
if err != nil {
6060
projectConfig = []byte("No project config file found")
6161
}
6262
cmd.Println("Leetgo version info :")
6363
cmd.Println("```")
6464
cmd.Println(buildVersion())
6565
cmd.Println("```")
66-
cmd.Println("Global config dir :", cfg.ConfigDir())
67-
cmd.Println("Global config file :", cfg.GlobalConfigFile())
66+
cmd.Println("Home dir :", cfg.HomeDir())
6867
cmd.Println("Project root :", cfg.ProjectRoot())
6968
cmd.Println("Working dir :", cwd)
70-
cmd.Println("Project config file :", cfg.ProjectConfigFile())
69+
cmd.Println("Project config file :", cfg.ConfigFile())
7170
cmd.Println("Project configuration:")
7271
cmd.Println("```yaml")
7372
cmd.Println(string(projectConfig))

cmd/init.go

Lines changed: 15 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ var initCmd = &cobra.Command{
4444
if err != nil {
4545
return err
4646
}
47-
err = createConfigFiles(dir)
47+
err = createConfigFile(dir)
4848
if err != nil {
4949
return err
5050
}
@@ -61,7 +61,7 @@ var initCmd = &cobra.Command{
6161

6262
func init() {
6363
initCmd.Flags().StringVarP(&initTemplate, "template", "t", "", "template to use, cn or us")
64-
initCmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite global config file if exists")
64+
initCmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite config file if exists")
6565

6666
_ = initCmd.RegisterFlagCompletionFunc(
6767
"template", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
@@ -71,7 +71,7 @@ func init() {
7171
}
7272

7373
func createConfigDir() error {
74-
dir := config.Get().ConfigDir()
74+
dir := config.Get().HomeDir()
7575
if utils.IsExist(dir) {
7676
return nil
7777
}
@@ -83,7 +83,7 @@ func createConfigDir() error {
8383
return nil
8484
}
8585

86-
func createConfigFiles(dir string) error {
86+
func createConfigFile(dir string) error {
8787
cfg := config.Get()
8888
site := cfg.LeetCode.Site
8989
language := cfg.Language
@@ -95,53 +95,25 @@ func createConfigFiles(dir string) error {
9595
language = config.ZH
9696
}
9797

98-
globalFile := cfg.GlobalConfigFile()
99-
if force || !utils.IsExist(globalFile) {
100-
f, err := os.Create(globalFile)
101-
if err != nil {
102-
return err
103-
}
104-
105-
author := defaultUser()
106-
cfg.LeetCode.Site = site
107-
cfg.Language = language
108-
cfg.Author = author
98+
author := defaultUser()
99+
cfg.LeetCode.Site = site
100+
cfg.Language = language
101+
cfg.Author = author
109102

110-
err = cfg.Write(f, true)
111-
if err != nil {
112-
return err
113-
}
114-
log.Info("global config file created", "file", globalFile)
103+
projectFile := filepath.Join(dir, constants.ConfigFilename)
104+
if utils.IsExist(projectFile) && !force {
105+
return fmt.Errorf("config file %s already exists, use -f to overwrite", utils.RelToCwd(projectFile))
115106
}
116107

117-
projectFile := filepath.Join(dir, constants.ProjectConfigFilename)
118108
f, err := os.Create(projectFile)
119109
if err != nil {
120110
return err
121111
}
112+
defer func() { _ = f.Close() }()
122113

123-
tmpl := `# This is the leetgo project level config, global config is at %s
124-
# For more details, please refer to https://github.com/j178/leetgo
125-
language: %s
126-
code:
127-
lang: %s
128-
leetcode:
129-
site: %s
130-
# credentials:
131-
# from: browser
132-
#editor:
133-
# use: none
134-
`
135-
_, _ = f.WriteString(
136-
fmt.Sprintf(
137-
tmpl,
138-
globalFile,
139-
language,
140-
cfg.Code.Lang,
141-
site,
142-
),
143-
)
144-
log.Info("project config file created", "file", utils.RelToCwd(projectFile))
114+
_, _ = f.WriteString("# Leetgo configuration file, see more at https://github.com/j178/leetgo\n\n")
115+
_ = cfg.Write(f, true)
116+
log.Info("config file created", "file", utils.RelToCwd(projectFile))
145117

146118
return nil
147119
}

config/config.go

Lines changed: 19 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
package config
22

33
import (
4+
"bytes"
45
"errors"
56
"fmt"
67
"io"
78
"os"
89
"path/filepath"
910
"strings"
1011

11-
"github.com/charmbracelet/log"
1212
"github.com/google/shlex"
1313
"github.com/mitchellh/go-homedir"
1414
"github.com/spf13/viper"
@@ -70,7 +70,7 @@ type Modifier struct {
7070
}
7171

7272
type CodeConfig struct {
73-
Lang string `yaml:"lang" mapstructure:"lang" comment:"Language of code generated for questions: go, python, ... \n(will be override by project config and flag --lang)"`
73+
Lang string `yaml:"lang" mapstructure:"lang" comment:"Language of code generated for questions: go, cpp, python, java... \n(will be overridden by command line flag -l/--lang)"`
7474
FilenameTemplate string `yaml:"filename_template" mapstructure:"filename_template" comment:"The default template to generate filename (without extension), e.g. {{.Id}}.{{.Slug}}\nAvailable attributes: Id, Slug, Title, Difficulty, Lang, SlugIsMeaningful\nAvailable functions: lower, upper, trim, padWithZero, toUnderscore, group"`
7575
SeparateDescriptionFile bool `yaml:"separate_description_file" mapstructure:"separate_description_file" comment:"Generate question description into a separate question.md file"`
7676
Blocks []Block `yaml:"blocks,omitempty" mapstructure:"blocks" comment:"Default block definitions for all languages"`
@@ -120,7 +120,7 @@ type LeetCodeConfig struct {
120120
Credentials Credentials `yaml:"credentials" mapstructure:"credentials" comment:"Credentials to access LeetCode"`
121121
}
122122

123-
func (c *Config) ConfigDir() string {
123+
func (c *Config) HomeDir() string {
124124
if c.dir != "" {
125125
return c.dir
126126
}
@@ -135,23 +135,19 @@ func (c *Config) ConfigDir() string {
135135
}
136136

137137
func (c *Config) CacheDir() string {
138-
return filepath.Join(c.ConfigDir(), "cache")
138+
return filepath.Join(c.HomeDir(), "cache")
139139
}
140140

141141
func (c *Config) TempDir() string {
142142
return filepath.Join(os.TempDir(), constants.CmdName)
143143
}
144144

145-
func (c *Config) GlobalConfigFile() string {
146-
return filepath.Join(c.ConfigDir(), constants.GlobalConfigFilename)
147-
}
148-
149145
func (c *Config) ProjectRoot() string {
150146
if c.projectRoot == "" {
151147
dir, _ := os.Getwd()
152148
c.projectRoot = dir
153149
for {
154-
if utils.IsExist(filepath.Join(dir, constants.ProjectConfigFilename)) {
150+
if utils.IsExist(filepath.Join(dir, constants.ConfigFilename)) {
155151
c.projectRoot = dir
156152
break
157153
}
@@ -166,8 +162,8 @@ func (c *Config) ProjectRoot() string {
166162
return c.projectRoot
167163
}
168164

169-
func (c *Config) ProjectConfigFile() string {
170-
return filepath.Join(c.ProjectRoot(), constants.ProjectConfigFilename)
165+
func (c *Config) ConfigFile() string {
166+
return filepath.Join(c.ProjectRoot(), constants.ConfigFilename)
171167
}
172168

173169
func (c *Config) StateFile() string {
@@ -301,45 +297,28 @@ func Load(init bool) error {
301297
return nil
302298
}
303299

304-
// load global configuration
300+
// load default configuration
305301
cfg := defaultConfig()
306-
viper.SetDefault("code.lang", cfg.Code.Lang)
307-
viper.SetDefault("leetcode.site", cfg.LeetCode.Site)
308302

309-
viper.SetConfigFile(cfg.GlobalConfigFile())
310-
err := viper.ReadInConfig()
303+
viper.SetConfigType("yaml")
304+
cfgBytes, err := yaml.Marshal(cfg)
311305
if err != nil {
312-
notExist := os.IsNotExist(err)
313-
if init && notExist {
314-
// During `init`, if global config file does not exist, we will create one.
315-
err = nil
316-
_ = err
317-
} else {
318-
if notExist {
319-
return fmt.Errorf(
320-
"global config file %s not found, run `leetgo init` to create one",
321-
cfg.GlobalConfigFile(),
322-
)
323-
}
324-
return fmt.Errorf("load global config file %s failed: %w", cfg.GlobalConfigFile(), err)
325-
}
306+
return fmt.Errorf("marshal default config failed: %w", err)
307+
}
308+
err = viper.ReadConfig(bytes.NewBuffer(cfgBytes))
309+
if err != nil {
310+
return fmt.Errorf("read default config failed: %w", err)
326311
}
327312

328-
// Don't read project config if we are running `init` command
313+
// load project configuration
329314
if !init {
330-
// load project configuration
331-
viper.SetConfigFile(cfg.ProjectConfigFile())
315+
viper.SetConfigFile(cfg.ConfigFile())
332316
err = viper.MergeInConfig()
333317
if err != nil {
334318
if os.IsNotExist(err) {
335-
log.Warn(
336-
fmt.Sprintf("%s not found, use global config only", constants.ProjectConfigFilename),
337-
"file",
338-
cfg.GlobalConfigFile(),
339-
)
340-
} else {
341-
return fmt.Errorf("load config file %s failed: %w", cfg.ProjectConfigFile(), err)
319+
return fmt.Errorf("%s not found, run `leetgo init` first", constants.ConfigFilename)
342320
}
321+
return fmt.Errorf("load config file %s failed: %w", cfg.ConfigFile(), err)
343322
}
344323
}
345324

constants/constants.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ var (
88

99
const (
1010
CmdName = "leetgo"
11-
GlobalConfigFilename = "config.yaml"
12-
ProjectConfigFilename = "leetgo.yaml"
11+
ConfigFilename = "leetgo.yaml"
1312
QuestionCacheBaseName = "leetcode-questions"
1413
StateFilename = "state.json"
1514
CodeBeginMarker = "@lc code=begin"

0 commit comments

Comments
 (0)