Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Format generated source code before writing it to the destination #3

Closed
wants to merge 2 commits into from
Closed
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
22 changes: 17 additions & 5 deletions mockgen/mockgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ package main
// TODO: This does not support embedding package-local interfaces in a separate file.

import (
"bytes"
"flag"
"fmt"
"go/format"
"go/token"
"io"
"log"
Expand Down Expand Up @@ -86,9 +88,7 @@ func main() {
packageName = "mock_" + sanitize(pkg.Name)
}

g := generator{
w: dst,
}
g := new(generator)
if *source != "" {
g.filename = *source
} else {
Expand All @@ -98,6 +98,9 @@ func main() {
if err := g.Generate(pkg, packageName); err != nil {
log.Fatalf("Failed generating mock: %v", err)
}
if _, err := dst.Write(g.Output()); err != nil {
log.Fatalf("Failed writing to destination: %v", err)
}
}

func usage() {
Expand All @@ -123,7 +126,7 @@ Example:
`

type generator struct {
w io.Writer
buf bytes.Buffer
indent string

filename string // may be empty
Expand All @@ -133,7 +136,7 @@ type generator struct {
}

func (g *generator) p(format string, args ...interface{}) {
fmt.Fprintf(g.w, g.indent+format+"\n", args...)
fmt.Fprintf(&g.buf, g.indent+format+"\n", args...)
}

func (g *generator) in() {
Expand Down Expand Up @@ -411,3 +414,12 @@ func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method)
g.p("}")
return nil
}

// Output returns the generator's output, formatted in the standard Go style.
func (g *generator) Output() []byte {
src, err := format.Source(g.buf.Bytes())
if err != nil {
log.Fatalf("Failed to format generated source code: %s\n%s", err, g.buf.String())
}
return src
}