Skip to content

Commit c2dba5f

Browse files
committed
refactor
1 parent fd9720e commit c2dba5f

File tree

5 files changed

+206
-62
lines changed

5 files changed

+206
-62
lines changed

ggen/config.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package ggen
33
import (
44
"os"
55

6-
"github.com/iolivernguyen/ggen/internal/log"
6+
"github.com/iolivernguyen/ggen/ggen/logging"
77
)
88

99
type GenerateFileNameInput struct {
@@ -56,7 +56,7 @@ func Start(cfg Config, patterns ...string) error {
5656
if cfg.LogHandler == nil {
5757
cfg.LogHandler = cfg.defaultLogHandler()
5858
}
59-
logger = log.NewLogger(cfg.LogHandler)
59+
logger = logging.NewLogger(cfg.LogHandler)
6060

6161
ng := newEngine(logger)
6262
return ng.start(cfg, patterns...)

ggen/log.go

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,19 @@ import (
44
"fmt"
55
"io"
66

7-
"github.com/iolivernguyen/ggen/internal/log"
7+
"github.com/iolivernguyen/ggen/ggen/logging"
88
)
99

10-
type Logger = log.Logger
11-
type LogAttr = log.Attr
12-
type LogLevel = log.Level
13-
type LogHandler = log.Handler
10+
type Logger = logging.Logger
11+
type LogAttr = logging.Attr
12+
type LogLevel = logging.Level
13+
type LogHandler = logging.Handler
1414

1515
const (
16-
DebugLevel = log.DebugLevel
17-
InfoLevel = log.InfoLevel
18-
WarnLevel = log.WarnLevel
19-
ErrorLevel = log.ErrorLevel
16+
DebugLevel = logging.DebugLevel
17+
InfoLevel = logging.InfoLevel
18+
WarnLevel = logging.WarnLevel
19+
ErrorLevel = logging.ErrorLevel
2020
)
2121

2222
var logger Logger
@@ -27,23 +27,23 @@ type embededLogger struct {
2727

2828
type defaultLogHandler struct {
2929
w io.Writer
30-
level log.Level
31-
attrs []log.Attr
30+
level logging.Level
31+
attrs []logging.Attr
3232
}
3333

34-
func (h defaultLogHandler) Enabled(level log.Level) bool {
34+
func (h defaultLogHandler) Enabled(level logging.Level) bool {
3535
return level >= h.level
3636
}
3737

38-
func (h defaultLogHandler) WithAttrs(attrs []log.Attr) log.Handler {
39-
newAttrs := make([]log.Attr, 0, len(h.attrs)+len(attrs))
38+
func (h defaultLogHandler) WithAttrs(attrs []logging.Attr) logging.Handler {
39+
newAttrs := make([]logging.Attr, 0, len(h.attrs)+len(attrs))
4040
newAttrs = append(newAttrs, h.attrs...)
4141
newAttrs = append(newAttrs, attrs...)
4242
h.attrs = newAttrs
4343
return h // copy
4444
}
4545

46-
func (h defaultLogHandler) Handle(r log.Record) (err error) {
46+
func (h defaultLogHandler) Handle(r logging.Record) (err error) {
4747
debugEnabled := h.Enabled(-1)
4848
if debugEnabled {
4949
_, err = fmt.Fprintf(h.w, "%7s: %s", r.Level, r.Message)
@@ -58,7 +58,7 @@ func (h defaultLogHandler) Handle(r log.Record) (err error) {
5858
for _, attr := range h.attrs {
5959
fmt.Fprintf(h.w, " %s=%v", attr.Key, attr.Value)
6060
}
61-
r.Attrs(func(attr log.Attr) {
61+
r.Attrs(func(attr logging.Attr) {
6262
fmt.Fprintf(h.w, " %s=%q", attr.Key, attr.Value)
6363
})
6464
_, err = fmt.Fprintf(h.w, "\n")

ggen/logging/log.go

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
package logging
2+
3+
import (
4+
"context"
5+
"runtime"
6+
"strconv"
7+
"time"
8+
)
9+
10+
type Level int
11+
12+
const (
13+
DebugLevel Level = -4
14+
InfoLevel Level = 0
15+
WarnLevel Level = 4
16+
ErrorLevel Level = 8
17+
)
18+
19+
func (l Level) String() string {
20+
switch {
21+
case l < DebugLevel:
22+
return "DEBUG-" + strconv.Itoa(int(DebugLevel-l))
23+
case l == DebugLevel:
24+
return "DEBUG"
25+
case l < InfoLevel:
26+
return "DEBUG+" + strconv.Itoa(int(l-DebugLevel))
27+
case l == InfoLevel:
28+
return "INFO"
29+
case l < WarnLevel:
30+
return "INFO+" + strconv.Itoa(int(l-InfoLevel))
31+
case l == WarnLevel:
32+
return "WARN"
33+
case l < ErrorLevel:
34+
return "WARN+" + strconv.Itoa(int(l-WarnLevel))
35+
case l == ErrorLevel:
36+
return "ERROR"
37+
default:
38+
return "ERROR+" + strconv.Itoa(int(l-ErrorLevel))
39+
}
40+
}
41+
42+
type Attr struct {
43+
Key string
44+
Value any
45+
}
46+
47+
type Record struct {
48+
Time time.Time
49+
Message string
50+
Level Level
51+
Context context.Context
52+
53+
pc uintptr
54+
attrs []Attr
55+
}
56+
57+
func NewRecord(t time.Time, level Level, msg string, ctx context.Context, attrs []Attr) Record {
58+
return Record{
59+
Time: t,
60+
Message: msg,
61+
Level: level,
62+
Context: ctx,
63+
pc: pc(3),
64+
attrs: attrs,
65+
}
66+
}
67+
68+
func (r Record) Attrs(fn func(Attr)) {
69+
for _, attr := range r.attrs {
70+
fn(attr)
71+
}
72+
}
73+
74+
type Handler interface {
75+
Enabled(Level) bool
76+
Handle(Record) error
77+
WithAttrs([]Attr) Handler
78+
}
79+
80+
type Logger interface {
81+
Debug(msg string, args ...any)
82+
Enabled(level Level) bool
83+
Error(msg string, err error, args ...any)
84+
Info(msg string, args ...any)
85+
Log(level Level, msg string, args ...any)
86+
Warn(msg string, args ...any)
87+
With(args ...any) Logger
88+
WithContext(ctx context.Context) Logger
89+
}
90+
91+
type defaultLogger struct {
92+
handler Handler
93+
ctx context.Context
94+
}
95+
96+
func NewLogger(handler Handler) Logger {
97+
return &defaultLogger{
98+
handler: handler,
99+
}
100+
}
101+
102+
func (l defaultLogger) Debug(msg string, args ...any) {
103+
l.Log(DebugLevel, msg, args...)
104+
}
105+
106+
func (l defaultLogger) Enabled(level Level) bool {
107+
return l.handler.Enabled(level)
108+
}
109+
110+
func (l defaultLogger) Warn(msg string, args ...any) {
111+
l.Log(WarnLevel, msg, args...)
112+
}
113+
114+
func (l defaultLogger) Error(msg string, err error, args ...any) {
115+
if err != nil {
116+
args = append(args, Attr{Key: "err", Value: err})
117+
}
118+
l.Log(ErrorLevel, msg, args...)
119+
}
120+
121+
func (l defaultLogger) Info(msg string, args ...any) {
122+
l.Log(InfoLevel, msg, args...)
123+
}
124+
125+
func (l defaultLogger) Log(level Level, msg string, args ...any) {
126+
if !l.Enabled(level) {
127+
return
128+
}
129+
record := NewRecord(time.Now(), level, msg, l.ctx, argsToAttrs(args))
130+
_ = l.handler.Handle(record)
131+
}
132+
133+
func (l defaultLogger) With(args ...any) Logger {
134+
attrs := argsToAttrs(args)
135+
return NewLogger(l.handler.WithAttrs(attrs))
136+
}
137+
138+
func (l defaultLogger) WithContext(ctx context.Context) Logger {
139+
l.ctx = ctx
140+
return l
141+
}
142+
143+
// pc returns the program counter at the given stack depth.
144+
func pc(depth int) uintptr {
145+
var pcs [1]uintptr
146+
runtime.Callers(depth, pcs[:])
147+
return pcs[0]
148+
}
149+
150+
func argsToAttrs(args []any) (attrs []Attr) {
151+
for len(args) > 0 {
152+
switch arg := args[0].(type) {
153+
case string:
154+
if len(args) == 1 {
155+
attrs = append(attrs, Attr{Key: "BADKEY", Value: arg})
156+
args = args[1:]
157+
} else {
158+
attrs = append(attrs, Attr{Key: arg, Value: args[1]})
159+
args = args[2:]
160+
}
161+
case Attr:
162+
attrs = append(attrs, arg)
163+
args = args[1:]
164+
default:
165+
attrs = append(attrs, Attr{Key: "BADKEY", Value: arg})
166+
args = args[1:]
167+
}
168+
}
169+
return attrs
170+
}

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
22
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
33
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
44
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
5+
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
56
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
67
github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg=
78
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
89
golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
10+
golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
911
golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI=
1012
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
13+
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
1114
golang.org/x/tools v0.9.3 h1:Gn1I8+64MsuTb/HpH+LmQtNas23LhUVr3rYZ0eKuaMM=
15+
golang.org/x/tools v0.9.3/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc=
1216
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
1317
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

main.go

Lines changed: 14 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ import (
1111
)
1212

1313
var flClean = flag.Bool("clean", false, "clean generated files without generating new files")
14-
var flPlugins = flag.String("plugin", "", "comma separated list of plugins for generating (default to all plugins)")
15-
var flDisabledPlugins = flag.String("disable", "", "comma separated list of plugins to disable")
16-
var flNamespace = flag.String("namespace", "", "only parse and generate packages under this namespace (example: github.com/foo)")
14+
var flPlugin = flag.String("plugin", "", "comma separated list of plugins for generating (default to all plugins)")
15+
var flNamespace = flag.String("namespace", "", "github.com/myproject")
16+
var flVerbose = flag.Int("verbose", 0, "enable verbosity (0: info, 4: debug, 8: more debug)")
1717

1818
func usage() {
1919
const text = `
@@ -39,23 +39,20 @@ func Start(plugins ...ggen.Plugin) {
3939
os.Exit(2)
4040
}
4141

42-
enabledPlugins := allPluginNames(plugins)
43-
if *flPlugins != "" {
44-
enabledPlugins = strings.Split(*flPlugins, ",")
45-
}
46-
if *flDisabledPlugins != "" {
47-
ignoredPlugins := strings.Split(*flDisabledPlugins, ",")
48-
enabledPlugins = calcEnabledPlugins(enabledPlugins, ignoredPlugins)
49-
}
50-
5142
cfg := ggen.Config{
52-
CleanOnly: *flClean,
53-
Namespace: *flNamespace,
54-
EnabledPlugins: enabledPlugins,
55-
GoimportsArgs: []string{}, // example: -local github.com/foo
43+
LogLevel: -ggen.LogLevel(*flVerbose),
44+
CleanOnly: *flClean,
45+
Namespace: *flNamespace,
46+
GoimportsArgs: []string{}, // example: -local github.com/foo
47+
}
48+
cfg.RegisterPlugin(plugins...)
49+
if *flPlugin != "" {
50+
pluginNames := strings.Split(*flPlugin, ",")
51+
for _, name := range pluginNames {
52+
cfg.EnablePlugin(name)
53+
}
5654
}
5755

58-
must(ggen.RegisterPlugin(plugins...))
5956
must(ggen.Start(cfg, patterns...))
6057
}
6158

@@ -65,30 +62,3 @@ func must(err error) {
6562
os.Exit(1)
6663
}
6764
}
68-
69-
func allPluginNames(plugins []ggen.Plugin) []string {
70-
names := make([]string, len(plugins))
71-
for i, p := range plugins {
72-
names[i] = p.Name()
73-
}
74-
return names
75-
}
76-
77-
func calcEnabledPlugins(plugins []string, ignoredPlugins []string) []string {
78-
result := make([]string, 0, len(plugins))
79-
for _, p := range plugins {
80-
if !contains(ignoredPlugins, p) {
81-
result = append(result, p)
82-
}
83-
}
84-
return result
85-
}
86-
87-
func contains(ss []string, s string) bool {
88-
for _, _s := range ss {
89-
if _s == s {
90-
return true
91-
}
92-
}
93-
return false
94-
}

0 commit comments

Comments
 (0)