Beispiel #1
0
func (n *Node) DownloadByGit(ctx *cli.Context, u *url.URL) error {
	var remoteAddr string
	switch u.Scheme {
	case "git+ssh":
		remoteAddr = fmt.Sprintf("git@%s:%s.git", u.Host, u.Path)
	case "git+http":
		remoteAddr = fmt.Sprintf("http://%s/%s", u.Host, u.Path)
	case "git+https":
		remoteAddr = fmt.Sprintf("https://%s/%s", u.Host, u.Path)
	}
	baseDir := path.Dir(n.InstallPath)
	os.MkdirAll(baseDir, os.ModePerm)
	_, stderr, err := base.ExecCmdDir(baseDir, "git", "clone", remoteAddr, n.InstallPath)
	if err != nil {
		log.Error("Error occurs when 'git clone " + remoteAddr + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	if !n.IsEmptyVal() {
		base.ExecCmdDir(n.InstallPath, "git", "checkout", n.Value)
		if err != nil {
			log.Error("Error occurs when 'git checkout" + n.Value + "'")
			log.Error("\t" + stderr)
			return errors.New(stderr)
		}
	}
	return nil
}
Beispiel #2
0
func (n *Node) DownloadByGoGet(ctx *cli.Context, u *url.URL) error {
	baseDir := path.Join(setting.HomeDir, ".gopm/temp/goget")
	os.MkdirAll(baseDir, os.ModePerm)
	defer func() {
		os.RemoveAll(baseDir)
	}()

	oriGopath := os.Getenv("GOPATH")
	os.Setenv("GOPATH", baseDir)
	fmt.Println(baseDir)
	defer func() {
		os.Setenv("GOPATH", oriGopath)
	}()

	log.Debug("RUN 'go get %s'", n.RootPath)
	_, stderr, err := base.ExecCmdDir(baseDir, "go", "get", n.RootPath)
	if err != nil {
		log.Error("Error occurs when 'go get" + n.RootPath + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	tmpPath := path.Join(baseDir, "src", n.RootPath)
	if !n.IsEmptyVal() {
		base.ExecCmdDir(tmpPath, "git", "checkout", n.Value)
		if err != nil {
			log.Error("Error occurs when 'git checkout" + n.Value + "'")
			log.Error("\t" + stderr)
			return errors.New(stderr)
		}
	}
	os.MkdirAll(path.Dir(n.InstallPath), os.ModePerm)
	os.Rename(tmpPath, n.InstallPath)
	return nil
}
Beispiel #3
0
func execCmd(gopath, curPath string, args ...string) error {
	oldGopath := os.Getenv("GOPATH")
	log.Info("Setting GOPATH to %s", gopath)

	sep := ":"
	if runtime.GOOS == "windows" {
		sep = ";"
	}

	if err := os.Setenv("GOPATH", gopath+sep+oldGopath); err != nil {
		if setting.LibraryMode {
			return fmt.Errorf("Fail to setting GOPATH: %v", err)
		}
		log.Error("", "Fail to setting GOPATH:")
		log.Fatal("", "\t"+err.Error())
	}
	if setting.HasGOPATHSetting {
		defer func() {
			log.Info("Setting GOPATH back to %s", oldGopath)
			os.Setenv("GOPATH", oldGopath)
		}()
	}

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

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

	err := cmd.Run()

	log.Info("====== application outputs end ======")
	return err
}
Beispiel #4
0
// If vcs has been detected, use corresponding command to update package.
func (n *Node) UpdateByVcs(vcs string) error {
	switch vcs {
	case "git":
		branch, stderr, err := base.ExecCmdDir(n.InstallGopath,
			"git", "rev-parse", "--abbrev-ref", "HEAD")
		if err != nil {
			log.Error("", "Error occurs when 'git rev-parse --abbrev-ref HEAD'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
		branch = strings.TrimSpace(branch)

		_, stderr, err = base.ExecCmdDir(n.InstallGopath,
			"git", "pull", "origin", branch)
		if err != nil {
			log.Error("", "Error occurs when 'git pull origin "+branch+"'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
	case "hg":
		_, stderr, err := base.ExecCmdDir(n.InstallGopath,
			"hg", "pull")
		if err != nil {
			log.Error("", "Error occurs when 'hg pull'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}

		_, stderr, err = base.ExecCmdDir(n.InstallGopath,
			"hg", "up")
		if err != nil {
			log.Error("", "Error occurs when 'hg up'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
	case "svn":
		_, stderr, err := base.ExecCmdDir(n.InstallGopath,
			"svn", "update")
		if err != nil {
			log.Error("", "Error occurs when 'svn update'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
	}
	return nil
}
Beispiel #5
0
func main() {
	setting.LibraryMode = false
	if err := lib.Run(os.Args); err.HasError {
		if err.Fatal != nil {
			log.Fatal("%v", err.Fatal)
		}
		for _, e := range err.Errors {
			log.Error("%v", e)
		}
	}
}
Beispiel #6
0
func loadLocalVerInfo() (ver version) {
	verPath := path.Join(setting.HomeDir, ".gopm", setting.VERINFO)

	// First time run should not exist.
	if !base.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
}
Beispiel #7
0
func (n *Node) DownloadLocalRepository(ctx *cli.Context, localize *goconfig.Localize) error {
	var repoAddr string
	switch localize.Download {
	case "git+ssh":
		repoAddr = fmt.Sprintf("git@%s:%s.git", localize.Domain, n.RootPath[len(localize.Domain)+1:])
	case "git+https":
		repoAddr = fmt.Sprintf("https://%s", n.RootPath)
	case "git+http":
		repoAddr = fmt.Sprintf("http://%s", n.RootPath)
	}
	downBaseDir := path.Dir(path.Join(setting.HomeDir, ".gopm/repos", n.RootPath))
	os.MkdirAll(downBaseDir, os.ModePerm)
	_, stderr, err := base.ExecCmdDir(downBaseDir, "git", "clone", repoAddr)
	if err != nil {
		//log.Error("", "Error occurs when 'git clone'")
		//log.Error("", "\t"+stderr)
		log.Error("Error occurs when 'git checkout" + n.Value + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	return nil
}
Beispiel #8
0
func (t *transport) SetProxy(proxy string) error {
	if len(proxy) == 0 {
		return nil
	}

	proxyUrl, err := url.Parse(proxy)
	if err != nil {
		if setting.LibraryMode {
			return fmt.Errorf("Fail to set HTTP proxy: %v", err)
		}
		log.Error("", "Fail to set HTTP proxy:")
		log.Fatal("", "\t"+err.Error())
	}
	t.t.Proxy = http.ProxyURL(proxyUrl)
	return nil
}
Beispiel #9
0
func (n *Node) CopyToGopath() error {
	if n.HasVcs() {
		log.Warn("Package in GOPATH has version control: %s", n.RootPath)
		return nil
	}

	os.RemoveAll(n.InstallGopath)
	if err := base.CopyDir(n.InstallPath, n.InstallGopath); err != nil {
		if setting.LibraryMode {
			return fmt.Errorf("Fail to copy to GOPATH: %v", err)
		}
		log.Error("", "Fail to copy to GOPATH:")
		log.Fatal("", "\t"+err.Error())
	}
	log.Info("Package copied to GOPATH: %s", n.RootPath)
	return nil
}
Beispiel #10
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(target string, ctx *cli.Context, nodes []*doc.Node) (err error) {
	for _, n := range nodes {
		// Check if it is a valid remote path or C.
		if n.ImportPath == "C" {
			continue
		} else if !base.IsValidRemotePath(n.ImportPath) {
			// Invalid import path.
			if setting.LibraryMode {
				errors.AppendError(errors.NewErrInvalidPackage(n.VerString()))
			}
			log.Error("Skipped invalid package: " + n.VerString())
			failConut++
			continue
		}

		// Valid import path.
		if isSubpackage(n.RootPath, target) {
			continue
		}

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

		if downloadCache.Get(n.VerString()) {
			if !skipCache.Get(n.VerString()) {
				skipCache.Set(n.VerString())
				log.Debug("Skipped downloaded package: %s", n.VerString())
			}
			continue
		}

		if !ctx.Bool("update") {
			// Check if package has been downloaded.
			if n.IsExist() {
				if !skipCache.Get(n.VerString()) {
					skipCache.Set(n.VerString())
					log.Info("%s", n.InstallPath)
					log.Debug("Skipped installed package: %s", n.VerString())
				}

				// Only copy when no version control.
				if !copyCache.Get(n.VerString()) && (ctx.Bool("gopath") || ctx.Bool("local")) {
					copyCache.Set(n.VerString())
					if err = n.CopyToGopath(); err != nil {
						return err
					}
				}
				continue
			} else {
				setting.LocalNodes.SetValue(n.RootPath, "value", "")
			}
		}
		// Download package.
		nod, imports, err := downloadPackage(ctx, n)
		if err != nil {
			return err
		}
		for _, name := range imports {
			var gf *goconfig.ConfigFile
			gfPath := path.Join(n.InstallPath, setting.GOPMFILE)

			// Check if has gopmfile.
			if base.IsFile(gfPath) {
				log.Info("Found gopmfile: %s", n.VerString())
				var err error
				gf, _, err = parseGopmfile(gfPath)
				if err != nil {
					return fmt.Errorf("fail to parse gopmfile(%s): %v", gfPath, err)
				}
			}

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

				if gf == nil {
					continue
				}

				// Check if user specified the version.
				if v := gf.MustValue("deps", imports[i]); len(v) > 0 {
					nodes[i].Type, nodes[i].Value, nodes[i].DownloadURL, err = validPkgInfo(v)
					if err != nil {
						return err
					}
				}
			}
			if err = downloadPackages(target, ctx, nodes); err != nil {
				return err
			}
		}

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

		// Save record in local nodes.
		log.Info("Got %s", n.VerString())
		downloadCount++

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

		// If update set downloadPackage will use VSC tools to download the package,
		// else just download to local repository and copy to GOPATH.
		if !nod.HasVcs() && !copyCache.Get(n.RootPath) && (ctx.Bool("gopath") || ctx.Bool("local")) {
			copyCache.Set(n.RootPath)
			if err = nod.CopyToGopath(); err != nil {
				return err
			}
		}
	}
	return nil
}
Beispiel #11
0
func runUpdate(ctx *cli.Context) {
	if setting.LibraryMode {
		errors.SetError(fmt.Errorf("Library mode does not support update command"))
		return
	}
	if err := setup(ctx); err != nil {
		errors.SetError(err)
		return
	}

	isAnythingUpdated := false
	localVerInfo := loadLocalVerInfo()

	// Get remote version info.
	var remoteVerInfo version
	if err := base.HttpGetJSON(doc.HttpClient, "http://gopm.io/VERSION.json", &remoteVerInfo); err != nil {
		log.Fatal("Fail to fetch VERSION.json: %v", err)
	}

	// Package name list.
	if remoteVerInfo.PackageNameList > localVerInfo.PackageNameList {
		log.Info("Updating pkgname.list...%v > %v",
			localVerInfo.PackageNameList, remoteVerInfo.PackageNameList)
		data, err := base.HttpGetBytes(doc.HttpClient, "https://raw.githubusercontent.com/gpmgo/docs/master/pkgname.list", nil)
		if err != nil {
			log.Warn("Fail to update pkgname.list: %v", err)
		} else {
			if err = ioutil.WriteFile(setting.PkgNameListFile, data, os.ModePerm); err != nil {
				log.Fatal("Fail to save pkgname.list: %v", err)
			}
			log.Info("Update pkgname.list to %v succeed!", remoteVerInfo.PackageNameList)
			isAnythingUpdated = true
		}
	}

	// Gopm.
	if remoteVerInfo.Gopm > setting.VERSION {
		log.Info("Updating gopm...%v > %v", setting.VERSION, remoteVerInfo.Gopm)

		tmpDir := base.GetTempDir()
		tmpBinPath := path.Join(tmpDir, "gopm")
		if runtime.GOOS == "windows" {
			tmpBinPath += ".exe"
		}

		os.MkdirAll(path.Dir(tmpBinPath), os.ModePerm)
		os.Remove(tmpBinPath)

		// Fetch code.
		args := []string{"bin", "-u", "-r", "-d=" + tmpDir}
		if ctx.Bool("verbose") {
			args = append(args, "-v")
		}
		args = append(args, "github.com/gpmgo/gopm")
		stdout, stderr, err := base.ExecCmd("gopm", args...)
		if err != nil {
			log.Fatal("Fail to execute 'bin -u -r -d=/Users/jiahuachen/.gopm/temp -v github.com/gpmgo/gopm: %s", stderr)
		}
		if len(stdout) > 0 {
			fmt.Print(stdout)
		}

		// Check if previous steps were successful.
		if !base.IsExist(tmpBinPath) {
			log.Error("Fail to continue command")
			log.Fatal("Previous steps weren't successful, no binary produced")
		}

		movePath, err := execPath()
		if err != nil {
			log.Fatal("Fail to get execute path: %v", err)
		}
		log.Info("New binary will be replaced for %s", movePath)
		// Move binary to given directory.
		if runtime.GOOS != "windows" {
			err := os.Rename(tmpBinPath, movePath)
			if err != nil {
				log.Fatal("Fail to move binary: %v", err)
			}
			os.Chmod(movePath+"/"+path.Base(tmpBinPath), os.ModePerm)
		} else {
			batPath := path.Join(tmpDir, "update.bat")
			f, err := os.Create(batPath)
			if err != nil {
				log.Error("Update", "Fail to generate bat file")
				log.Fatal("", err.Error())
			}
			f.WriteString("@echo off\r\n")
			f.WriteString(fmt.Sprintf("ping -n 1 127.0.0.1>nul\r\ncopy \"%v\" \"%v\" >nul\r\ndel \"%v\" >nul\r\n\r\n",
				tmpBinPath, movePath, tmpBinPath))
			f.Close()

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

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

		log.Info("Command execute successfully!")
		isAnythingUpdated = true
	}

	if isAnythingUpdated {
		// Save JSON.
		verPath := path.Join(setting.HomeDir, ".gopm", setting.VERINFO)
		os.MkdirAll(path.Dir(verPath), os.ModePerm)
		f, err := os.Create(verPath)
		if err != nil {
			log.Fatal("Fail to create VERSION.json: %v", err)
		}
		if err := json.NewEncoder(f).Encode(&remoteVerInfo); err != nil {
			log.Fatal("Fail to encode VERSION.json: %v", err)
		}
	} else {
		log.Info("Nothing need to be updated")
	}
	log.Info("Exit old gopm")
}