Exemple #1
0
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")
		}
	}
}
Exemple #2
0
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!")
}
Exemple #3
0
func getChildPkgs(ctx *cli.Context, cpath string, ppkg *doc.Pkg, cachePkgs map[string]*doc.Pkg, isTest bool) error {
	log.Trace("Current Path: 1 %s", cpath)
	pkgs, err := getGopmPkgs(cpath, isTest)
	if err != nil {
		return errors.New("Fail to get gopmfile deps: " + err.Error())
	}
	for name, pkg := range pkgs {
		pkg.RootPath = doc.GetProjectPath(pkg.ImportPath)
		if !pkgInCache(pkg.RootPath, cachePkgs) {
			var newPath string
			if !build.IsLocalImport(name) && pkg.Type != doc.LOCAL {
				suf := versionSuffix(pkg.Value)
				pkgPath := strings.Replace(
					pkg.ImportPath, pkg.RootPath, pkg.RootPath+suf, 1)
				newPath = filepath.Join(installRepoPath, pkgPath)
				if len(suf) == 0 && !ctx.Bool("remote") &&
					com.IsDir(filepath.Join(installGopath, pkgPath)) {
					newPath = filepath.Join(installGopath, pkgPath)
				}
				if pkgName != "" && strings.HasPrefix(pkg.ImportPath, pkgName) {
					newPath = filepath.Join(curPath, strings.TrimPrefix(pkg.ImportPath, pkgName))
				} else {
					if !com.IsExist(newPath) || ctx.Bool("update") {
						node := doc.NewNode(pkg.ImportPath, pkg.ImportPath,
							pkg.Type, pkg.Value, true)
						nodes := []*doc.Node{node}
						downloadPackages(ctx, nodes)
						// TODO: Should handler download failed
					}
				}
			} else {
				if pkg.Type == doc.LOCAL {
					newPath, err = filepath.Abs(pkg.Value)
				} else {
					newPath, err = filepath.Abs(name)
				}
				if err != nil {
					return err
				}
			}
			cachePkgs[pkg.RootPath] = pkg
			err = getChildPkgs(ctx, newPath, pkg, cachePkgs, false)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
Exemple #4
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!")
}
Exemple #5
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())
	}
}
Exemple #6
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!")
}
Exemple #7
0
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!")
}
Exemple #8
0
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)
}
Exemple #9
0
// downloadPackages downloads packages with certain commit,
// if the commit is empty string, then it downloads all dependencies,
// otherwise, it only downloada package with specific commit only.
func downloadPackages(ctx *cli.Context, nodes []*doc.Node) {
	// Check all packages, they may be raw packages path.
	for _, n := range nodes {
		// Check if local reference
		if n.Type == doc.LOCAL {
			continue
		}
		// Check if it is a valid remote path or C.
		if n.ImportPath == "C" {
			continue
		} else if !doc.IsValidRemotePath(n.ImportPath) {
			// Invalid import path.
			log.Error("download", "Skipped invalid package: "+fmt.Sprintf("%s@%s:%s",
				n.ImportPath, n.Type, doc.CheckNodeValue(n.Value)))
			failConut++
			continue
		}

		// Valid import path.
		gopathDir := path.Join(installGopath, n.ImportPath)
		n.RootPath = doc.GetProjectPath(n.ImportPath)
		installPath := path.Join(installRepoPath, n.RootPath) + versionSuffix(n.Value)

		if isSubpackage(n.RootPath, ".") {
			continue
		}

		// Indicates whether need to download package again.
		if n.IsFixed() && com.IsExist(installPath) {
			n.IsGetDepsOnly = true
		}

		if !ctx.Bool("update") {
			// Check if package has been downloaded.
			if (len(n.Value) == 0 && !ctx.Bool("remote") && com.IsExist(gopathDir)) ||
				com.IsExist(installPath) {
				log.Trace("Skipped installed package: %s@%s:%s",
					n.ImportPath, n.Type, doc.CheckNodeValue(n.Value))

				// Only copy when no version control.
				if ctx.Bool("gopath") && com.IsExist(installPath) ||
					len(getVcsName(gopathDir)) == 0 {
					copyToGopath(installPath, gopathDir)
				}
				continue
			} else {
				doc.LocalNodes.SetValue(n.RootPath, "value", "")
			}
		}

		if downloadCache[n.RootPath] {
			log.Trace("Skipped downloaded package: %s@%s:%s",
				n.ImportPath, n.Type, doc.CheckNodeValue(n.Value))
			continue
		}

		// Download package.
		nod, imports := downloadPackage(ctx, n)
		if len(imports) > 0 {
			var gf *goconfig.ConfigFile

			// Check if has gopmfile.
			if com.IsFile(installPath + "/" + doc.GOPM_FILE_NAME) {
				log.Log("Found gopmfile: %s@%s:%s",
					n.ImportPath, n.Type, doc.CheckNodeValue(n.Value))
				gf = doc.NewGopmfile(installPath)
			}

			// Need to download dependencies.
			// Generate temporary nodes.
			nodes := make([]*doc.Node, len(imports))
			for i := range nodes {
				nodes[i] = doc.NewNode(imports[i], imports[i], doc.BRANCH, "", true)

				if gf == nil {
					continue
				}

				// Check if user specified the version.
				if v, err := gf.GetValue("deps", imports[i]); err == nil && len(v) > 0 {
					nodes[i].Type, nodes[i].Value = validPath(v)
				}
			}
			downloadPackages(ctx, nodes)
		}

		// Only save package information with specific commit.
		if nod == nil {
			continue
		}

		// Save record in local nodes.
		log.Success("SUCC", "GET", fmt.Sprintf("%s@%s:%s",
			n.ImportPath, n.Type, doc.CheckNodeValue(n.Value)))
		downloadCount++

		// Only save non-commit node.
		if len(nod.Value) == 0 && len(nod.Revision) > 0 {
			doc.LocalNodes.SetValue(nod.RootPath, "value", nod.Revision)
		}

		if ctx.Bool("gopath") && com.IsExist(installPath) && !ctx.Bool("update") &&
			len(getVcsName(path.Join(installGopath, nod.RootPath))) == 0 {
			copyToGopath(installPath, gopathDir)
		}
	}
}
Exemple #10
0
func runUpdate(ctx *cli.Context) {
	doc.LoadPkgNameList(doc.HomeDir + "/data/pkgname.list")

	installRepoPath = doc.HomeDir + "/repos"

	// Check arguments.
	num := 0

	if len(ctx.Args()) != num {
		log.Error("Update", "Fail to start command")
		log.Fatal("", "Invalid argument number")
	}

	// Parse package version.
	info := "github.com/gpmgo/gopm"
	pkgPath := info
	ver := ""
	var err error
	if i := strings.Index(info, "@"); i > -1 {
		pkgPath = info[:i]
		_, ver = validPath(info[i+1:])
	}

	// Check package name.
	if !strings.Contains(pkgPath, "/") {
		name, ok := doc.PackageNameList[pkgPath]
		if !ok {
			log.Error("Update", "Invalid package name: "+pkgPath)
			log.Fatal("", "No match in the package name list")
		}
		pkgPath = name
	}

	// Get code.
	stdout, _, _ := com.ExecCmd("gopm", "get", info)
	if len(stdout) > 0 {
		fmt.Print(stdout)
	}

	// Check if previous steps were successful.
	repoPath := installRepoPath + "/" + pkgPath
	if len(ver) > 0 {
		repoPath += "." + ver
	}
	if !com.IsDir(repoPath) {
		log.Error("Bin", "Fail to continue command")
		log.Fatal("", "Previous steps weren't successful")
	}

	wd, err := os.Getwd()
	if err != nil {
		log.Error("Bin", "Fail to get work directory")
		log.Fatal("", err.Error())
	}

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

	// Build application.
	stdout, _, _ = com.ExecCmd("gopm", "build")
	if len(stdout) > 0 {
		fmt.Print(stdout)
	}
	defer func() {
		// Clean files.
		os.RemoveAll(path.Join(repoPath, doc.VENDOR))
	}()

	// 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)
		}
	}

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

	binName := path.Base(pkgName)
	if runtime.GOOS == "windows" {
		binName += ".exe"
	}
	binPath := path.Join(doc.VENDOR, "src", pkgPath, binName)
	if !com.IsFile(binPath) {
		log.Error("Update", "Fail to continue command")
		log.Fatal("", "Previous steps weren't successful or the project does not contain main package")
	}

	movePath := exePath()
	fmt.Print(movePath)

	// Move binary to given directory.
	if runtime.GOOS != "windows" {
		err = os.Rename(binPath, movePath)
		if err != nil {
			log.Error("Update", "Fail to move binary")
			log.Fatal("", err.Error())
		}
		os.Chmod(movePath+"/"+binName, os.ModePerm)
	} else {
		batPath := filepath.Join(wd, "a.bat")
		f, err := os.Create(batPath)
		if err != nil {
			log.Error("Update", "Fail to generate bat file")
			log.Fatal("", err.Error())
		}
		f.WriteString(fmt.Sprintf(`ping -n 1 127.0.0.1>nul\ncopy "%v" "%v"\ndel "%v"\ndel "%v"`,
			binPath, movePath, binPath, batPath))
		f.Close()

		attr := &os.ProcAttr{
			Dir: wd,
			Env: os.Environ(),
			//Files: []*os.File{nil, nil, nil},
			Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
		}

		_, err = os.StartProcess(batPath, []string{"a.bat"}, attr)
		if err != nil {
			log.Error("Update", "Fail to start bat process")
			log.Fatal("", err.Error())
		}
	}

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

	log.Success("SUCC", "Update", "Command execute successfully!")
}