当前位置: 首页>>代码示例>>Golang>>正文


Golang Config.Fprint方法代码示例

本文整理汇总了Golang中go/printer.Config.Fprint方法的典型用法代码示例。如果您正苦于以下问题:Golang Config.Fprint方法的具体用法?Golang Config.Fprint怎么用?Golang Config.Fprint使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在go/printer.Config的用法示例。


在下文中一共展示了Config.Fprint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: generateRunner

func generateRunner(filename string, testMains []*TestMain) os.Error {
	src := bytes.NewBufferString("")
	fmt.Fprint(src, "package main\n\n")
	fmt.Fprint(src, "import \"sync\"\n")
	fmt.Fprint(src, "import \"testing\"\n")
	fmt.Fprint(src, "import (\n")
	for _, testMain := range testMains {
		name := testMain.underscorePkgName()
		fmt.Fprintf(src, "%s \"%s\"\n", name, testMain.pkgName)
	}
	fmt.Fprint(src, ")\n")
	fmt.Fprint(src, "func main() {\n")
	fmt.Fprint(src, "wg := new(sync.WaitGroup)\n")
	for _, testMain := range testMains {
		pkgName := testMain.underscorePkgName()
		fmt.Fprint(src, "wg.Add(1)\n")
		fmt.Fprint(src, "go func() {\n")
		fmt.Fprint(src, "tests := []testing.InternalTest{\n")
		for _, test := range testMain.tests {
			testFunc := pkgName + "." + test
			fmt.Fprintf(src, "{\"%s\", %s},\n", testMain.pkgName+"."+test, testFunc)
		}
		fmt.Fprint(src, "}\n")
		fmt.Fprint(src, "benchmarks := []testing.InternalBenchmark{\n")
		for _, bench := range testMain.benchmarks {
			benchFunc := pkgName + "." + bench
			fmt.Fprintf(src, "{\"%s\", %s},\n", testMain.pkgName+"."+bench, benchFunc)
		}
		fmt.Fprint(src, "}\n")
		fmt.Fprintf(src, "for i := 0; i < %d; i++ {\n", iters)
		fmt.Fprint(src, "testing.Main(regexp.MatchString, tests)\n")
		fmt.Fprint(src, "testing.RunBenchmarks(regexp.MatchString, benchmarks)\n")
		fmt.Fprint(src, "}\n")
		fmt.Fprint(src, "wg.Done()\n")
		fmt.Fprint(src, "}()\n\n")
	}
	fmt.Fprint(src, "wg.Wait()\n")
	fmt.Fprint(src, "}\n")

	file, err := os.Open(filename, os.O_CREAT|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		return err
	}
	defer file.Close()

	//fmt.Printf("%s\n", string(src.Bytes()))

	fileNode, err := parser.ParseFile(token.NewFileSet(), filename, src.Bytes(), 0)
	if err != nil {
		panic(err)
	}

	config := printer.Config{printer.TabIndent, 8}
	_, err = config.Fprint(file, token.NewFileSet(), fileNode)
	if err != nil {
		return err
	}

	return nil
}
开发者ID:alberts,项目名称:gostress,代码行数:60,代码来源:gostress.go

示例2: print

func (f *File) print(w io.Writer) {
	cfg := printer.Config{
		Mode:     printer.SourcePos,
		Tabwidth: 8,
		Indent:   0,
	}
	cfg.Fprint(w, f.fset, f.astFile)
}
开发者ID:pierrec,项目名称:go-fuzz,代码行数:8,代码来源:cover.go

示例3: codeToString

func codeToString(fset *token.FileSet, i interface{}) string {
	b := bytes.NewBuffer(make([]byte, 0, 128))
	tmpb := bytes.NewBuffer(make([]byte, 0, 128))
	flags := printer.UseSpaces | printer.TabIndent
	config := printer.Config{flags, 8}
	config.Fprint(tmpb, fset, i)
	template.HTMLEscape(b, tmpb.Bytes())
	return b.String()
}
开发者ID:nsf,项目名称:gortfm,代码行数:9,代码来源:jsencode.go

