예제 #1
0
func (rp *rewritePackage) determineImportPath(filePath string) (string, error) {
	dirName := filepath.Dir(filePath)
	if rp.options.RootPathFlag == "" {
		rp.Println("i18n4go: using the PWD as the rootPath:", os.Getenv("PWD"))
		rp.RootPath = os.Getenv("PWD")
	}
	rp.Println("i18n4go: determining import path using root path:", rp.RootPath)
	pkg, err := build.Default.ImportDir(rp.RootPath, build.ImportMode(1))
	if err != nil {
		rp.Println("i18n4go: error getting root path import:", err.Error)
		return "", err
	}
	rp.Println("i18n4go: got a root pkg with import path:", pkg.ImportPath)

	otherPkg, err := build.Default.ImportDir(dirName, build.ImportMode(0))
	if err != nil {
		rp.Println("i18n4go: error getting root path import:", err.Error)
		return "", err
	}
	rp.Println("i18n4go: got a pkg with import:", otherPkg.ImportPath)

	importPath := otherPkg.ImportPath
	importPath = strings.Replace(importPath, pkg.ImportPath, "", 1)
	if strings.HasPrefix(importPath, "/") {
		importPath = strings.TrimLeft(importPath, "/")
	}
	rp.Println("i18n4go: using import path as:", importPath)

	return importPath, nil
}
/*
 * Attempts to return a package with its test files already read.
 * The ImportMode arg to build.Import lets you specify if you want go to read the
 * buildable go files inside the package, but it fails if the package has no go files
 */
