예제 #1
0
파일: generator.go 프로젝트: bketelsen/goa
func (m *Generator) generateToolSourceCode(pkg *codegen.Package) {
	file := pkg.CreateSourceFile("main.go")
	imports := append(m.Imports,
		codegen.SimpleImport("fmt"),
		codegen.SimpleImport("os"),
		codegen.SimpleImport("strings"),
		codegen.NewImport(".", "github.com/raphael/goa/design"),
		codegen.NewImport(".", "github.com/raphael/goa/design/dsl"),
		codegen.NewImport("_", filepath.ToSlash(codegen.DesignPackagePath)),
	)
	file.WriteHeader("Code Generator", "main", imports)
	tmpl, err := template.New("generator").Parse(mainTmpl)
	if err != nil {
		panic(err) // bug
	}
	pkgName, err := codegen.PackageName(pkg.Abs())
	if err != nil {
		panic(err)
	}
	context := map[string]string{
		"Genfunc":       m.Genfunc,
		"DesignPackage": codegen.DesignPackagePath,
		"PkgName":       pkgName,
	}
	err = tmpl.Execute(file, context)
	if err != nil {
		panic(err) // bug
	}
	if codegen.Debug {
		src, _ := ioutil.ReadFile(file.Abs())
		fmt.Printf("goagen source:\n%s\n", src)
	}
}
예제 #2
0
파일: generator.go 프로젝트: bketelsen/goa
// Generate compiles and runs the generator and returns the generated filenames.
func (m *Generator) Generate() ([]string, error) {
	if codegen.OutputDir == "" {
		return nil, fmt.Errorf("missing output directory specification")
	}

	if codegen.DesignPackagePath == "" {
		return nil, fmt.Errorf("missing design package path specification")
	}

	if os.Getenv("GOPATH") == "" {
		return nil, fmt.Errorf("GOPATH not set")
	}

	// Create output directory
	if err := os.MkdirAll(codegen.OutputDir, 0755); err != nil {
		return nil, err
	}

	// Create temporary workspace used for generation
	w, err := codegen.NewWorkspace("goagen")
	if err != nil {
		if _, ok := err.(*os.PathError); ok {
			err = fmt.Errorf(`invalid output directory path "%s"`, codegen.OutputDir)
		}
		return nil, err
	}
	defer func() {
		if !codegen.Debug {
			w.Delete()
		}
	}()
	if codegen.Debug {
		fmt.Printf("goagen source dir: %s\n", w.Path)
	}

	// Figure out design package name from its path
	path, err := codegen.PackageSourcePath(codegen.DesignPackagePath)
	if err != nil {
		return nil, err
	}
	pkgName, err := codegen.PackageName(path)
	if err != nil {
		return nil, err
	}

	// Generate tool source code.
	p, err := w.NewPackage(pkgName)
	if err != nil {
		return nil, err
	}
	m.generateToolSourceCode(p)

	// Compile and run generated tool.
	genbin, err := p.Compile("goagen")
	if err != nil {
		return nil, err
	}
	return m.spawn(genbin)
}