本文整理汇总了Golang中go/format.Source函数的典型用法代码示例。如果您正苦于以下问题:Golang Source函数的具体用法?Golang Source怎么用?Golang Source使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Source函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
}
开发者ID:hbdlb,项目名称:qml-1,代码行数:32,代码来源:main.go
示例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
}
}
开发者ID:hbdlb,项目名称:qml-1,代码行数:30,代码来源:main.go
示例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
}
开发者ID:ChimeraCoder,项目名称:gojson,代码行数:56,代码来源:json-to-struct.go
示例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)
}
}
开发者ID:135yshr,项目名称:slackbot,代码行数:50,代码来源:new.go
示例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)
}
}
开发者ID:Greentor,项目名称:go,代码行数:27,代码来源:encgen.go
示例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
}
开发者ID:JohanSJA,项目名称:grpc-gateway,代码行数:29,代码来源:generator.go
示例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)
}
}
开发者ID:samuell,项目名称:exp,代码行数:30,代码来源:gen.go
示例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)
}
开发者ID:hooklift,项目名称:govsphere,代码行数:26,代码来源:generator.go
示例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)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:31,代码来源:main.go
示例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)
}
}
开发者ID:hexiaochun,项目名称:gowalker,代码行数:32,代码来源:gen.go
示例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
}
开发者ID:bz2,项目名称:httprequest,代码行数:35,代码来源:main.go
示例12: formatGo
func formatGo(src string) (string, error) {
source, err := format.Source([]byte(src))
if err != nil {
return "", err
}
return string(source), nil
}
开发者ID:RoyDong,项目名称:xorm,代码行数:7,代码来源:go.go
示例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
}
开发者ID:joao-parana,项目名称:csfw,代码行数:30,代码来源:strings.go
示例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)
}
}
开发者ID:nangong92t,项目名称:go_src,代码行数:29,代码来源:gen.go
示例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)
}
}
开发者ID:bwmarrin,项目名称:discordgo,代码行数:29,代码来源:main.go
示例16: generateBinding
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
}
开发者ID:philipsoutham,项目名称:cqlc,代码行数:35,代码来源:generator.go
示例17: Generate
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
}
开发者ID:huhaibo,项目名称:mongoschema,代码行数:30,代码来源:mongoschema.go
示例18: TestMockMethodUnnamedValues
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))
}
开发者ID:jasonkeene,项目名称:hel,代码行数:25,代码来源:method_test.go
示例19: main
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)
}
}
开发者ID:supasate,项目名称:docker,代码行数:31,代码来源:mksyscall_windows.go
示例20: TestMockMethodParams
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))
}
开发者ID:jasonkeene,项目名称:hel,代码行数:25,代码来源:method_test.go
注:本文中的go/format.Source函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论