示例4: Generate

func Generate(prog *loader.Program, getFileBytes func(string) ([]byte, error), writerFor func(importPath, filename string) io.WriteCloser) {
	for _, pkgInfo := range prog.InitialPackages() {
		defs = pkgInfo.Defs
		_types = pkgInfo.Types
		pkg = pkgInfo.Pkg
		path := pkg.Path()
		if !pkgInfo.Importable && strings.HasSuffix(pkgInfo.Pkg.Name(), "_test") {
			// EXTERNAL TEST package, strip the _test to find the path
			path = strings.TrimSuffix(pkg.Path(), "_test")
		}
		idents.pkgScope = generatePackageScopeIdent(pkgInfo)
		for i, f := range pkgInfo.Files {
			fs = prog.Fset
			fname := fs.Position(f.Pos()).Filename
			if strings.HasSuffix(fname, "/C") {
				continue
			}
			b, err := getFileBytes(fname)
			if err != nil {
				fmt.Fprint(os.Stderr, "Error reading file:", err)
				os.Exit(1)
			}
			b = normalizeCRLF(b)
			quotedContents := rawQuote(string(b))
			ast1, fs1 := parseCgoFile(fname, b)
			if ast1 != nil {
				f = ast1
				fs = fs1
			}
			generateGodebugIdentifiers(f)
			ast.Walk(&visitor{context: f, scopeVar: idents.fileScope}, f)
			importName := idents.godebug
			if importName == "godebug" {
				importName = ""
			}
			astutil.AddNamedImport(fs, f, importName, "github.com/mailgun/godebug/lib")
			cfg := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
			out := writerFor(path, fname)
			defer out.Close()
			_ = cfg.Fprint(out, fs, f)
			fmt.Fprintln(out, "\nvar", idents.fileContents, "=", quotedContents)
			if i == 0 {
				err := generatePackageFile(idents.pkgScope, pkgInfo, out)
				if err != nil {
					fmt.Fprint(os.Stderr, "Error writing package file:", err)
					os.Exit(1)
				}
			}
		}
	}
}
开发者ID:philipmulcahy,项目名称:godebug,代码行数:51,代码来源:gen.go

示例5: Generate

// Generates a Go file with the given name using the provided template and
// template data.
func (g *goFileGenerator) Generate(filename, tmpl string, data interface{}) ([]byte, error) {
	funcs := template.FuncMap{
		"import":     g.Import,
		"formatType": g.FormatType,
	}
	for k, v := range g.templateFuncs {
		funcs[k] = v
	}

	t, err := template.New(filename).Delims("<", ">").Funcs(funcs).Parse(tmpl)
	if err != nil {
		return nil, fmt.Errorf("failed to parse template %q: %v", filename, err)
	}

	var buff bytes.Buffer
	if err := t.Execute(&buff, data); err != nil {
		return nil, err
	}

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, filename, buff.Bytes(), parser.ParseComments)
	if err != nil {
		return nil, fmt.Errorf("failed to parse generated code: %v:\n%s", err, buff.String())
	}

	if len(f.Imports) > 0 {
		return nil, fmt.Errorf(
			"plain imports are not allowed with GoFileFromTemplate: use the import function")
	}

	importPaths := make([]string, 0, len(g.imports))
	for path := range g.imports {
		importPaths = append(importPaths, path)
	}
	sort.Strings(importPaths)
	for _, path := range importPaths {
		astutil.AddNamedImport(fset, f, g.imports[path], path)
	}

	cfg := printer.Config{
		Mode:     printer.UseSpaces | printer.TabIndent,
		Tabwidth: 8,
	}

	buff = bytes.Buffer{}
	if err := cfg.Fprint(&buff, fset, f); err != nil {
		return nil, err // TODO wrap error
	}

	return buff.Bytes(), nil
}
开发者ID:thriftrw,项目名称:thriftrw-go,代码行数:53,代码来源:template.go

示例6: main

