hexdigest / gowrap

GoWrap is a command line tool for generating decorators for Go interfaces
MIT License
1.09k stars 82 forks source link

Merge generated file with existing instead of overwriting #83

Open alenapetraki opened 8 months ago

alenapetraki commented 8 months ago

I want to edit generated methods and I want them not to be overwritten by next generation. If new methods are added to interface I want them to be generated and added to the existing file.

So what I want is some kind of strategy. Invocation may look like:

gowrap gen -i Some -t mine.tmpl -o generated.go -strategy merge|overwrite

How woild this work:

Template:

type {{$decorator}} struct {
  logger *zap.Logger
  next {{.Interface.Type}}
}

{{range $method := .Interface.Methods}}
func (m *{{$decorator}}) {{$method.Declaration}} {
    m.logger.Info("{{ $method.Name }}")
    {{ $method.Pass "m.next." }}
}
{{end}}

Initial interface:

type Some interface {
    A()
}

Initial generated file:

type decorator struct {
    logger *zap.Logger
    next Some
}

func (d *decorator) A() {
    m.logger.Info("A") 
    m.next.A()
}

Updated file:

type decorator struct {
    logger *zap.Logger
    next Some
}

func (d *decorator) A() {
    m.logger.Info("A with updates") // updated generated file
    m.next.A()
}

Updated interface:

type Some interface {
    A()
    B() // New added method
}

Generated with stratedy 'merge' file:

type decorator struct {
    logger *zap.Logger
    next Some
}

func (d *decorator) A() {
    m.logger.Info("A with updates") // updates are not overwritten
    m.next.A()
}

func (d *decorator) B() {
    m.logger.Info("B") 
    m.next.A()
}

If you believe there is a place for such a feature in this library I might be able to implement it myself.