Exemplo n.º 1
0
func LoadPkgNameList(filePath string) {
	PackageNameList = make(map[string]string)

	// If file does not exist, simply ignore.
	if !com.IsFile(filePath) {
		return
	}

	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		log.Error("Package name list", "Fail to read file")
		log.Fatal("", err.Error())
	}

	pkgs := strings.Split(string(data), "\n")
	for i, line := range pkgs {
		infos := strings.Split(line, "=")
		if len(infos) != 2 {
			// Last item might be empty line.
			if i == len(pkgs)-1 {
				continue
			}
			log.Error("", "Fail to parse package name: "+line)
			log.Fatal("", "Invalid package name information")
		}
		PackageNameList[strings.TrimSpace(infos[0])] =
			strings.TrimSpace(infos[1])
	}
}
Exemplo n.º 2
0
Arquivo: build.go Projeto: jexwn/gopm
func buildBinary(ctx *cli.Context, args ...string) {
	genNewGoPath(ctx, false)

	log.Trace("Building...")

	cmdArgs := []string{"go", "build"}
	cmdArgs = append(cmdArgs, args...)
	err := execCmd(newGoPath, newCurPath, cmdArgs...)
	if err != nil {
		log.Error("build", "fail to build program:")
		log.Fatal("", "\t"+err.Error())
	}

	if isWindowsXP {
		fName := path.Base(pkgName)
		binName := fName + ".exe"
		os.Remove(binName)
		exePath := filepath.Join(curPath, doc.VENDOR, "src", pkgName, binName)
		if com.IsFile(exePath) {
			err = os.Rename(exePath, filepath.Join(curPath, binName))
			if err != nil {
				log.Error("build", "fail to move binary:")
				log.Fatal("", "\t"+err.Error())
			}
		} else {
			log.Warn("No binary generated")
		}
	}
}
Exemplo n.º 3
0
Arquivo: gen.go Projeto: nashtsai/gopm
// scan a directory and gen a gopm file
func runGen(ctx *cli.Context) {
	setup(ctx)

	if !com.IsExist(".gopmfile") {
		os.Create(".gopmfile")
	}

	gf, err := goconfig.LoadConfigFile(".gopmfile")
	if err != nil {
		log.Error("gen", "Cannot load gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	// Get dependencies.
	imports := doc.GetAllImports([]string{workDir},
		parseTarget(gf.MustValue("target", "path")), ctx.Bool("example"))

	for _, p := range imports {
		p = doc.GetProjectPath(p)
		if strings.HasSuffix(workDir, p) {
			continue
		}
		if value := gf.MustValue("deps", p); len(value) == 0 {
			gf.SetValue("deps", p, "")
		}
	}

	err = goconfig.SaveConfigFile(gf, ".gopmfile")
	if err != nil {
		log.Error("gen", "Fail to save gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Success("SUCC", "gen", "Generate gopmfile successfully!")
}
Exemplo n.º 4
0
func init() {
	hd, err := com.HomeDir()
	if err != nil {
		log.Error("", "Fail to get current user")
		log.Fatal("", err.Error())
	}

	HomeDir = strings.Replace(RawHomeDir, "~", hd, -1)

	cfgPath := path.Join(HomeDir, GOPM_CONFIG_FILE)
	if !com.IsExist(cfgPath) {
		os.MkdirAll(path.Dir(cfgPath), os.ModePerm)
		if _, err = os.Create(cfgPath); err != nil {
			log.Error("", "Fail to create gopm config file")
			log.Fatal("", err.Error())
		}
	}
	Cfg, err = goconfig.LoadConfigFile(cfgPath)
	if err != nil {
		log.Error("", "Fail to load gopm config file")
		log.Fatal("", err.Error())
	}

	LoadLocalNodes()
	LoadPkgNameList(path.Join(HomeDir, PKG_NAME_LIST_PATH))
}
Exemplo n.º 5
0
func execCmd(gopath, curPath string, args ...string) error {
	cwd, err := os.Getwd()
	if err != nil {
		log.Error("", "Fail to get work directory:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Log("Changing work directory to %s", curPath)
	err = os.Chdir(curPath)
	if err != nil {
		log.Error("", "Fail to change work directory:")
		log.Fatal("", "\t"+err.Error())
	}
	defer func() {
		log.Log("Changing work directory back to %s", cwd)
		os.Chdir(cwd)
	}()

	err = os.Chdir(curPath)
	if err != nil {
		log.Error("", "Fail to change work directory:")
		log.Fatal("", "\t"+err.Error())
	}

	oldGoPath = os.Getenv("GOPATH")
	log.Log("Setting GOPATH to %s", gopath)

	sep := ":"
	if runtime.GOOS == "windows" {
		sep = ";"
	}
	err = os.Setenv("GOPATH", gopath+sep+oldGoPath)
	if err != nil {
		log.Error("", "Fail to setting GOPATH:")
		log.Fatal("", "\t"+err.Error())
	}
	defer func() {
		log.Log("Setting GOPATH back to %s", oldGoPath)
		os.Setenv("GOPATH", oldGoPath)
	}()

	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	log.Log("===== application outputs start =====\n")

	err = cmd.Run()

	log.Log("====== application outputs end ======")
	return err
}
Exemplo n.º 6
0
func exePath() string {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		log.Error("Update", "Fail to execute exec.LookPath")
		log.Fatal("", err.Error())
	}
	path, err := filepath.Abs(file)
	if err != nil {
		log.Error("Update", "Fail to get absolutely path")
		log.Fatal("", err.Error())
	}
	return path
}
Exemplo n.º 7
0
// GetImports returns package denpendencies.
func GetImports(absPath, importPath string, example bool) []string {
	pkg, err := build.ImportDir(absPath, build.AllowBinary)
	if err != nil {
		if _, ok := err.(*build.NoGoError); !ok {
			log.Error("", "Fail to get imports")
			log.Fatal("", err.Error())
		}
	}

	fis := GetDirsInfo(absPath)
	absPath += "/"

	dirs := make([]string, 0)
	for _, fi := range fis {
		if fi.IsDir() && !strings.Contains(fi.Name(), VENDOR) {
			dirs = append(dirs, absPath+fi.Name())
		}
	}

	imports := make([]string, 0, len(pkg.Imports))
	for _, p := range pkg.Imports {
		if !IsGoRepoPath(p) && !strings.HasPrefix(p, importPath) {
			imports = append(imports, p)
		}
	}
	if len(dirs) > 0 {
		imports = append(imports, GetAllImports(dirs, importPath, example)...)
	}
	return imports
}
Exemplo n.º 8
0
// GetDirsInfo returns os.FileInfo of all sub-directories in root path.
func GetDirsInfo(rootPath string) []os.FileInfo {
	rootDir, err := os.Open(rootPath)
	if err != nil {
		log.Error("", "Fail to open directory")
		log.Fatal("", err.Error())
	}
	defer rootDir.Close()

	dirs, err := rootDir.Readdir(0)
	if err != nil {
		log.Error("", "Fail to read directory")
		log.Fatal("", err.Error())
	}

	return dirs
}
Exemplo n.º 9
0
// CheckIsExistWithVCS returns false if directory only has VCS folder,
// or doesn't exist.
func CheckIsExistWithVCS(path string) bool {
	// Check if directory exist.
	if !com.IsExist(path) {
		return false
	}

	// Check if only has VCS folder.
	dirs, err := GetDirsInfo(path)
	if err != nil {
		log.Error("", "Fail to get directory's information")
		log.Fatal("", err.Error())
	}

	if len(dirs) > 1 {
		return true
	} else if len(dirs) == 0 {
		return false
	}

	switch dirs[0].Name() {
	case ".git", ".hg", ".svn":
		return false
	}

	return true
}
Exemplo n.º 10
0
Arquivo: run.go Projeto: nashtsai/gopm
func runRun(ctx *cli.Context) {
	setup(ctx)

	// Get GOPATH.
	installGopath = com.GetGOPATHs()[0]
	if com.IsDir(installGopath) {
		isHasGopath = true
		log.Log("Indicated GOPATH: %s", installGopath)
		installGopath += "/src"
	}

	genNewGoPath(ctx, false)

	log.Trace("Running...")

	cmdArgs := []string{"go", "run"}
	cmdArgs = append(cmdArgs, ctx.Args()...)
	err := execCmd(newGoPath, newCurPath, cmdArgs...)
	if err != nil {
		log.Error("run", "Fail to run program:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Success("SUCC", "run", "Command executed successfully!")
}
Exemplo n.º 11
0
Arquivo: gen.go Projeto: puma007/gopm
func runGen(ctx *cli.Context) {
	setup(ctx)

	if !com.IsExist(".gopmfile") {
		os.Create(".gopmfile")
	}

	gf, err := goconfig.LoadConfigFile(".gopmfile")
	if err != nil {
		log.Error("gen", "Cannot load gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	targetPath := parseTarget(gf.MustValue("target", "path"))
	// Get and set dependencies.
	imports := doc.GetAllImports([]string{workDir}, targetPath, ctx.Bool("example"), false)
	for _, p := range imports {
		p = doc.GetProjectPath(p)
		// Skip subpackage(s) of current project.
		if isSubpackage(p, targetPath) {
			continue
		}

		// Check if user specified the version.
		if value := gf.MustValue("deps", p); len(value) == 0 {
			gf.SetValue("deps", p, "")
		}
	}

	// Get and set resources.
	res := make([]string, 0, len(commonRes))
	for _, cr := range commonRes {
		if com.IsExist(cr) {
			res = append(res, cr)
		}
	}
	gf.SetValue("res", "include", strings.Join(res, "|"))

	err = goconfig.SaveConfigFile(gf, ".gopmfile")
	if err != nil {
		log.Error("gen", "Fail to save gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Success("SUCC", "gen", "Generate gopmfile successfully!")
}
Exemplo n.º 12
0
Arquivo: get.go Projeto: nashtsai/gopm
func copyToGopath(srcPath, destPath string) {
	os.RemoveAll(destPath)
	err := com.CopyDir(srcPath, destPath)
	if err != nil {
		log.Error("download", "Fail to copy to GOPATH:")
		log.Fatal("", "\t"+err.Error())
	}
}
Exemplo n.º 13
0
func GetPkgFullPath(short string) string {
	name, ok := PackageNameList[short]
	if !ok {
		log.Error("", "Invalid package name")
		log.Error("", "It's not a invalid import path and no match in the package name list:")
		log.Fatal("", "\t"+short)
	}
	return name
}
Exemplo n.º 14
0
// NewGopmfile loads gopmgile in given directory.
func NewGopmfile(dirPath string) *goconfig.ConfigFile {
	dirPath, _ = filepath.Abs(dirPath)
	gf, err := goconfig.LoadConfigFile(path.Join(dirPath, GOPM_FILE_NAME))
	if err != nil {
		log.Error("", "Fail to load gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}
	return gf
}
Exemplo n.º 15
0
func loadLocalVerInfo() (ver version) {
	verPath := path.Join(doc.HomeDir, doc.VER_PATH)

	// First time run should not exist.
	if !com.IsExist(verPath) {
		return ver
	}

	f, err := os.Open(verPath)
	if err != nil {
		log.Error("Update", "Fail to open VERSION.json")
		log.Fatal("", err.Error())
	}

	if err := json.NewDecoder(f).Decode(&ver); err != nil {
		log.Error("Update", "Fail to decode VERSION.json")
		log.Fatal("", err.Error())
	}
	return ver
}
Exemplo n.º 16
0
// setup initialize common environment for commands.
func setup(ctx *cli.Context) {
	var err error
	workDir, err = os.Getwd()
	if err != nil {
		log.Error("setup", "Fail to get work directory:")
		log.Fatal("", "\t"+err.Error())
	}

	log.PureMode = ctx.GlobalBool("noterm")
	log.Verbose = ctx.Bool("verbose")
}
Exemplo n.º 17
0
func init() {
	hd, err := com.HomeDir()
	if err != nil {
		log.Error("", "Fail to get current user")
		log.Fatal("", err.Error())
	}

	HomeDir = strings.Replace(RawHomeDir, "~", hd, -1)

	LoadLocalNodes()
	LoadPkgNameList(HomeDir + "/data/pkgname.list")
}
Exemplo n.º 18
0
Arquivo: config.go Projeto: jexwn/gopm
func runConfig(ctx *cli.Context) {
	setup(ctx)

	if len(ctx.Args()) == 0 {
		log.Error("config", "Cannot start command:")
		log.Fatal("", "\tNo section specified")
	}

	switch ctx.Args()[0] {
	case "github":
		if len(ctx.Args()) < 3 {
			log.Error("config", "Cannot config section 'github'")
			log.Fatal("", "\tNot enough arguments for client_id and client_secret")
		}
		doc.Cfg.SetValue("github", "client_id", ctx.Args()[1])
		doc.Cfg.SetValue("github", "client_secret", ctx.Args()[2])
		goconfig.SaveConfigFile(doc.Cfg, path.Join(doc.HomeDir, doc.GOPM_CONFIG_FILE))
	}

	log.Success("SUCC", "config", "Command executed successfully!")
}
Exemplo n.º 19
0
func updateByVcs(vcs, dirPath string) error {
	err := os.Chdir(dirPath)
	if err != nil {
		log.Error("Update by VCS", "Fail to change work directory:")
		log.Fatal("", "\t"+err.Error())
	}
	defer os.Chdir(workDir)

	switch vcs {
	case "git":
		stdout, _, err := com.ExecCmd("git", "status")
		if err != nil {
			log.Error("", "Error occurs when 'git status'")
			log.Error("", "\t"+err.Error())
		}

		i := strings.Index(stdout, "\n")
		if i == -1 {
			log.Error("", "Empty result for 'git status'")
			return nil
		}

		branch := strings.TrimPrefix(stdout[:i], "# On branch ")
		_, _, err = com.ExecCmd("git", "pull", "origin", branch)
		if err != nil {
			log.Error("", "Error occurs when 'git pull origin "+branch+"'")
			log.Error("", "\t"+err.Error())
		}
	case "hg":
		_, stderr, err := com.ExecCmd("hg", "pull")
		if err != nil {
			log.Error("", "Error occurs when 'hg pull'")
			log.Error("", "\t"+err.Error())
		}
		if len(stderr) > 0 {
			log.Error("", "Error: "+stderr)
		}

		_, stderr, err = com.ExecCmd("hg", "up")
		if err != nil {
			log.Error("", "Error occurs when 'hg up'")
			log.Error("", "\t"+err.Error())
		}
		if len(stderr) > 0 {
			log.Error("", "Error: "+stderr)
		}
	case "svn":
		log.Error("", "Error: not support svn yet")
	}
	return nil
}
Exemplo n.º 20
0
Arquivo: get.go Projeto: jexwn/gopm
func updateByVcs(vcs, dirPath string) error {
	err := os.Chdir(dirPath)
	if err != nil {
		log.Error("Update by VCS", "Fail to change work directory:")
		log.Fatal("", "\t"+err.Error())
	}
	defer os.Chdir(workDir)

	switch vcs {
	case "git":
		branch, _, err := com.ExecCmd("git", "rev-parse", "--abbrev-ref", "HEAD")
		if err != nil {
			log.Error("", "Error occurs when 'git rev-parse --abbrev-ref HEAD'")
			log.Error("", "\t"+err.Error())
		}

		_, _, err = com.ExecCmd("git", "pull", "origin", branch)
		if err != nil {
			log.Error("", "Error occurs when 'git pull origin "+branch+"'")
			log.Error("", "\t"+err.Error())
		}
	case "hg":
		_, stderr, err := com.ExecCmd("hg", "pull")
		if err != nil {
			log.Error("", "Error occurs when 'hg pull'")
			log.Error("", "\t"+err.Error())
		}
		if len(stderr) > 0 {
			log.Error("", "Error: "+stderr)
		}

		_, stderr, err = com.ExecCmd("hg", "up")
		if err != nil {
			log.Error("", "Error occurs when 'hg up'")
			log.Error("", "\t"+err.Error())
		}
		if len(stderr) > 0 {
			log.Error("", "Error: "+stderr)
		}
	case "svn":
		_, stderr, err := com.ExecCmd("svn", "update")
		if err != nil {
			log.Error("", "Error occurs when 'svn update'")
			log.Error("", "\t"+err.Error())
		}
		if len(stderr) > 0 {
			log.Error("", "Error: "+stderr)
		}
	}
	return nil
}
Exemplo n.º 21
0
func getGopmPkgs(dirPath string, isTest bool) (pkgs map[string]*doc.Pkg, err error) {
	absPath, err := filepath.Abs(dirPath)
	if err != nil {
		log.Error("", "Fail to get absolute path of work directory:")
		log.Fatal("", "\t"+err.Error())
	}

	var builds map[string]string

	if com.IsFile(absPath + "/" + doc.GOPM_FILE_NAME) {
		gf := doc.NewGopmfile(absPath)

		if builds, err = gf.GetSection("deps"); err != nil {
			builds = nil
		}
	}

	imports := doc.GetAllImports([]string{dirPath}, ".", false, false)
	pkgs = make(map[string]*doc.Pkg)
	for _, name := range imports {
		if name == "C" {
			continue
		}
		if !doc.IsGoRepoPath(name) {
			if builds != nil {
				if info, ok := builds[name]; ok {
					// Check version. there should chek
					// local first because d:\ contains :
					if com.IsDir(info) {
						pkgs[name] = &doc.Pkg{
							ImportPath: name,
							Type:       doc.LOCAL,
							Value:      info,
						}
						continue
					} else if i := strings.Index(info, ":"); i > -1 {
						pkgs[name] = &doc.Pkg{
							ImportPath: name,
							Type:       info[:i],
							Value:      info[i+1:],
						}
						continue
					}
				}
			}
			pkgs[name] = doc.NewDefaultPkg(name)
		}
	}
	return pkgs, nil
}
Exemplo n.º 22
0
func runTest(ctx *cli.Context) {
	genNewGoPath(ctx, true)

	log.Trace("Testing...")

	cmdArgs := []string{"go", "test"}
	cmdArgs = append(cmdArgs, ctx.Args()...)
	err := execCmd(newGoPath, newCurPath, cmdArgs...)
	if err != nil {
		log.Error("Test", "Fail to test program")
		log.Fatal("", err.Error())
	}

	log.Success("SUCC", "Test", "Command execute successfully!")
}
Exemplo n.º 23
0
func copyToGopath(srcPath, destPath string) {
	importPath := strings.TrimPrefix(destPath, installGopath+"/")
	if len(getVcsName(destPath)) > 0 {
		log.Warn("Package in GOPATH has version control: %s", importPath)
		return
	}

	os.RemoveAll(destPath)
	err := com.CopyDir(srcPath, destPath)
	if err != nil {
		log.Error("download", "Fail to copy to GOPATH:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Log("Package copied to GOPATH: %s", importPath)
}
Exemplo n.º 24
0
func LoadLocalNodes() {
	if !com.IsDir(HomeDir + "/data") {
		os.MkdirAll(HomeDir+"/data", os.ModePerm)
	}

	if !com.IsFile(HomeDir + LocalNodesFile) {
		os.Create(HomeDir + LocalNodesFile)
	}

	var err error
	LocalNodes, err = goconfig.LoadConfigFile(path.Join(HomeDir + LocalNodesFile))
	if err != nil {
		log.Error("load node", "Fail to load localnodes.list")
		log.Fatal("", err.Error())
	}
}
Exemplo n.º 25
0
Arquivo: vcs.go Projeto: puma007/gopm
func getImports(rootPath string, match map[string]string, cmdFlags map[string]bool, nod *Node) (imports []string) {
	dirs, err := GetDirsInfo(rootPath)
	if err != nil {
		log.Error("", "Fail to get directory's information")
		log.Fatal("", err.Error())
	}

	for _, d := range dirs {
		if d.IsDir() && !(!cmdFlags["-e"] && strings.Contains(d.Name(), "example")) {
			absPath := rootPath + d.Name() + "/"
			importPkgs, err := CheckImports(absPath, match["importPath"], nod)
			if err != nil {
				return nil
			}
			imports = append(imports, importPkgs...)
		}
	}
	return imports
}
Exemplo n.º 26
0
Arquivo: bin.go Projeto: puma007/gopm
func runBin(ctx *cli.Context) {
	setup(ctx)

	if len(ctx.Args()) == 0 {
		log.Error("bin", "Cannot start command:")
		log.Fatal("", "\tNo package specified")
	}

	installRepoPath = doc.HomeDir + "/repos"
	log.Log("Local repository path: %s", installRepoPath)

	// Check arguments.
	num := 1
	if ctx.Bool("dir") {
		num = 2
	}
	if len(ctx.Args()) != num {
		log.Error("bin", "Cannot start command:")
		log.Fatal("", "\tMissing indicated path to build binary")
	}

	// Check if given directory exists.
	if ctx.Bool("dir") && !com.IsDir(ctx.Args()[1]) {
		log.Error("bin", "Cannot start command:")
		log.Fatal("", "\tIndicated path does not exist or is not a directory")
	}

	// Parse package version.
	info := ctx.Args()[0]
	pkgPath := info
	node := doc.NewNode(pkgPath, pkgPath, doc.BRANCH, "", true)
	var err error
	if i := strings.Index(info, "@"); i > -1 {
		pkgPath = info[:i]
		node.ImportPath = pkgPath
		node.DownloadURL = pkgPath
		node.Type, node.Value = validPath(info[i+1:])
	}

	// Check package name.
	if !strings.Contains(pkgPath, "/") {
		pkgPath = doc.GetPkgFullPath(pkgPath)
	}

	// Get code.
	downloadPackages(ctx, []*doc.Node{node})

	// Check if previous steps were successful.
	repoPath := installRepoPath + "/" + pkgPath + versionSuffix(node.Value)
	if !com.IsDir(repoPath) {
		log.Error("bin", "Cannot continue command:")
		log.Fatal("", "\tPrevious steps weren't successful")
	}

	wd, err := os.Getwd()
	if err != nil {
		log.Error("bin", "Cannot get work directory:")
		log.Fatal("", "\t"+err.Error())
	}

	// Change to repository path.
	log.Log("Changing work directory to %s", repoPath)
	if err = os.Chdir(repoPath); err != nil {
		log.Error("bin", "Fail to change work directory:")
		log.Fatal("", "\t"+err.Error())
	}

	// Build application.
	buildBinary(ctx)
	defer func() {
		// Clean files.
		os.RemoveAll(path.Join(repoPath, doc.VENDOR))
	}()

	includes := make([]string, 0, 3)
	// Check if previous steps were successful.
	if com.IsFile(doc.GOPM_FILE_NAME) {
		log.Trace("Loading gopmfile...")
		gf := doc.NewGopmfile(".")

		var err error
		pkgName, err = gf.GetValue("target", "path")
		if err == nil {
			log.Log("Target name: %s", pkgName)
		}

		includes = strings.Split(gf.MustValue("res", "include"), "|")
	}

	if len(pkgName) == 0 {
		_, pkgName = filepath.Split(pkgPath)
	}

	// Because build command moved binary to root path.
	binName := path.Base(pkgName)
	if runtime.GOOS == "windows" {
		binName += ".exe"
	}
	if !com.IsFile(binName) {
		log.Error("bin", "Binary does not exist:")
		log.Error("", "\t"+binName)
		log.Fatal("", "\tPrevious steps weren't successful or the project does not contain main package")
	}

	// Move binary to given directory.
	movePath := wd
	if ctx.Bool("dir") {
		movePath = ctx.Args()[1]
	}

	if com.IsExist(movePath + "/" + binName) {
		if err = os.Remove(movePath + "/" + binName); err != nil {
			log.Warn("Cannot remove binary in work directory:")
			log.Warn("\t %s", err)
		}
	}

	if err = os.Rename(binName, movePath+"/"+binName); err != nil {
		log.Error("bin", "Fail to move binary:")
		log.Fatal("", "\t"+err.Error())
	}
	os.Chmod(movePath+"/"+binName, os.ModePerm)

	if len(includes) > 0 {
		log.Log("Copying resources to %s", movePath)
		for _, include := range includes {
			if com.IsDir(include) {
				if err = com.CopyDir(include, filepath.Join(movePath, include)); err != nil {
					log.Error("bin", "Fail to copy following resource:")
					log.Error("", "\t"+include)
				}
			}
		}
	}

	log.Log("Changing work directory back to %s", wd)
	os.Chdir(wd)

	log.Success("SUCC", "bin", "Command executed successfully!")
	fmt.Println("Binary has been built into: " + movePath)
}
Exemplo n.º 27
0
func genNewGoPath(ctx *cli.Context, isTest bool) {
	var err error
	curPath, err = os.Getwd()
	if err != nil {
		log.Error("", "Fail to get work directory:")
		log.Fatal("", "\t"+err.Error())
	}
	log.Trace("Current Path: 0 %s", curPath)

	installRepoPath = doc.HomeDir + "/repos"

	if com.IsFile(curPath + "/" + doc.GOPM_FILE_NAME) {
		log.Trace("Loading gopmfile...")
		gf := doc.NewGopmfile(curPath)

		var err error
		pkgName, err = gf.GetValue("target", "path")
		if err == nil {
			log.Log("Target name: %s", pkgName)
		}
	}

	if len(pkgName) == 0 {
		_, pkgName = filepath.Split(curPath)
	}

	cachePkgs := make(map[string]*doc.Pkg)
	if err = getChildPkgs(ctx, curPath, nil, cachePkgs, isTest); err != nil {
		log.Error("", "Fail to get child pakcages:")
		log.Fatal("", "\t"+err.Error())
	}

	newGoPath = filepath.Join(curPath, doc.VENDOR)
	newGoPathSrc := filepath.Join(newGoPath, "src")
	os.RemoveAll(newGoPathSrc)
	os.MkdirAll(newGoPathSrc, os.ModePerm)

	for name, pkg := range cachePkgs {
		suf := versionSuffix(pkg.Value)

		var oldPath string
		if pkg.Type == doc.LOCAL {
			oldPath, _ = filepath.Abs(pkg.Value)
		} else {
			oldPath = filepath.Join(installRepoPath, name) + suf
		}

		newPath := filepath.Join(newGoPathSrc, name)
		paths := strings.Split(name, "/")
		var isExistP, isCurChild bool
		if name == pkgName {
			continue
		}

		for i := 0; i < len(paths)-1; i++ {
			pName := strings.Join(paths[:len(paths)-1-i], "/")
			if _, ok := cachePkgs[pName]; ok {
				isExistP = true
				break
			}
			if pkgName == pName {
				isCurChild = true
				break
			}
		}
		if isCurChild {
			continue
		}

		if !isExistP && (len(pkg.Value) > 0 || ctx.Bool("remote") ||
			!com.IsDir(filepath.Join(installGopath, pkg.ImportPath))) {
			log.Log("Linking %s", name+suf)
			err = autoLink(oldPath, newPath)
			if err != nil {
				log.Error("", "Fail to make link:")
				log.Fatal("", "\t"+err.Error())
			}
		}
	}

	newCurPath = filepath.Join(newGoPathSrc, pkgName)
	log.Log("Linking %s", pkgName)
	err = autoLink(curPath, newCurPath)
	if err != nil {
		log.Error("", "Fail to make link:")
		log.Fatal("", "\t"+err.Error())
	}
}
Exemplo n.º 28
0
func runInstall(ctx *cli.Context) {
	setup(ctx)

	var target string
	switch len(ctx.Args()) {
	case 0:
		if !com.IsFile(".gopmfile") {
			break
		}

		gf := doc.NewGopmfile(".")
		target = gf.MustValue("target", "path")
	case 1:
		target = ctx.Args()[0]
	default:
		log.Fatal("install", "Too many arguments")
	}

	// Get GOPATH.
	installGopath = com.GetGOPATHs()[0]
	if com.IsDir(installGopath) {
		isHasGopath = true
		log.Log("Indicated GOPATH: %s", installGopath)
		installGopath += "/src"
	} else {
		if ctx.Bool("gopath") {
			log.Error("get", "Invalid GOPATH path")
			log.Error("", "GOPATH does not exist or is not a directory:")
			log.Error("", "\t"+installGopath)
			log.Help("Try 'go help gopath' to get more information")
		} else {
			// It's OK that no GOPATH setting
			// when user does not specify to use.
			log.Warn("No GOPATH setting available")
		}
	}

	genNewGoPath(ctx, false)

	var installRepos []string
	if ctx.Bool("pkg") {
		curPath, _ := filepath.Abs(".")
		installRepos = doc.GetAllImports([]string{curPath},
			".", ctx.Bool("example"))
	} else {
		if len(target) == 0 {
			target = pkgName
		}

		installRepos = []string{target}
	}

	log.Trace("Installing...")

	for _, repo := range installRepos {
		cmdArgs := []string{"go", "install"}

		if ctx.Bool("verbose") {
			cmdArgs = append(cmdArgs, "-v")
		}
		cmdArgs = append(cmdArgs, repo)
		err := execCmd(newGoPath, newCurPath, cmdArgs...)
		if err != nil {
			log.Error("install", "Fail to install program:")
			log.Fatal("", "\t"+err.Error())
		}
	}

	log.Success("SUCC", "install", "Command executed successfully!")
}
Exemplo n.º 29
0
func runExec(ctx *cli.Context) {
	setup(ctx)

	if len(ctx.Args()) == 0 {
		log.Error("exec", "Cannot start command:")
		log.Fatal("", "\tNo package specified")
	}

	installRepoPath = doc.HomeDir + "/repos"
	log.Log("Local repository path: %s", installRepoPath)

	// Parse package version.
	info := ctx.Args()[0]
	pkgPath := info
	node := doc.NewNode(pkgPath, pkgPath, doc.BRANCH, "", true)
	if i := strings.Index(info, "@"); i > -1 {
		// Specify version by argument.
		pkgPath = info[:i]
		node.Type, node.Value = validPath(info[i+1:])
	}

	// Check package name.
	if !strings.Contains(pkgPath, "/") {
		pkgPath = doc.GetPkgFullPath(pkgPath)
	}

	node.ImportPath = pkgPath
	node.DownloadURL = pkgPath

	if len(node.Value) == 0 && com.IsFile(".gopmfile") {
		// Specify version by gopmfile.
		gf := doc.NewGopmfile(".")
		info, err := gf.GetValue("exec", pkgPath)
		if err == nil && len(info) > 0 {
			node.Type, node.Value = validPath(info)
		}
	}

	// Check if binary exists.
	binPath := path.Join(doc.HomeDir, "bins", node.ImportPath, path.Base(node.ImportPath)+versionSuffix(node.Value))
	log.Log("Binary path: %s", binPath)

	if !com.IsFile(binPath) {
		// Calling bin command.
		args := []string{"bin", "-d"}
		if ctx.Bool("verbose") {
			args = append(args, "-v")
		}
		if ctx.Bool("update") {
			args = append(args, "-u")
		}
		args = append(args, node.ImportPath+"@"+node.Type+":"+node.Value)
		args = append(args, path.Dir(binPath))
		stdout, stderr, err := com.ExecCmd("gopm", args...)
		if err != nil {
			log.Error("exec", "Building binary failed:")
			log.Fatal("", "\t"+err.Error())
		}
		if len(stderr) > 0 {
			fmt.Print(stderr)
		}
		if len(stdout) > 0 {
			fmt.Print(stdout)
		}
	}
	fmt.Printf("%+v\n", node)

	return
	stdout, stderr, err := com.ExecCmd(binPath, ctx.Args()[1:]...)
	if err != nil {
		log.Error("exec", "Calling binary failed:")
		log.Fatal("", "\t"+err.Error())
	}
	if len(stderr) > 0 {
		fmt.Print(stderr)
	}
	if len(stdout) > 0 {
		fmt.Print(stdout)
	}
}
Exemplo n.º 30
0
Arquivo: run.go Projeto: kulasama/gopm
func runRun(ctx *cli.Context) {
	setup(ctx)
	//support unix only
	if ctx.Bool("local") {
		var localPath string
		var err error
		var wd string
		var gf *goconfig.ConfigFile
		wd, _ = os.Getwd()
		for wd != "/" {
			gf, _ = goconfig.LoadConfigFile(".gopmfile")
			if gf != nil {
				localPath = gf.MustValue("project", "localPath")
			}
			if localPath != "" {
				break
			}
			os.Chdir("..")
			wd, _ = os.Getwd()
		}
		if wd == "/" {
			log.Fatal("run", "no gopmfile in the directory or parent directory")
		}
		argss := gf.MustValue("run", "cmd")
		if localPath == "" {
			log.Fatal("run", "No localPath set")
		}
		args := strings.Split(argss, " ")
		argsLen := len(args)
		for i := 0; i < argsLen; i++ {
			strings.Trim(args[i], " ")
		}
		if len(args) < 2 {
			log.Fatal("run", "cmd arguments less than 2")
		}
		err = execCmd(localPath, localPath, args...)
		if err != nil {
			log.Error("run", "Fail to run program:")
			log.Fatal("", "\t"+err.Error())
		}
		return
	}
	// Get GOPATH.
	installGopath = com.GetGOPATHs()[0]
	if com.IsDir(installGopath) {
		isHasGopath = true
		log.Log("Indicated GOPATH: %s", installGopath)
		installGopath += "/src"
	}
	// run command with gopm repos context
	// need version control , auto link to GOPATH/src repos
	genNewGoPath(ctx, false)
	defer os.RemoveAll(doc.VENDOR)

	log.Trace("Running...")

	cmdArgs := []string{"go", "run"}
	cmdArgs = append(cmdArgs, ctx.Args()...)
	err := execCmd(newGoPath, newCurPath, cmdArgs...)
	if err != nil {
		log.Error("run", "Fail to run program:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Success("SUCC", "run", "Command executed successfully!")
}