Skip to content

Commit dc0de03

Browse files
authored
feat: add the -dir flag (#14)
1 parent 4a0abf1 commit dc0de03

File tree

3 files changed

+19
-10
lines changed

3 files changed

+19
-10
lines changed

main.go

+10-2
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@ func run() (runErr error) {
2626
return err
2727
}
2828

29-
if cfg.path != "" {
30-
cfgFile, err := os.Open(cfg.path)
29+
path, dir := cfg.path, cfg.dir
30+
31+
if path != "" {
32+
cfgFile, err := os.Open(path)
3133
if err != nil {
3234
return err
3335
}
@@ -39,6 +41,12 @@ func run() (runErr error) {
3941
}
4042
}
4143

44+
if dir != "" {
45+
if err := os.Chdir(dir); err != nil {
46+
return err
47+
}
48+
}
49+
4250
if err := os.Mkdir(cfg.Pkg, 0o755); err != nil && !errors.Is(err, os.ErrExist) {
4351
return err
4452
}

sloggen.go

+8-7
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,13 @@ var (
4646
// NOTE: when iterating over a map, text/template visits the elements in sorted key order.
4747
type (
4848
config struct {
49-
path string
50-
Pkg string
51-
Imports []string
52-
Levels map[int]string // severity:name
53-
Consts []string
54-
Attrs map[string]string // key:type
55-
Logger *logger
49+
Pkg string
50+
Imports []string
51+
Levels map[int]string // severity:name
52+
Consts []string
53+
Attrs map[string]string // key:type
54+
Logger *logger
55+
path, dir string // for flags only.
5656
}
5757
logger struct {
5858
Levels map[int]string
@@ -93,6 +93,7 @@ func readFlags(args []string) (*config, error) {
9393

9494
fs := flag.NewFlagSet("sloggen", flag.ContinueOnError)
9595
fs.StringVar(&cfg.path, "config", "", "read config from the file instead of flags")
96+
fs.StringVar(&cfg.dir, "dir", "", "change the working directory before generating files")
9697
fs.StringVar(&cfg.Pkg, "pkg", "slogx", "the name for the generated package")
9798

9899
fs.Func("i", "add import", func(s string) error {

sloggen_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
"go-simpler.org/sloggen/example"
1414
)
1515

16-
//go:generate go run main.go sloggen.go --config=.slog.example.yml
16+
//go:generate go run main.go sloggen.go -config=.slog.example.yml -dir=.
1717

1818
var cfg = config{
1919
Pkg: "test",

0 commit comments

Comments
 (0)