Exemple #1
0
func processGlGo(dirName string) {
	data, err := ioutil.ReadFile(dirName + "/gl.go")
	if err != nil {
		log.Fatal("ioutil.ReadFile: ", err)
	}
	data, _ = format.Source(data)

	oldStr := "// #cgo pkg-config: Qt5Core Qt5OpenGL\n"
	newStr := "// #cgo !windows pkg-config: Qt5Core Qt5OpenGL\n// #cgo windows LDFLAGS: -L./goqgl -lgoqgl_{{.LibSuffix}}\n"

	newStr = strings.Replace(newStr, "{{.LibSuffix}}", libSuffix(dirName), -1)

	if *flagRevert {
		data = bytes.Replace(data, []byte(newStr), []byte(oldStr), -1)
		data, _ = format.Source(data)

		err = ioutil.WriteFile(dirName+"/gl.go", data, 0666)
		if err != nil {
			log.Fatal("ioutil.WriteFile: ", err)
		}
		return
	} else {
		data = bytes.Replace(data, []byte(oldStr), []byte(newStr), -1)
		data, _ = format.Source(data)

		err = ioutil.WriteFile(dirName+"/gl.go", data, 0666)
		if err != nil {
			log.Fatal("ioutil.WriteFile: ", err)
		}
		return
	}
}
Exemple #2
0
func processGlGo_importPath(dirName string) {
	data, err := ioutil.ReadFile(dirName + "/gl.go")
	if err != nil {
		log.Fatal("ioutil.ReadFile: ", err)
	}
	data, _ = format.Source(data)

	oldStr := `"gopkg.in/qml.v1/gl/glbase"`
	newStr := `"github.com/chai2010/qml/gl/glbase"`

	if *flagRevert {
		data = bytes.Replace(data, []byte(newStr), []byte(oldStr), -1)
		data, _ = format.Source(data)

		err = ioutil.WriteFile(dirName+"/gl.go", data, 0666)
		if err != nil {
			log.Fatal("ioutil.WriteFile: ", err)
		}
		return
	} else {
		data = bytes.Replace(data, []byte(oldStr), []byte(newStr), -1)
		data, _ = format.Source(data)

		err = ioutil.WriteFile(dirName+"/gl.go", data, 0666)
		if err != nil {
			log.Fatal("ioutil.WriteFile: ", err)
		}
		return
	}
}
// Given a JSON string representation of an object and a name structName,
// attemp to generate a struct definition
func Generate(input io.Reader, parser Parser, structName, pkgName string, tags []string, subStruct bool) ([]byte, error) {
	var subStructMap map[string]string = nil
	if subStruct {
		subStructMap = make(map[string]string)
	}

	var result map[string]interface{}

	iresult, err := parser(input)
	if err != nil {
		return nil, err
	}

	switch iresult := iresult.(type) {
	case map[interface{}]interface{}:
		result = convertKeysToStrings(iresult)
	case map[string]interface{}:
		result = iresult
	case []interface{}:
		src := fmt.Sprintf("package %s\n\ntype %s %s\n",
			pkgName,
			structName,
			typeForValue(iresult, structName, tags, subStructMap))
		formatted, err := format.Source([]byte(src))
		if err != nil {
			err = fmt.Errorf("error formatting: %s, was formatting\n%s", err, src)
		}
		return formatted, err
	default:
		return nil, fmt.Errorf("unexpected type: %T", iresult)
	}

	src := fmt.Sprintf("package %s\ntype %s %s}",
		pkgName,
		structName,
		generateTypes(result, structName, tags, 0, subStructMap))

	keys := make([]string, 0, len(subStructMap))
	for key := range subStructMap {
		keys = append(keys, key)
	}

	sort.Strings(keys)

	for _, k := range keys {
		src = fmt.Sprintf("%v\n\ntype %v %v", src, subStructMap[k], k)
	}

	formatted, err := format.Source([]byte(src))
	if err != nil {
		err = fmt.Errorf("error formatting: %s, was formatting\n%s", err, src)
	}
	return formatted, err
}
Exemple #4
0
func CmdNew(c *cli.Context) {
	log.SetFlags(log.Llongfile | log.LstdFlags)

	pkgName := c.String("pkg")
	if len(pkgName) <= 0 {
		fmt.Fprintf(os.Stderr, "not selected pkg name")
		os.Exit(2)
	}

	// mkdir
	if err := os.Mkdir(pkgName, 0755); err != nil {
		log.Fatalln(err)
	}

	// execute template
	var buf bytes.Buffer
	if err := PluginTmpl(&buf, pkgName); err != nil {
		log.Fatalln(err)
	}

	// go fmt
	srcBuf, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatalln(err)
	}

	// Write your code here
	filePath := filepath.Join(pkgName, pkgName+".go")
	if err := ioutil.WriteFile(filePath, srcBuf, 0644); err != nil {
		log.Fatalln(err)
	}

	// execute template
	buf.Reset()
	if err := PluginTestTmpl(&buf, pkgName); err != nil {
		log.Fatalln(err)
	}

	// go fmt
	srcBuf, err = format.Source(buf.Bytes())
	if err != nil {
		log.Fatalln(err)
	}

	// Write your code here
	filePath = filepath.Join(pkgName, pkgName+"_test.go")
	if err := ioutil.WriteFile(filePath, srcBuf, 0644); err != nil {
		log.Fatalln(err)
	}
}
Exemple #5
0
func main() {
	log.SetFlags(0)
	log.SetPrefix("encgen: ")
	flag.Parse()
	if flag.NArg() != 0 {
		log.Fatal("usage: encgen [--output filename]")
	}
	var b bytes.Buffer
	fmt.Fprintf(&b, "// Created by encgen --output %s; DO NOT EDIT\n", *output)
	fmt.Fprint(&b, header)
	printMaps(&b, "Array")
	fmt.Fprint(&b, "\n")
	printMaps(&b, "Slice")
	for _, t := range types {
		fmt.Fprintf(&b, arrayHelper, t.lower, t.upper)
		fmt.Fprintf(&b, sliceHelper, t.lower, t.upper, t.zero, t.encoder)
	}
	source, err := format.Source(b.Bytes())
	if err != nil {
		log.Fatal("source format error:", err)
	}
	fd, err := os.Create(*output)
	_, err = fd.Write(source)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #6
0
func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) {
	var files []*plugin.CodeGeneratorResponse_File
	for _, file := range targets {
		glog.V(1).Infof("Processing %s", file.GetName())
		code, err := g.generate(file)
		if err == errNoTargetService {
			glog.V(1).Infof("%s: %v", file.GetName(), err)
			continue
		}
		if err != nil {
			return nil, err
		}
		formatted, err := format.Source([]byte(code))
		if err != nil {
			glog.Errorf("%v: %s", err, code)
			return nil, err
		}
		name := file.GetName()
		ext := filepath.Ext(name)
		base := strings.TrimSuffix(name, ext)
		output := fmt.Sprintf("%s.pb.gw.go", base)
		files = append(files, &plugin.CodeGeneratorResponse_File{
			Name:    proto.String(output),
			Content: proto.String(string(formatted)),
		})
		glog.V(1).Infof("Will emit %s", output)
	}
	return files, nil
}
Exemple #7
0
func main() {
	flag.Parse()

	var buf bytes.Buffer

	fmt.Fprintln(&buf, "package bit")
	fmt.Fprintln(&buf)
	fmt.Fprintln(&buf, "// autogenerated by go run gen.go -output tables.go")
	fmt.Fprintln(&buf)

	table(&buf, "reverseByte", 256, func(v uint64) uint64 { return reverse(v, 8) })

	fmt.Fprintln(&buf)
	fmt.Fprintln(&buf, "const scanTableBits = 16")
	fmt.Fprintln(&buf, "const scanTableMask = (1<<scanTableBits)-1")

	table(&buf, "scanLeftTable", 256*256, scanLeft)

	table(&buf, "scanRightTable", 256*256, scanRight)

	data, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}

	err = ioutil.WriteFile(*filename, data, 0644)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #8
