Beispiel #1
0
// NewGenerator initializes a Generator
func NewGenerator(pkg, target string) (*Generator, error) {
	var err error
	if pkg == "" || pkg[0] == '.' {
		pkg, err = filepath.Abs(filepath.Clean(pkg))
		if err != nil {
			return nil, err
		}
		pkg = gogenutil.StripGopath(pkg)
	}
	p, err := importer.Default().Import(pkg)
	if err != nil {
		return nil, err
	}
	obj := p.Scope().Lookup(target)
	if obj == nil {
		return nil, fmt.Errorf("struct %s missing", target)
	}
	if _, ok := obj.Type().Underlying().(*types.Struct); !ok {
		return nil, fmt.Errorf("%s should be an struct, was %s", target, obj.Type().Underlying())
	}
	return &Generator{
		targetName: target,
		pkg:        p,
		target:     obj.Type().Underlying().(*types.Struct),
	}, nil
}
Beispiel #2
0
func main() {
	flag.Parse()
	log.SetFlags(0)

	iface := flag.Arg(0)

	if iface == "" {
		log.Fatal("need to specify an interface name")
	}

	parts := strings.Split(iface, ".")
	switch len(parts) {
	case 1:
	case 2:
		if *pkg != "." {
			log.Fatalf("unexpected -pkg value (%q), package is already defined in the interface name as %s", *pkg, parts[0])
		}
		*pkg = parts[0]
		iface = parts[1]
	default:
		log.Fatalf("invalid interface %q", iface)
	}

	gen, err := automock.NewGenerator(*pkg, iface)
	if err != nil {
		log.Fatal(err)
	}

	gen.SetTemplate(template)

	if *mockName != "" {
		gen.SetName(*mockName)
	}
	inPkg := *pkg == "." && path.Dir(*out) == "."
	gen.SetInternal(inPkg)
	if *mockPkg == "" && !inPkg {
		p, err := importer.Default().Import(".")
		if err != nil {
			log.Fatal(err)
		}
		*mockPkg = p.Name()
	}
	if *mockPkg != "" {
		gen.SetPackage(*mockPkg)
	}

	w := os.Stdout
	if *out == "" {
		*out = fmt.Sprintf("%s_test.go", gen.Name())
		if p := regexp.MustCompile(".*/").ReplaceAllString(*pkg, ""); !inPkg && p != "" && p != "." {
			*out = p + "_" + *out
		}
	}
	if *out != "-" {
		*out = strconv.SnakeCase(*out)
		log.Printf("Generating mock for %s in %s", iface, *out)
		w, err = os.OpenFile(*out, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
		if err != nil {
			log.Fatal(err)
		}
	}

	err = gen.Write(w)
	switch err := err.(type) {
	case automock.GenerationError:
		log.Println(err.CodeWithLineNumbers())
		log.Fatal(err)
	case error:
		log.Fatal(err)
	}
}