本文整理汇总了Golang中go/format.Source函数的典型用法代码示例。如果您正苦于以下问题:Golang Source函数的具体用法?Golang Source怎么用?Golang Source使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Source函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: processGlGo
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
}
}
示例2: processGlGo_importPath
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
}
}
示例3: Generate
// 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
}
示例4: CmdNew
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)
}
}
示例5: main
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)
}
}
示例6: Generate
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
}
示例7: main
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)
}
}
示例8: genTypeRegistry
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)
}
示例9: main
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)
}
示例10: main
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)
}
}
示例11: generate
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
}
示例12: formatGo
func formatGo(src string) (string, error) {
source, err := format.Source([]byte(src))
if err != nil {
return "", err
}
return string(source), nil
}
示例13: GenerateCode
// 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
}
示例14: main
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)
}
}
示例15: main
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)
}
}