0
func genTypeRegistry(objects []Object, pkg string) {
	file := pkg + "/registry.go"

	fd, err := os.Create(file)
	if err != nil {
		log.Fatalln(err)
	}
	defer fd.Close()

	data := new(bytes.Buffer)
	data.WriteString("package " + pkg + "\n")

	tmpl := template.Must(template.New("registry").Parse(registryTmpl))
	err = tmpl.Execute(data, objects)
	if err != nil {
		log.Fatalln(err)
	}

	source := data.Bytes()
	fsource, err := format.Source(source)
	if err != nil {
		fd.Write(source)
		log.Fatalf("There are errors in the generated source for %s: %s\n", file, err.Error())
	}
	fd.Write(fsource)
}
Exemple #9
0
func main() {
	out := flag.String("o", "", "output file")
	flag.Parse()
	tmpl, err := template.New("tpl").Parse(fileTpl)
	if err != nil {
		log.Fatal(err)
	}
	lst := permission.PermissionRegistry.Permissions()
	sort.Sort(lst)
	data := context{
		Time:        time.Now(),
		Permissions: lst,
	}
	var buf bytes.Buffer
	err = tmpl.Execute(&buf, data)
	if err != nil {
		log.Fatal(err)
	}
	rawFile := buf.Bytes()
	rawFile = bytes.Replace(rawFile, []byte("\\\n"), []byte{}, -1)
	formatedFile, err := format.Source(rawFile)
	if err != nil {
		log.Fatalf("unable to format code: %s\n%s", err, rawFile)
	}
	file, err := os.OpenFile(*out, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0660)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	file.Write(formatedFile)
}
Exemple #10
0
func main() {
	log.SetFlags(0)
	log.SetPrefix("gen: ")
	flag.Parse()
	if flag.NArg() != 0 {
		log.Fatal("usage: decgen [--output filename]")
	}

	// Generate output.
	var buf bytes.Buffer
	err := tmpl.Execute(&buf, map[string]interface{}{
		"output":        *output,
		"goRepoPath":    goRepoPath,
		"goSubrepoPath": goSubrepoPath,
		"gaeRepoPath":   gaeRepoPath,
		"packagePath":   packagePath,
		"pathFlags":     getPathFlags(),
		"validTLDs":     getValidTLDs(),
	})
	if err != nil {
		log.Fatal("template error:", err)
	}
	source, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal("source format error:", err)
	}
	fd, err := os.Create(*output)
	_, err = fd.Write(source)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #11
