本文整理汇总了Golang中go/printer.Config类的典型用法代码示例。如果您正苦于以下问题:Golang Config类的具体用法?Golang Config怎么用?Golang Config使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Config类的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
}
示例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)
}
示例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()
}
示例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)
}
}
}
}
}
示例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
}
示例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)
}
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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)
}
}
示例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
}
示例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
}
示例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)
}
}
示例15: Compile
//.........这里部分代码省略.........
_, eof, _, class = optimizeAlternates(n.Front())
case TypePlus, TypePush:
consumes, eof, peek, class = optimizeAlternates(n.Front())
case TypeAction, TypeNil:
class = new(characterClass)
}
return
}
for element := t.Front(); element != nil; element = element.Next() {
n := element.Value.(Node)
if n.GetType() == TypeRule {
optimizeAlternates(n.(*node))
break
}
}
}
out, error := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if error != nil {
fmt.Printf("%v: %v\n", file, error)
return
}
defer out.Close()
var buffer bytes.Buffer
defer func() {
fileSet := token.NewFileSet()
code, error := parser.ParseFile(fileSet, file, &buffer, parser.ParseComments)
if error != nil {
buffer.WriteTo(out)
fmt.Printf("%v: %v\n", file, error)
return
}
formatter := printer.Config{printer.TabIndent | printer.UseSpaces, 8}
_, error = formatter.Fprint(out, fileSet, code)
if error != nil {
buffer.WriteTo(out)
fmt.Printf("%v: %v\n", file, error)
return
}
}()
print := func(format string, a ...interface{}) { fmt.Fprintf(&buffer, format, a...) }
printSave := func(n uint) { print("\n position%d, tokenIndex%d := position, tokenIndex", n, n) }
printRestore := func(n uint) { print(" position, tokenIndex = position%d, tokenIndex%d", n, n) }
printTemplate := func(s string) {
if error := template.Must(template.New("peg").Parse(s)).Execute(&buffer, t); error != nil {
panic(error)
}
}
if t.HasActions = counts[TypeAction] > 0; t.HasActions {
bits := 0
for length := len(t.Actions); length != 0; length >>= 1 {
bits++
}
switch {
case bits < 8:
bits = 8
case bits < 16:
bits = 16
case bits < 32:
bits = 32
case bits < 64:
bits = 64