func main() {
	log.SetFlags(0)
	if len(os.Args) != 2 {
		log.Fatalf("Usage: %s FILE", os.Args[0])
	}
	f, err := parser.ParseFile(fset, os.Args[1], nil, parser.ParseComments)
	if err != nil {
		log.Fatal(err)
	}
	ast.Walk(&Visitor{}, f)
	config := printer.Config{Mode: 0, Tabwidth: 8}
	if err := config.Fprint(os.Stdout, fset, f); err != nil {
		log.Fatal(err)
	}
}
开发者ID:nbaum,项目名称:x,代码行数:15,代码来源:main.go

示例7: Write

func (g *generator) Write(w io.Writer, fs *token.FileSet) error {
	// TODO constants first, types next, and functions after that

	if _, err := w.Write([]byte(generatedByHeader)); err != nil {
		return err
	}

	if _, err := fmt.Fprintf(w, "package %s\n\n", g.PackageName); err != nil {
		return err
	}

	cfg := printer.Config{
		Mode:     printer.UseSpaces | printer.TabIndent,
		Tabwidth: 8,
	}

	if importDecl := g.importDecl(); importDecl != nil {
		if err := cfg.Fprint(w, fs, importDecl); err != nil {
			return err
		}
	}

	if _, err := io.WriteString(w, "\n"); err != nil {
		return err
	}

	for _, decl := range g.decls {
		if _, err := io.WriteString(w, "\n"); err != nil {
			return err
		}

		if err := cfg.Fprint(w, fs, decl); err != nil {
			return err
		}

		if _, err := io.WriteString(w, "\n"); err != nil {
			return err
		}
	}

	g.decls = nil
	g.importer = newImporter(g.Namespace.Child())

	// init can appear multiple times in the same package across different
	// files
	g.Namespace.Forget("init")
	return nil
}
开发者ID:thriftrw,项目名称:thriftrw-go,代码行数:48,代码来源:generator.go

示例8: source

func (s *Session) source(space bool) (string, error) {
	normalizeNodePos(s.mainFunc())

	var config *printer.Config
	if space {
		config = &printer.Config{
			Mode:     printer.UseSpaces,
			Tabwidth: 4,
		}
	} else {
		config = &printer.Config{
			Tabwidth: 8,
		}
	}

	var buf bytes.Buffer
	err := config.Fprint(&buf, s.Fset, s.File)
	return buf.String(), err
}
开发者ID:jonfk,项目名称:gore,代码行数:19,代码来源:main.go

示例9: gen

func gen(o Options, fset *token.FileSet, n ast.Node) ([]byte, error) {
	v := &visitor{Options: o}
	ast.Walk(v, n)
	if v.err != nil {
		return nil, v.err
	}
	if !v.changed {
		return nil, nil
	}
	c := printer.Config{Mode: printer.RawFormat}
	buf := &bytes.Buffer{}
	if err := c.Fprint(buf, fset, n); err != nil {
		return nil, fmt.Errorf("error printing output: %s", err)
	}
	b, err := format.Source(buf.Bytes())
	if err != nil {
		return nil, err
	}
	return b, nil
}
开发者ID:nange,项目名称:graffiti,代码行数:20,代码来源:generate.go

示例10: BumpInFile

// BumpInFile finds a constant named VERSION, version, or Version in the file
// with the given filename, increments the version per the given VersionType,
// and writes the file back to disk. Returns the incremented Version object.
func BumpInFile(vtype VersionType, filename string) (*Version, error) {
	fset := token.NewFileSet()
	parsedFile, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
	if err != nil {
		return nil, err
	}
	for _, decl := range parsedFile.Decls {
		switch gd := decl.(type) {
		case *ast.GenDecl:
			if gd.Tok != token.CONST {
				continue
			}
			spec, _ := gd.Specs[0].(*ast.ValueSpec)
			if strings.ToUpper(spec.Names[0].Name) == "VERSION" {
				value, _ := spec.Values[0].(*ast.BasicLit)
				if value.Kind != token.STRING {
					return nil, fmt.Errorf("VERSION is not a string, was %#v\n", value.Value)
				}
				version, err := changeVersion(vtype, value.Value)
				if err != nil {
					return nil, err
				}
				value.Value = fmt.Sprintf("\"%s\"", version.String())
				f, err := os.Create(filename)
				if err != nil {
					return nil, err
				}
				cfg := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
				err = cfg.Fprint(f, fset, parsedFile)
				if err != nil {
					return nil, err
				}
				return version, nil
			}
		default:
			continue
		}
	}
	return nil, fmt.Errorf("No VERSION const found in %s", filename)
}
开发者ID:Shyp,项目名称:bump_version,代码行数:43,代码来源:lib.go