0
func generate(serverPkg, serverType, clientType string) error {
	cwd, err := os.Getwd()
	if err != nil {
		return err
	}
	currentDir = cwd

	methods, imports, err := serverMethods(serverPkg, serverType)
	if err != nil {
		return errgo.Mask(err)
	}
	localPkg, err := build.Import(".", currentDir, 0)
	if err != nil {
		return errgo.Notef(err, "cannot open package in current directory")
	}
	arg := templateArg{
		CommandLine: strings.Join(flag.Args(), " "),
		Imports:     imports,
		Methods:     methods,
		PkgName:     localPkg.Name,
		ClientType:  clientType,
	}
	var buf bytes.Buffer
	if err := code.Execute(&buf, arg); err != nil {
		return errgo.Mask(err)
	}
	data, err := format.Source(buf.Bytes())
	if err != nil {
		return errgo.Notef(err, "cannot format source")
	}
	if err := writeOutput(data, clientType); err != nil {
		return errgo.Mask(err)
	}
	return nil
}
Exemple #12
0
func formatGo(src string) (string, error) {
	source, err := format.Source([]byte(src))
	if err != nil {
		return "", err
	}
	return string(source), nil
}
Exemple #13
0
// GenerateCode uses text/template for create Go code. package name pkg will also be used
// to remove stutter in variable names.
func GenerateCode(pkg, tplCode string, data interface{}, addFM template.FuncMap) ([]byte, error) {

	funcMap := template.FuncMap{
		"quote":           func(s string) string { return "`" + s + "`" },
		"prepareVar":      prepareVar(pkg),
		"camelize":        util.UnderscoreCamelize,
		"toLowerFirst":    toLowerFirst,
		"prepareVarIndex": func(i int, s string) string { return fmt.Sprintf("%03d%s", i, prepareVar(pkg)(s)) },
		"sprintf":         fmt.Sprintf,
	}
	for k, v := range addFM {
		funcMap[k] = v
	}

	codeTpl := template.Must(template.New("tpl_code").Funcs(funcMap).Parse(tplCode))

	var buf = new(bytes.Buffer)
	err := codeTpl.Execute(buf, data)
	if err != nil {
		return nil, errgo.Mask(err)
	}

	fmt, err := format.Source(buf.Bytes())
	if err != nil {
		return buf.Bytes(), err
	}
	return fmt, nil
}
Exemple #14
0
func main() {
	flag.Parse()

	w := new(bytes.Buffer)
	w.WriteString("// generated by \"go run gen.go\". DO NOT EDIT.\n\n" +
		"package draw\n\nimport (\n" +
		"\"image\"\n" +
		"\"image/color\"\n" +
		"\"math\"\n" +
		"\n" +
		"\"golang.org/x/image/math/f64\"\n" +
		")\n")

	gen(w, "nnInterpolator", codeNNScaleLeaf, codeNNTransformLeaf)
	gen(w, "ablInterpolator", codeABLScaleLeaf, codeABLTransformLeaf)
	genKernel(w)

	if *debug {
		os.Stdout.Write(w.Bytes())
		return
	}
	out, err := format.Source(w.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	if err := ioutil.WriteFile("impl.go", out, 0660); err != nil {
		log.Fatal(err)
	}
}
Exemple #15
0
func main() {
	var buf bytes.Buffer
	dir := filepath.Dir(".")

	fs := token.NewFileSet()
	parsedFile, err := parser.ParseFile(fs, "events.go", nil, 0)
	if err != nil {
		log.Fatalf("warning: internal error: could not parse events.go: %s", err)
		return
	}

	names := []string{}
	for object := range parsedFile.Scope.Objects {
		names = append(names, object)
	}
	sort.Strings(names)
	eventHandlerTmpl.Execute(&buf, names)

	src, err := format.Source(buf.Bytes())
	if err != nil {
		log.Println("warning: internal error: invalid Go generated:", err)
		src = buf.Bytes()
	}

	err = ioutil.WriteFile(filepath.Join(dir, strings.ToLower("eventhandlers.go")), src, 0644)
	if err != nil {
		log.Fatal(buf, "writing output: %s", err)
	}
}
Exemple #16
0
func generateBinding(opts *Options, version string, w io.Writer) error {

	cf, err := ColumnFamilies(opts)

	if err != nil {
		return err
	}

	provenance := Provenance{
		Version:   version,
		Timestamp: time.Now(),
	}

	meta := make(map[string]interface{})
	meta["Provenance"] = provenance
	meta["Options"] = opts
	meta["Imports"] = coalesceImports(cf)
	meta["ColumnFamilies"] = cf

	var b bytes.Buffer
	if err := bindingTemplate.Execute(&b, meta); err != nil {
		return err
	}

	bfmt, err := format.Source(b.Bytes())
	if err != nil {
		return err
	}

	if _, err := w.Write(bfmt); err != nil {
		return err
	}

	return nil
}
Exemple #17
0
func (s *Generator) Generate() error {
	session, collection, err := s.connect()
	if err != nil {
		return err
	}

	root := StructType{}
	iter := collection.Find(nil).Iter()
	m := bson.M{}
	for iter.Next(m) {
		root.Merge(NewType(m))
		m = bson.M{}
	}
	if err := iter.Close(); err != nil {
		return err
	}
	session.Close()

	const srcFmt = "package %s\ntype %s %s"
	src := fmt.Sprintf(srcFmt, s.Package, s.Struct, root.GoType())
	if s.Raw {
		fmt.Println(src)
	}
	formatted, err := format.Source([]byte(src))
	if err != nil {
		return err
	}
	fmt.Printf("%s\n", formatted)
	return nil
}
Exemple #18
0
func TestMockMethodUnnamedValues(t *testing.T) {
	expect := expect.New(t)

	spec := typeSpec(expect, `
 type Foo interface {
   Foo(int, string) (string, error)
 }`)
	mock, err := mocks.For(spec)
	expect(err).To.Be.Nil()
	method := mocks.MethodFor(mock, "Foo", method(expect, spec))

	expected, err := format.Source([]byte(`
 package foo

 func (m *mockFoo) Foo(arg0 int, arg1 string) (string, error) {
   m.FooCalled <- true
   m.FooInput.Arg0 <- arg0
   m.FooInput.Arg1 <- arg1
   return <-m.FooOutput.Ret0, <-m.FooOutput.Ret1
 }`))
	expect(err).To.Be.Nil()

	src := source(expect, "foo", []ast.Decl{method.Ast()}, nil)
	expect(src).To.Equal(string(expected))
}
Exemple #19
0
func main() {
	flag.Usage = usage
	flag.Parse()
	if len(flag.Args()) <= 0 {
		fmt.Fprintf(os.Stderr, "no files to parse provided\n")
		usage()
	}

	src, err := ParseFiles(flag.Args())
	if err != nil {
		log.Fatal(err)
	}

	var buf bytes.Buffer
	if err := src.Generate(&buf); err != nil {
		log.Fatal(err)
	}

	data, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	if *filename == "" {
		_, err = os.Stdout.Write(data)
	} else {
		err = ioutil.WriteFile(*filename, data, 0644)
	}
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #20
0
func TestMockMethodParams(t *testing.T) {
	expect := expect.New(t)

	spec := typeSpec(expect, `
 type Foo interface {
         Foo(foo, bar string, baz int)
 }`)
	mock, err := mocks.For(spec)
	expect(err).To.Be.Nil()
	method := mocks.MethodFor(mock, "Foo", method(expect, spec))

	expected, err := format.Source([]byte(`
 package foo

 func (m *mockFoo) Foo(foo, bar string, baz int) {
   m.FooCalled <- true
   m.FooInput.Foo <- foo
   m.FooInput.Bar <- bar
   m.FooInput.Baz <- baz
 }`))
	expect(err).To.Be.Nil()

	src := source(expect, "foo", []ast.Decl{method.Ast()}, nil)
	expect(src).To.Equal(string(expected))
}
Exemple #21
0
func writeTemplatedFile(templStr string, data interface{}) (error, []byte) {
	buf := new(bytes.Buffer)
	template.Must(template.New("some_template").Parse(templStr)).Execute(buf, data)

	formatted, err := format.Source(buf.Bytes())
	return err, formatted
}
func main() {
	certs, err := selectCerts()
	if err != nil {
		log.Fatal(err)
	}

	buf := new(bytes.Buffer)

	fmt.Fprintf(buf, "// Created by root_darwin_arm_gen --output %s; DO NOT EDIT\n", *output)
	fmt.Fprintf(buf, "%s", header)

	fmt.Fprintf(buf, "const systemRootsPEM = `\n")
	for _, cert := range certs {
		b := &pem.Block{
			Type:  "CERTIFICATE",
			Bytes: cert.Raw,
		}
		if err := pem.Encode(buf, b); err != nil {
			log.Fatal(err)
		}
	}
	fmt.Fprintf(buf, "`")

	source, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal("source format error:", err)
	}
	if err := ioutil.WriteFile(*output, source, 0644); err != nil {
		log.Fatal(err)
	}
}
Exemple #23
0
func GenFiles(out, project, tplStr string, bs []byte) error {
	models, apis, err := meta.Load(bs)
	if nil != err {
		return err
	}

	if !strings.HasSuffix(out, "/") {
		out += "/"
	}
	path_file := Convert(project, models, apis)
	for path, file := range path_file {
		if len(file.Models) == 0 && len(file.Apis) == 0 {
			continue
		}

		path = out + path
		if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
			return err
		}

		buf := bytes.NewBuffer(*new([]byte))
		GenFileContent(tplStr, file, buf)
		//		bs := wr.Bytes()
		bs, err := format.Source(buf.Bytes())
		if err != nil {
			return err
		}

		if err := ioutil.WriteFile(path, bs, os.ModePerm); err != nil {
			return err
		}
	}
	return nil
}
Exemple #24
0
func main() {
	var bb bytes.Buffer
	fmt.Fprintf(&bb, "// go run gentest.go\n")
	fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n")
	fmt.Fprintf(&bb, "package ipv6_test\n\n")
	for _, r := range registries {
		resp, err := http.Get(r.url)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url)
			os.Exit(1)
		}
		if err := r.parse(&bb, resp.Body); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		fmt.Fprintf(&bb, "\n")
	}
	b, err := format.Source(bb.Bytes())
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	os.Stdout.Write(b)
}
Exemple #25
0
func Generate(req *plugin.CodeGeneratorRequest) *plugin.CodeGeneratorResponse {
	// Begin by allocating a generator. The request and response structures are stored there
	// so we can do error handling easily - the response structure contains the field to
	// report failure.
	g := generator.New()
	g.Request = req

	g.CommandLineParameters(g.Request.GetParameter())

	// Create a wrapped version of the Descriptors and EnumDescriptors that
	// point to the file that defines them.
	g.WrapTypes()

	g.SetPackageNames()
	g.BuildTypeNameMap()

	g.GenerateAllFiles()

	gtest := generator.New()

	data, err := proto.Marshal(req)
	if err != nil {
		g.Error(err, "failed to marshal modified proto")
	}
	if err := proto.Unmarshal(data, gtest.Request); err != nil {
		g.Error(err, "parsing modified proto")
	}

	if len(gtest.Request.FileToGenerate) == 0 {
		gtest.Fail("no files to generate")
	}

	gtest.CommandLineParameters(gtest.Request.GetParameter())

	// Create a wrapped version of the Descriptors and EnumDescriptors that
	// point to the file that defines them.
	gtest.WrapTypes()

	gtest.SetPackageNames()
	gtest.BuildTypeNameMap()

	gtest.GeneratePlugin(testgen.NewPlugin())

	for i := 0; i < len(gtest.Response.File); i++ {
		if strings.Contains(*gtest.Response.File[i].Content, `//These tests are generated by github.com/andres-erbsen/protobuf/plugin/testgen`) {
			gtest.Response.File[i].Name = proto.String(strings.Replace(*gtest.Response.File[i].Name, ".pb.go", "pb_test.go", -1))
			g.Response.File = append(g.Response.File, gtest.Response.File[i])
		}
	}

	for i := 0; i < len(g.Response.File); i++ {
		formatted, err := format.Source([]byte(g.Response.File[i].GetContent()))
		if err != nil {
			g.Error(err, "go format error")
		}
		fmts := string(formatted)
		g.Response.File[i].Content = &fmts
	}
	return g.Response
}
Exemple #26
0
func main() {
	flag.Parse()
	zs, err := readWindowsZones()
	if err != nil {
		log.Fatal(err)
	}
	sort.Sort(zs)
	var v = struct {
		URL string
		Zs  zones
	}{
		wzURL,
		zs,
	}
	var buf bytes.Buffer
	err = template.Must(template.New("prog").Parse(prog)).Execute(&buf, v)
	if err != nil {
		log.Fatal(err)
	}
	data, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	err = ioutil.WriteFile(*filename, data, 0644)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #27
0
// Process takes a Go source file and bumps version declaration according to conf.
// Returns the modified code and a map from identifiers to updated versions and an error, if any.
func (conf Config) Process(filename string, src interface{}) ([]byte, map[string]string, error) {
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
	if err != nil {
		return nil, nil, err
	}

	versions, err := conf.ProcessNode(fset, file)
	if err != nil {
		return nil, nil, err
	}

	var buf bytes.Buffer
	err = printer.Fprint(&buf, fset, file)
	if err != nil {
		return nil, nil, err
	}

	out := buf.Bytes()

	out, err = format.Source(out)
	if err != nil {
		return nil, nil, err
	}

	return out, versions, nil
}
Exemple #28
0
func genzsys() error {
	defs := "defs_" + runtime.GOOS + ".go"
	f, err := os.Open(defs)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	f.Close()
	cmd := exec.Command("go", "tool", "cgo", "-godefs", defs)
	b, err := cmd.Output()
	if err != nil {
		return err
	}
	b, err = format.Source(b)
	if err != nil {
		return err
	}
	zsys := "zsys_" + runtime.GOOS + ".go"
	switch runtime.GOOS {
	case "freebsd", "linux":
		zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go"
	}
	if err := ioutil.WriteFile(zsys, b, 0644); err != nil {
		return err
	}
	return nil
}
Exemple #29
0
func geniana() error {
	var bb bytes.Buffer
	fmt.Fprintf(&bb, "// go generate gen.go\n")
	fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n")
	fmt.Fprintf(&bb, "package ipv6\n\n")
	for _, r := range registries {
		resp, err := http.Get(r.url)
		if err != nil {
			return err
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url)
		}
		if err := r.parse(&bb, resp.Body); err != nil {
			return err
		}
		fmt.Fprintf(&bb, "\n")
	}
	b, err := format.Source(bb.Bytes())
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile("iana.go", b, 0644); err != nil {
		return err
	}
	return nil
}
Exemple #30
0
// GoFmt returns the Go formated string of the input.
//
// Panics if the format fails.
func GoFmt(buf string) string {
	formatted, err := format.Source([]byte(buf))
	if err != nil {
		panic(fmt.Errorf("%s\nOriginal code:\n%s", err.Error(), buf))
	}
	return string(formatted)
}