github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgGoSource/ContextDecl.go.bak (about)

     1  package kmgGoSource
     2  
     3  import (
     4  	"go/parser"
     5  	"go/token"
     6  	"os"
     7  	"path/filepath"
     8  	"reflect"
     9  	"strings"
    10  )
    11  
    12  //全局定义(包含所有的package)
    13  type ContextDecl struct {
    14  	PackageMap map[string]*PackageDecl
    15  }
    16  
    17  func (ctxt *ContextDecl) GetTypeDeclByReflectType(reflectType reflect.Type) (*TypeDecl, bool) {
    18  	reflectType = IndirectType(reflectType)
    19  	pkg, ok := ctxt.PackageMap[reflectType.PkgPath()]
    20  	if !ok {
    21  		return nil, false
    22  	}
    23  	t, ok := pkg.TypeMap[reflectType.Name()]
    24  	if !ok {
    25  		return nil, false
    26  	}
    27  	return t, true
    28  }
    29  func (ctxt *ContextDecl) GetMethodDeclByReflectType(reflectType reflect.Type, methodName string) (*FuncDecl, bool) {
    30  	t, ok := ctxt.GetTypeDeclByReflectType(reflectType)
    31  	if !ok {
    32  		return nil, false
    33  	}
    34  	f, ok := t.Methods[methodName]
    35  	if !ok {
    36  		return nil, false
    37  	}
    38  	return f, true
    39  }
    40  
    41  func NewContextDeclFromSrcPath(root string) (*ContextDecl, error) {
    42  	decl := &ContextDecl{PackageMap: make(map[string]*PackageDecl)}
    43  	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
    44  		if !info.IsDir() {
    45  			return nil
    46  		}
    47  		if info.Name()[0] == '.' {
    48  			return filepath.SkipDir
    49  		}
    50  		fset := token.NewFileSet()
    51  		pkgs, err := parser.ParseDir(fset, path, nil, parser.ParseComments|parser.AllErrors)
    52  		if err != nil {
    53  			return err
    54  		}
    55  		pkg := pkgs[info.Name()]
    56  		if pkg == nil {
    57  			return nil
    58  		}
    59  		fullImportPath, err := filepath.Rel(root, path)
    60  		if err != nil {
    61  			return err
    62  		}
    63  		fullImportPath = strings.Replace(fullImportPath, "\\", "/", -1)
    64  		decl.PackageMap[fullImportPath] = NewPackageDeclFromAstPackage(pkg, fullImportPath)
    65  		return nil
    66  	})
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	return decl, nil
    72  }