示例11: rewrite

func rewrite(name, id, hash, base string) {
	cmdir := filepath.Join(base, "cmd", name)
	path := filepath.Join(cmdir, "main.go")
	mainfile, err := os.OpenFile(path, os.O_RDWR, 0660)
	if err != nil {
		log.Fatal(err)
	}
	defer mainfile.Close()

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, path, mainfile, parser.ParseComments)
	if err != nil {
		log.Fatal(err)
	}

	for _, d := range f.Decls {
		d, ok := d.(*ast.GenDecl)
		if !ok {
			continue
		}

		if d.Tok != token.CONST {
			continue
		}
		for _, spec := range d.Specs {
			spec, ok := spec.(*ast.ValueSpec)
			if !ok {
				continue
			}

			if len(spec.Names) != 1 || len(spec.Values) != 1 {
				continue
			}

			value, ok := spec.Values[0].(*ast.BasicLit)
			if !ok {
				continue
			}

			switch spec.Names[0].Name {
			case "VersionDate":
				value.Value = id
			case "VersionID":
				value.Value = hash
			}
		}
	}

	var config = printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
	var buf bytes.Buffer
	if err := config.Fprint(&buf, fset, f); err != nil {
		log.Fatal(err)
	}

	if _, err := mainfile.Seek(0, os.SEEK_SET); err != nil {
		log.Fatal(err)
	}

	if _, err := io.Copy(mainfile, &buf); err != nil {
		log.Fatal(err)
	}
}
开发者ID:eswdd,项目名称:bosun,代码行数:62,代码来源:build.go

示例12: Format

// Format formats the given package file originally obtained from src
// and adjusts the result based on the original source via sourceAdj
// and indentAdj.
func Format(
	fset *token.FileSet,
	file *ast.File,
	sourceAdj func(src []byte, indent int) []byte,
	indentAdj int,
	src []byte,
	cfg printer.Config,
) ([]byte, error) {
	if sourceAdj == nil {
		// Complete source file.
		var buf bytes.Buffer
		err := cfg.Fprint(&buf, fset, file)
		if err != nil {
			return nil, err
		}
		return buf.Bytes(), nil
	}

	// Partial source file.
	// Determine and prepend leading space.
	i, j := 0, 0
	for j < len(src) && IsSpace(src[j]) {
		if src[j] == '\n' {
			i = j + 1 // byte offset of last line in leading space
		}
		j++
	}
	var res []byte
	res = append(res, src[:i]...)

	// Determine and prepend indentation of first code line.
	// Spaces are ignored unless there are no tabs,
	// in which case spaces count as one tab.
	indent := 0
	hasSpace := false
	for _, b := range src[i:j] {
		switch b {
		case ' ':
			hasSpace = true
		case '\t':
			indent++
		}
	}
	if indent == 0 && hasSpace {
		indent = 1
	}
	for i := 0; i < indent; i++ {
		res = append(res, '\t')
	}

	// Format the source.
	// Write it without any leading and trailing space.
	cfg.Indent = indent + indentAdj
	var buf bytes.Buffer
	err := cfg.Fprint(&buf, fset, file)
	if err != nil {
		return nil, err
	}
	res = append(res, sourceAdj(buf.Bytes(), cfg.Indent)...)

	// Determine and append trailing space.
	i = len(src)
	for i > 0 && IsSpace(src[i-1]) {
		i--
	}
	return append(res, src[i:]...), nil
}
开发者ID:RobHoyt,项目名称:go,代码行数:70,代码来源:format.go

示例13: writeSingleTest

