Exemplo n.º 1
0
func (command *GoTest) findRootPath(context *console.Context) (root string, err error) {
	if context.FlagSet().NArg() == 1 {
		command.moduleName = context.FlagSet().Arg(0)
	}
	if command.dir != "" {
		root = command.dir
		exist, err := kmgFile.FileExist(root)
		if err != nil {
			return "", err
		}
		if !exist {
			return "", fmt.Errorf("[GoTest] dir path:[%s] not found", root)
		}
		return root, nil
	}
	if command.moduleName != "" {
		//TODO 处理多个GOPATH的问题,从GOPATH里面找到这个模块
		root = filepath.Join(command.gopath, "src", command.moduleName)
		exist, err := kmgFile.FileExist(root)
		if err != nil {
			return "", err
		}
		if !exist {
			return "", fmt.Errorf("[GoTest] module name:[%s] not found", command.moduleName)
		}
		return root, nil
	}
	if root == "" {
		root, err = os.Getwd()
		if err != nil {
			return
		}
	}
	return
}
Exemplo n.º 2
0
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
}