func packageWithName(name string) (pkg *build.Package, err error) {
	pkg, err = build.Default.Import(name, ".", build.ImportMode(0))
	if err == nil {
		return
	}

	pkg, err = build.Default.Import(name, ".", build.ImportMode(1))
	return
}
예제 #3
0
// findPackageName reads all the go packages in the curent directory
// and finds which package they are in
func findPackageName() string {
	p, err := build.Default.Import(".", ".", build.ImportMode(0))
	if err != nil {
		fatalf("Failed to read packages in current directory: %v", err)
	}
	return p.Name
}
예제 #4
0
파일: helper.go 프로젝트: pombredanne/dep
func (ø *subPackages) Walker(path string, info os.FileInfo, err error) error {
	if err != nil {
		return err
	}
	if info.IsDir() {
		pPath := ø.env.PkgPath(path)
		if ø.env.Skip(pPath) {
			return filepath.SkipDir
		}
		if VERBOSE {
			fmt.Printf("walk: %s\n", path)
		}
		pkg, buildErr := ø.env.Build().ImportDir(path, build.ImportMode(0))

		if buildErr != nil && fmt.Sprintf("%T", buildErr) == "*build.NoGoError" {
			return nil
		}

		if buildErr != nil { // && VERBOSE {
			fmt.Printf("error for package %s: %s (%T)\n", path, buildErr.Error(), buildErr)
		}
		if buildErr == nil && pkg != nil {
			ø.packages[pPath] = true
			return nil
		}
		return buildErr
	}
	return nil
}
예제 #5
0
func generate(dir, pkg string) {
	p, err := build.Default.Import(templateDir, dir, build.ImportMode(0))
	if err != nil {
		log.Fatalf("Import %s failed: %s", templateDir, err)
	}

	if len(p.GoFiles) != 1 {
		log.Fatalf("Expecting only 1 go file in dir %s", templateDir)
	}

	templateFilePath := path.Join(p.Dir, p.GoFiles[0])
	fset, f := parseFile(templateFilePath)

	// Change the package to the local package name
	f.Name.Name = pkg

	newDecls := []ast.Decl{}
	for _, Decl := range f.Decls {
		keep := true
		switch d := Decl.(type) {
		case *ast.GenDecl:
			// A general definition
			switch d.Tok {
			case token.TYPE:
				for _, spec := range d.Specs {
					typeSpec := spec.(*ast.TypeSpec)
					keep = !strings.HasPrefix(typeSpec.Name.Name, "Replace")
				}
			}
		}
		if keep {
			newDecls = append(newDecls, Decl)
		}
	}

	// remove the declarations that start with "Replace"
	f.Decls = newDecls
	replaceIdentifier(f, "ReplaceKey", keyType)
	replaceIdentifier(f, "ReplaceValue", valueType)

	// rename ACache and aWrapper with the type specified
	typeName := strings.ToUpper(valueType[:1]) + valueType[1:]
	replaceIdentifier(f, "ACache", typeName+"Cache")
	replaceIdentifier(f, "NewACache", "New"+typeName+"Cache")
	wrapperName := strings.ToLower(valueType[:1]) + valueType[1:]
	replaceIdentifier(f, "aCache", wrapperName+"Cache")
	replaceIdentifier(f, "aWrapper", wrapperName+"Wrapper")
	replaceIdentifier(f, "stopACacheCleanup", "stop"+typeName+"CacheCleanup")

	// output the new file
	outputFileName := strings.ToLower(valueType) + "_cache.go"
	outputFile(fset, f, outputFileName)

	log.Printf("Wrote %q", outputFileName)
}
예제 #6
0
파일: GoTest.go 프로젝트: iizotop/kmg
func (command *GoTest) handlePath(path string) error {
	pkg, err := command.buildContext.ImportDir(path, build.ImportMode(0))
	if err != nil {
		//仅忽略 不是golang的目录的错误
		_, ok := err.(*build.NoGoError)
		if ok {
			return nil
		}
		return err
	}
	if pkg.IsCommand() {
		return nil
	}
	if command.onlyBuild || len(pkg.TestGoFiles) == 0 {
		//如果没有测试文件,还会尝试build一下这个目录
		return command.gobuild(path)
		//return nil
	}
	return command.gotest(path)
}
예제 #7
0
// Instantiate the template package
func (t *template) instantiate() {
	logf("Substituting %q with %s(%s) into package %s", t.Package, t.Name, strings.Join(t.Args, ","), t.NewPackage)

	p, err := build.Default.Import(t.Package, t.Dir, build.ImportMode(0))
	if err != nil {
		fatalf("Import %s failed: %s", t.Package, err)
	}
	//debugf("package = %#v", p)
	debugf("Dir = %#v", p.Dir)
	// FIXME CgoFiles ?
	debugf("Go files = %#v", p.GoFiles)

	if len(p.GoFiles) == 0 {
		fatalf("No go files found for package '%s'", t.Package)
	}
	// FIXME
	if len(p.GoFiles) != 1 {
		fatalf("Found more than one go file in '%s' - can only cope with 1 for the moment, sorry", t.Package)
	}

	templateFilePath := path.Join(p.Dir, p.GoFiles[0])
	t.parse(templateFilePath)
}
예제 #8
0
파일: importer.go 프로젝트: tcard/sgo
func (imp *importer) ImportFrom(path, srcDir string, mode types.ImportMode) (*types.Package, error) {
	if imported, ok := imp.imported[path]; ok {
		return imported, nil
	}

	if path == "unsafe" {
		gopkg, err := goimporter.Default().Import(path)
		if err != nil {
			return nil, err
		}
		conv := &converter{gopkg: gopkg}
		conv.convert()
		imp.imported[path] = conv.ret
		return conv.ret, nil
	}

	buildPkg, err := build.Import(path, srcDir, build.ImportMode(mode))
	if err != nil {
		return nil, err
	}
	fset := token.NewFileSet()

	var files []*ast.File
	for _, name := range buildPkg.GoFiles {
		path := filepath.Join(buildPkg.Dir, name)
		f, err := os.Open(path)
		if err != nil {
			return nil, err
		}
		a, err := parser.ParseFile(fset, name, f, parser.ParseComments)
		f.Close()
		if err != nil {
			return nil, err
		}
		files = append(files, a)
	}

	// 1. Typecheck without converting anything; ConvertAST needs to know
	//    which idents are types to perform the default conversions.

	info := &types.Info{
		Defs: map[*ast.Ident]types.Object{},
		Uses: map[*ast.Ident]types.Object{},
	}
	cfg := &types.Config{
		IgnoreFuncBodies:        true,
		IgnoreTopLevelVarValues: true,
		Importer:                imp.fromPkg(),
		AllowUninitializedExprs: true,
	}
	pkg, err := cfg.Check(path, fset, files, info)
	if err != nil {
		return nil, err
	}

	// 2. Convert AST, now using the doc comment annotations and fromPkg
	//    everything that hasn't been converted explicitly by then with the
	//    default conversion (wrapping in optionals).

	var ann *annotations.Annotation
	if a, ok := defaultAnnotations[path]; ok {
		ann = annotations.NewAnnotation(a)
	} else if a, ok := imp.sgovendored[path]; ok {
		ann, err = a()
		if err != nil {
			return nil, fmt.Errorf("reading SGo annotations for %s: %v", path, err)
		}
	}

	for _, f := range files {
		ConvertAST(f, info, ann)
	}

	// 3. Typecheck converted AST.

	pkg, err = cfg.Check(path, fset, files, &types.Info{})
	if err != nil {
		return nil, err
	}

	imp.imported[path] = pkg
	return pkg, nil
}
예제 #9
0
파일: GoAllImport.go 프로젝트: iizotop/kmg
func (command *GoAllImport) Execute(context *console.Context) (err error) {
	kmgc, err := kmgConfig.LoadEnvFromWd()
	if err != nil {
		return
	}
	command.gopath = kmgc.GOPATH[0]
	root := command.dir
	exist, err := kmgFile.FileExist(root)
	if err != nil {
		return
	}
	if !exist {
		return fmt.Errorf("[GoAllImport] dir path[%s] not exist", root)
	}
	c := &build.Context{
		GOPATH:   kmgc.GOPATHToString(),
		Compiler: build.Default.Compiler,
	}
	root, err = kmgFile.Realpath(root)
	if err != nil {
		return
	}
	moduleList := []string{}
	err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			return nil
		}
		if kmgFile.IsDotFile(path) {
			return filepath.SkipDir
		}
		pkg, err := c.ImportDir(path, build.ImportMode(0))
		if err != nil {
			//忽略异常文件夹,(不是golang的目录之类的)
			return nil
		}
		if pkg.IsCommand() {
			return nil
		}

		pkgFullName, err := filepath.Rel(command.gopath, path)
		if err != nil {
			return err
		}
		moduleList = append(moduleList, strings.TrimPrefix(filepath.ToSlash(pkgFullName), "src/"))
		return nil
	})
	if err != nil {
		return
	}
	tpl := template.Must(template.New("").Parse(`package {{.PackageName}}
import(
{{range .ModuleList}}	_ "{{.}}"
{{end}}
)
`))
	buf := &bytes.Buffer{}
	tpl.Execute(buf, struct {
		PackageName string
		ModuleList  []string
	}{
		PackageName: command.packageName,
		ModuleList:  moduleList,
	})
	fmt.Println(string(buf.Bytes()))
	return
}
예제 #10
0
파일: lib.go 프로젝트: go-stay/stay
func newpack(dir string) (pkg *pack, err error) {
	pkg = &pack{}
	pkg.fset = token.NewFileSet()
	pkg.buildPkg, err = build.ImportDir(dir, build.ImportMode(0))
	return
}