func writeSingleTest(testMain *TestMain, testName string, testType int, filename string) os.Error {

	src := bytes.NewBufferString("")

	fmt.Fprint(src, "// "+testMain.pkgName+"."+testName+"\n")

	fmt.Fprint(src, "//\n")
	fmt.Fprint(src, "package main\n\n")
	fmt.Fprint(src, "import \"sync\"\n")
	fmt.Fprint(src, "import \"testing\"\n")
	if testMain.pkgName != "regexp" {
		fmt.Fprint(src, "import \"regexp\"\n")
	}
	fmt.Fprintf(src, "import %s \"%s\"\n", testMain.underscorePkgName(), testMain.pkgName)
	fmt.Fprint(src, "\nfunc main() {\n")
	fmt.Fprint(src, "wg := new(sync.WaitGroup)\n")
	pkgName := testMain.underscorePkgName()

	fmt.Fprintf(src, "for i := 0; i < %d; i++ {\n", iters)

	fmt.Fprint(src, "wg.Add(1)\n")
	fmt.Fprint(src, "go func() {\n")
	if testType == 0 {
		fmt.Fprint(src, "tests := []testing.InternalTest{\n")
		testFunc := pkgName + "." + testName
		fmt.Fprintf(src, "{\"%s\", %s},\n", testMain.pkgName+"."+testName, testFunc)
		fmt.Fprint(src, "}\n")
		fmt.Fprint(src, "testing.Main(regexp.MatchString, tests)\n")
	} else if testType == 1 {
		fmt.Fprint(src, "benchmarks := []testing.InternalBenchmark{\n")
		benchFunc := pkgName + "." + testName
		fmt.Fprintf(src, "{\"%s\", %s},\n", testMain.pkgName+"."+testName, benchFunc)
		fmt.Fprint(src, "}\n")
		fmt.Fprint(src, "testing.RunBenchmarks(regexp.MatchString, benchmarks)\n")
	}

	fmt.Fprint(src, "wg.Done()\n")
	fmt.Fprint(src, "}()\n")

	fmt.Fprint(src, "}\n\n")
	fmt.Fprint(src, "wg.Wait()\n")
	fmt.Fprint(src, "}\n")

	//fmt.Printf("%s\n", string(src.Bytes()))

	file, err := os.Open(filename, os.O_CREAT|os.O_TRUNC|os.O_WRONLY, 0666)

	if err != nil {
		return err
	}
	defer file.Close()

	fileset := token.NewFileSet()

	fileNode, err := parser.ParseFile(fileset, filename, src.Bytes(), parser.ParseComments)
	if err != nil {
		panic(err)
	}

	config := printer.Config{printer.TabIndent, 8}
	_, err = config.Fprint(file, fileset, fileNode)
	if err != nil {
		return err
	}
	return nil
}
开发者ID:alberts,项目名称:gostress,代码行数:66,代码来源:gostress.go

示例14: main

func main() {
	flag.Usage = usage
	flag.Parse()

	if flag.NArg() == 0 {
		flag.Usage()
	}

	fileContents := map[string]string{}

	fset := token.NewFileSet()

	for i := 0; i < flag.NArg(); i++ {
		arg := flag.Arg(i)
		fi, err := os.Stat(arg)
		dieIf(err)

		if fi.IsDir() {
			if i != 0 {
				die("you can only specify exact one directory")
			}

			fis, err := ioutil.ReadDir(arg)
			dieIf(err)

			for _, fi := range fis {
				if fi.IsDir() {
					continue
				}

				name := fi.Name()
				if !strings.HasSuffix(name, ".go") {
					continue
				}
				if name[0] == '_' || name[0] == '.' {
					continue
				}

				filename := filepath.Join(arg, name)
				b, err := ioutil.ReadFile(filename)
				dieIf(err)

				fileContents[filename] = string(b)
			}
		} else {
			b, err := ioutil.ReadFile(arg)
			dieIf(err)

			fileContents[arg] = string(b)
		}

	}

	ff, err := parseFiles(fset, fileContents)
	dieIf(err)

	if *flagRevert {
		err = quickfix.RevertQuickFix(fset, ff)
	} else {
		err = quickfix.QuickFix(fset, ff)
	}
	dieIf(err)

	for _, f := range ff {
		filename := fset.File(f.Pos()).Name()

		var buf bytes.Buffer
		conf := printer.Config{
			Tabwidth: 8,
			Mode:     printer.UseSpaces | printer.TabIndent,
		}
		err := conf.Fprint(&buf, fset, f)
		dieIf(err)

		if buf.String() == fileContents[filename] {
			// no change, skip this file
			continue
		}

		out := os.Stdout
		if *flagWrite {
			out, err = os.Create(filename)
			dieIf(err)
		}

		buf.WriteTo(out)
	}
}
开发者ID:Pinkxa,项目名称:gophernotes,代码行数:88,代码来源:main.go

