Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.
Closed
Changes from 1 commit
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
25 changes: 20 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 := generator{}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's make this

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.Format()); 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,15 @@ func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method)
g.p("}")
return nil
}

// Format gives a go-formatted copy of the buffer.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's call this Output.

// Output returns the generator's output, formatted in the standard Go style.

func (g *generator) Format() []byte {
src, err := format.Source(g.buf.Bytes())
if err != nil {
// This should never happen, but if it does, give the user a warning
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it should never happen, log.Fatalf is good enough. You can have it print out the buffer.

// and return the contents of the unmodified buffer.
log.Printf("Warning: generated source could not be go-formatted: %s", err)
return g.buf.Bytes()
}
return src
}