示例15: Compile

func (t *Tree) Compile(file string) {
	counts := [TypeLast]uint{}

	for element := t.Front(); element != nil; element = element.Next() {
		node := element.Value.(Node)
		switch node.GetType() {
		case TypePackage:
			t.PackageName = node.String()
		case TypePeg:
			t.StructName = node.String()
			t.StructVariables = node.Front().String()
		case TypeRule:
			t.Rules[node.String()] = node
			t.RuleNames = append(t.RuleNames, node)
		}
	}

	/*Needed for undefined rules!*/
	for name, r := range t.Rules {
		if r.String() == "" {
			r := &node{Type: TypeRule, string: name, id: t.ruleId}
			r.PushBack(&node{Type: TypeNil, string: "<nil>"})
			t.ruleId++
			t.Rules[name] = r
			t.PushBack(r)
		}
	}
	t.RulesCount = len(t.Rules)

	join([]func(){
		func() {
			var countTypes func(node Node)
			countTypes = func(node Node) {
				nodeType := node.GetType()
				id := counts[nodeType]
				counts[nodeType]++
				switch nodeType {
				case TypeAction:
					node.SetId(int(id))
					t.Actions = append(t.Actions, node)
				case TypeRule, TypeAlternate, TypeUnorderedAlternate, TypeSequence,
					TypePeekFor, TypePeekNot, TypeQuery, TypeStar, TypePlus, TypePush:
					for element := node.Front(); element != nil; element = element.Next() {
						countTypes(element)
					}
				}
			}
			for _, rule := range t.Rules {
				countTypes(rule)
			}
		},
		func() {
			var countRules func(node Node)
			ruleReached := make([]bool, len(t.Rules))
			countRules = func(node Node) {
				switch node.GetType() {
				case TypeRule:
					name, id := node.String(), node.GetId()
					if count, ok := t.rulesCount[name]; ok {
						t.rulesCount[name] = count + 1
					} else {
						t.rulesCount[name] = 1
					}
					if ruleReached[id] {
						return
					}
					ruleReached[id] = true
					countRules(node.Front())
				case TypeName:
					countRules(t.Rules[node.String()])
				case TypeAlternate, TypeUnorderedAlternate, TypeSequence,
					TypePeekFor, TypePeekNot, TypeQuery, TypeStar, TypePlus, TypePush:
					for element := node.Front(); element != nil; element = element.Next() {
						countRules(element)
					}
				}
			}
			for element := t.Front(); element != nil; element = element.Next() {
				node := element.Value.(Node)
				if node.GetType() == TypeRule {
					countRules(node)
					break
				}
			}
		},
		func() {
			var checkRecursion func(node Node) bool
			ruleReached := make([]bool, len(t.Rules))
			checkRecursion = func(node Node) bool {
				switch node.GetType() {
				case TypeRule:
					id := node.GetId()
					if ruleReached[id] {
						fmt.Fprintf(os.Stderr, "possible infinite left recursion in rule '%v'\n", node)
						return false
					}
					ruleReached[id] = true
					consumes := checkRecursion(node.Front())
					ruleReached[id] = false
					return consumes
//.........这里部分代码省略.........
开发者ID:taruti,项目名称:peg,代码行数:101,代码来源:peg.go


注:本文中的go/printer.Config.Fprint方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。