• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang com.ExecCmd函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/Unknwon/com.ExecCmd函数的典型用法代码示例。如果您正苦于以下问题:Golang ExecCmd函数的具体用法?Golang ExecCmd怎么用?Golang ExecCmd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ExecCmd函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: NewRepoContext

func NewRepoContext() {
	zip.Verbose = false

	// Check if server has basic git setting.
	stdout, stderr, err := com.ExecCmd("git", "config", "--get", "user.name")
	if strings.Contains(stderr, "fatal:") {
		log.Fatal("repo.NewRepoContext(fail to get git user.name): %s", stderr)
	} else if err != nil || len(strings.TrimSpace(stdout)) == 0 {
		if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.email", "[email protected]"); err != nil {
			log.Fatal("repo.NewRepoContext(fail to set git user.email): %s", stderr)
		} else if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
			log.Fatal("repo.NewRepoContext(fail to set git user.name): %s", stderr)
		}
	}

	barePath := path.Join(setting.RepoRootPath, "git-bare.zip")
	if !com.IsExist(barePath) {
		data, err := bin.Asset("conf/content/git-bare.zip")
		if err != nil {
			log.Fatal("Fail to get asset 'git-bare.zip': %v", err)
		} else if err := ioutil.WriteFile(barePath, data, os.ModePerm); err != nil {
			log.Fatal("Fail to write asset 'git-bare.zip': %v", err)
		}
	}
}
开发者ID:jcfrank,项目名称:gogs,代码行数:25,代码来源:repo.go


示例2: NewRepoContext

func NewRepoContext() {
	zip.Verbose = false

	// Check if server has basic git setting.
	stdout, _, err := com.ExecCmd("git", "config", "--get", "user.name")
	if err != nil {
		fmt.Printf("repo.init(fail to get git user.name): %v", err)
		os.Exit(2)
	} else if len(stdout) == 0 {
		if _, _, err = com.ExecCmd("git", "config", "--global", "user.email", "[email protected]"); err != nil {
			fmt.Printf("repo.init(fail to set git user.email): %v", err)
			os.Exit(2)
		} else if _, _, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
			fmt.Printf("repo.init(fail to set git user.name): %v", err)
			os.Exit(2)
		}
	}

	// Initialize illegal patterns.
	for i := range illegalPatterns[1:] {
		pattern := ""
		for j := range illegalPatterns[i+1] {
			pattern += "[" + string(illegalPatterns[i+1][j]-32) + string(illegalPatterns[i+1][j]) + "]"
		}
		illegalPatterns[i+1] = pattern
	}
}
开发者ID:josephyzhou,项目名称:gogs,代码行数:27,代码来源:repo.go


示例3: initRepoCommit

// initRepoCommit temporarily changes with work directory.
func initRepoCommit(tmpPath string, sig *git.Signature) error {
	gitInitLocker.Lock()
	defer gitInitLocker.Unlock()

	// Change work directory.
	curPath, err := os.Getwd()
	if err != nil {
		return err
	} else if err = os.Chdir(tmpPath); err != nil {
		return err
	}
	defer os.Chdir(curPath)

	var stderr string
	if _, stderr, err = com.ExecCmd("git", "add", "--all"); err != nil {
		return err
	}
	log.Info("stderr(1): %s", stderr)
	if _, stderr, err = com.ExecCmd("git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
		"-m", "Init commit"); err != nil {
		return err
	}
	log.Info("stderr(2): %s", stderr)
	if _, stderr, err = com.ExecCmd("git", "push", "origin", "master"); err != nil {
		return err
	}
	log.Info("stderr(3): %s", stderr)
	return nil
}
开发者ID:josephyzhou,项目名称:gogs,代码行数:30,代码来源:repo.go


示例4: updateByVcs

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
}
开发者ID:josephyzhou,项目名称:gopm,代码行数:51,代码来源:get.go


示例5: updateByVcs

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
}
开发者ID:jexwn,项目名称:gopm,代码行数:51,代码来源:get.go


示例6: NewRepoContext

func NewRepoContext() {
	zip.Verbose = false

	// Check if server has basic git setting.
	stdout, stderr, err := com.ExecCmd("git", "config", "--get", "user.name")
	if strings.Contains(stderr, "fatal:") {
		qlog.Fatalf("repo.NewRepoContext(fail to get git user.name): %s", stderr)
	} else if err != nil || len(strings.TrimSpace(stdout)) == 0 {
		if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.email", "[email protected]"); err != nil {
			qlog.Fatalf("repo.NewRepoContext(fail to set git user.email): %s", stderr)
		} else if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
			qlog.Fatalf("repo.NewRepoContext(fail to set git user.name): %s", stderr)
		}
	}
}
开发者ID:j20,项目名称:gogs,代码行数:15,代码来源:repo.go


示例7: Listen

// Listen starts a SSH server listens on given port.
func Listen(port int) {
	config := &ssh.ServerConfig{
		PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
			if err != nil {
				log.Error(3, "SearchPublicKeyByContent: %v", err)
				return nil, err
			}
			return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
		},
	}

	keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
	if !com.IsExist(keyPath) {
		os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
		_, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
		if err != nil {
			panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
		}
		log.Trace("New private key is generateed: %s", keyPath)
	}

	privateBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		panic("Fail to load private key")
	}
	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Fail to parse private key")
	}
	config.AddHostKey(private)

	go listen(config, port)
}
开发者ID:cuteluo1983,项目名称:gogs,代码行数:35,代码来源:ssh.go


示例8: getGoogleTags

func getGoogleTags(importPath string, defaultBranch string, isGoRepo bool) []string {
	stdout, _, err := com.ExecCmd("curl", "http://"+utils.GetProjectPath(importPath)+"/source/browse")
	if err != nil {
		return nil
	}
	p := []byte(stdout)

	page := string(p)
	start := strings.Index(page, "<strong>Tag:</strong>")
	if start == -1 {
		return nil
	}

	m := googleTagRe.FindAllStringSubmatch(page[start:], -1)

	var tags []string
	if isGoRepo {
		tags = make([]string, 1, 20)
	} else {
		tags = make([]string, len(m)+1)
	}

	tags[0] = defaultBranch
	for i, v := range m {
		if isGoRepo {
			if strings.HasPrefix(v[1], "go") {
				tags = append(tags, v[1])
			}
			continue
		}
		tags[i+1] = v[1]
	}
	return tags
}
开发者ID:NicholeGit,项目名称:gowalker,代码行数:34,代码来源:google.go


示例9: NewRepoContext

func NewRepoContext() {
	zip.Verbose = false

	// Check if server has basic git setting.
	stdout, _, err := com.ExecCmd("git", "config", "--get", "user.name")
	if err != nil {
		fmt.Printf("repo.init(fail to get git user.name): %v", err)
		os.Exit(2)
	} else if len(stdout) == 0 {
		if _, _, err = com.ExecCmd("git", "config", "--global", "user.email", "[email protected]"); err != nil {
			fmt.Printf("repo.init(fail to set git user.email): %v", err)
			os.Exit(2)
		} else if _, _, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
			fmt.Printf("repo.init(fail to set git user.name): %v", err)
			os.Exit(2)
		}
	}
}
开发者ID:JREAMLU,项目名称:gogs,代码行数:18,代码来源:repo.go


示例10: getGoogleVCS

func getGoogleVCS(match map[string]string) error {
	// Scrape the HTML project page to find the VCS.
	stdout, _, err := com.ExecCmd("curl", com.Expand("http://code.google.com/p/{repo}/source/checkout", match))
	if err != nil {
		return errors.New("doc.getGoogleVCS(" + match["importPath"] + ") -> " + err.Error())
	}
	m := googleRepoRe.FindSubmatch([]byte(stdout))
	if m == nil {
		return com.NotFoundError{"Could not VCS on Google Code project page."}
	}
	match["vcs"] = string(m[1])
	return nil
}
开发者ID:NicholeGit,项目名称:gowalker,代码行数:13,代码来源:google.go


示例11: makeLink

func makeLink(srcPath, destPath string) error {
	srcPath = strings.Replace(srcPath, "/", "\\", -1)
	destPath = strings.Replace(destPath, "/", "\\", -1)

	// Check if Windows version is XP.
	if getWindowsVersion() >= 6 {
		_, stderr, err := com.ExecCmd("cmd", "/c", "mklink", "/j", destPath, srcPath)
		if err != nil {
			return errors.New(stderr)
		}
		return nil
	}

	// XP.
	setting.IsWindowsXP = true
	// if both are ntfs file system
	if volumnType(srcPath) == "NTFS" && volumnType(destPath) == "NTFS" {
		// if has junction command installed
		file, err := exec.LookPath("junction")
		if err == nil {
			path, _ := filepath.Abs(file)
			if com.IsFile(path) {
				_, stderr, err := com.ExecCmd("cmd", "/c", "junction", destPath, srcPath)
				if err != nil {
					return errors.New(stderr)
				}
				return nil
			}
		}
	}
	os.RemoveAll(destPath)

	return com.CopyDir(srcPath, destPath, func(filePath string) bool {
		return strings.Contains(filePath, setting.VENDOR)
	})
}
开发者ID:juqkai,项目名称:gopm,代码行数:36,代码来源:helper_windows.go


示例12: MigrateRepository

// MigrateRepository migrates a existing repository from other project hosting.
func MigrateRepository(user *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
	repo, err := CreateRepository(user, name, desc, "", "", private, mirror, false)
	if err != nil {
		return nil, err
	}

	// Clone to temprory path and do the init commit.
	tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
	os.MkdirAll(tmpDir, os.ModePerm)

	repoPath := RepoPath(user.Name, name)

	repo.IsBare = false
	if mirror {
		if err = MirrorRepository(repo.Id, user.Name, repo.Name, repoPath, url); err != nil {
			return repo, err
		}
		repo.IsMirror = true
		return repo, UpdateRepository(repo)
	}

	// Clone from local repository.
	_, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir)
	if err != nil {
		return repo, err
	} else if strings.Contains(stderr, "fatal:") {
		return repo, errors.New("git clone: " + stderr)
	}

	// Pull data from source.
	_, stderr, err = com.ExecCmdDir(tmpDir, "git", "pull", url)
	if err != nil {
		return repo, err
	} else if strings.Contains(stderr, "fatal:") {
		return repo, errors.New("git pull: " + stderr)
	}

	// Push data to local repository.
	if _, stderr, err = com.ExecCmdDir(tmpDir, "git", "push", "origin", "master"); err != nil {
		return repo, err
	} else if strings.Contains(stderr, "fatal:") {
		return repo, errors.New("git push: " + stderr)
	}

	return repo, UpdateRepository(repo)
}
开发者ID:kennylixi,项目名称:gogs,代码行数:47,代码来源:repo.go


示例13: MirrorRepository

// MirrorRepository creates a mirror repository from source.
func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
	_, stderr, err := com.ExecCmd("git", "clone", "--mirror", url, repoPath)
	if err != nil {
		return errors.New("git clone --mirror: " + stderr)
	}

	if _, err = orm.InsertOne(&Mirror{
		RepoId:     repoId,
		RepoName:   strings.ToLower(userName + "/" + repoName),
		Interval:   24,
		NextUpdate: time.Now().Add(24 * time.Hour),
	}); err != nil {
		return err
	}

	return git.UnpackRefs(repoPath)
}
开发者ID:kristofer,项目名称:gogs,代码行数:18,代码来源:repo.go


示例14: GetVersion

// GetVersion returns current Git version installed.
func GetVersion() (*Version, error) {
	if gitVer != nil {
		return gitVer, nil
	}

	stdout, stderr, err := com.ExecCmd("git", "version")
	if err != nil {
		return nil, errors.New(stderr)
	}

	infos := strings.Split(stdout, " ")
	if len(infos) < 3 {
		return nil, errors.New("not enough output")
	}

	gitVer, err = ParseVersion(infos[2])
	return gitVer, err
}
开发者ID:nathan7,项目名称:gogs,代码行数:19,代码来源:version.go


示例15: ReloadDocs

func ReloadDocs() error {
	tocLocker.Lock()
	defer tocLocker.Unlock()

	localRoot := setting.Docs.Target

	// Fetch docs from remote.
	if setting.Docs.Type.IsRemote() {
		localRoot = docsRoot

		absRoot, err := filepath.Abs(localRoot)
		if err != nil {
			return fmt.Errorf("filepath.Abs: %v", err)
		}

		// Clone new or pull to update.
		if com.IsDir(absRoot) {
			stdout, stderr, err := com.ExecCmdDir(absRoot, "git", "pull")
			if err != nil {
				return fmt.Errorf("Fail to update docs from remote source(%s): %v - %s", setting.Docs.Target, err, stderr)
			}
			fmt.Println(stdout)
		} else {
			os.MkdirAll(filepath.Dir(absRoot), os.ModePerm)
			stdout, stderr, err := com.ExecCmd("git", "clone", setting.Docs.Target, absRoot)
			if err != nil {
				return fmt.Errorf("Fail to clone docs from remote source(%s): %v - %s", setting.Docs.Target, err, stderr)
			}
			fmt.Println(stdout)
		}
	}

	if !com.IsDir(localRoot) {
		return fmt.Errorf("Documentation not found: %s - %s", setting.Docs.Type, localRoot)
	}

	tocs, err := initToc(localRoot)
	if err != nil {
		return fmt.Errorf("initToc: %v", err)
	}
	initDocs(tocs, localRoot)
	Tocs = tocs
	return reloadProtects(localRoot)
}
开发者ID:52M,项目名称:peach,代码行数:44,代码来源:toc.go


示例16: AddPublicKey

// AddPublicKey adds new public key to database and SSH key file.
func AddPublicKey(key *PublicKey) (err error) {
	// Check if public key name has been used.
	has, err := orm.Get(key)
	if err != nil {
		return err
	} else if has {
		return ErrKeyAlreadyExist
	}

	// Calculate fingerprint.
	tmpPath := strings.Replace(filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
		"id_rsa.pub"), "\\", "/", -1)
	os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
	if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
		return err
	}
	stdout, _, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
	if err != nil {
		return err
	} else if len(stdout) < 2 {
		return errors.New("Not enough output for calculating fingerprint")
	}
	key.Fingerprint = strings.Split(stdout, " ")[1]

	// Save SSH key.
	if _, err = orm.Insert(key); err != nil {
		return err
	}
	if err = SaveAuthorizedKeyFile(key); err != nil {
		if _, err2 := orm.Delete(key); err2 != nil {
			return err2
		}
		return err
	}

	return nil
}
开发者ID:JREAMLU,项目名称:gogs,代码行数:38,代码来源:publickey.go


示例17: GetVersion

// GetVersion returns current Git version installed.
func GetVersion() (Version, error) {
	stdout, stderr, err := com.ExecCmd("git", "version")
	if err != nil {
		return Version{}, errors.New(stderr)
	}

	infos := strings.Split(stdout, " ")
	if len(infos) < 3 {
		return Version{}, errors.New("not enough output")
	}

	v := Version{}
	for i, s := range strings.Split(strings.TrimSpace(infos[2]), ".") {
		switch i {
		case 0:
			v.Major, _ = com.StrTo(s).Int()
		case 1:
			v.Minor, _ = com.StrTo(s).Int()
		case 2:
			v.Patch, _ = com.StrTo(s).Int()
		}
	}
	return v, nil
}
开发者ID:felipelovato,项目名称:gogs,代码行数:25,代码来源:version.go


示例18: runExec

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)
	}
}
开发者ID:kulasama,项目名称:gopm,代码行数:80,代码来源:exec.go


示例19: getStandardDoc

func getStandardDoc(client *http.Client, importPath, tag, ptag string) (*hv.Package, error) {
	// hg-higtory: http://go.googlecode.com/hg-history/release/src/pkg/"+importPath+"/"
	stdout, _, err := com.ExecCmd("curl", "http://go.googlecode.com/hg/src/pkg/"+importPath+"/?r="+tag)
	if err != nil {
		return nil, errors.New("doc.getStandardDoc(" + importPath + ") -> " + err.Error())
	}
	p := []byte(stdout)

	// Check revision tag.
	var etag string
	if m := googleRevisionRe.FindSubmatch(p); m == nil {
		return nil, errors.New("doc.getStandardDoc(" + importPath + ") -> Could not find revision")
	} else {
		etag = string(m[1])
		if etag == ptag {
			return nil, errNotModified
		}
	}

	// Get source file data.
	ms := googleFileRe.FindAllSubmatch(p, -1)
	files := make([]com.RawFile, 0, len(ms))
	for _, m := range ms {
		fname := strings.Split(string(m[1]), "?")[0]
		if utils.IsDocFile(fname) {
			files = append(files, &hv.Source{
				SrcName:   fname,
				BrowseUrl: "code.google.com/p/go/source/browse/src/pkg/" + importPath + "/" + fname + "?r=" + tag,
				RawSrcUrl: "http://go.googlecode.com/hg/src/pkg/" + importPath + "/" + fname + "?r=" + tag,
			})
		}
	}

	// Get subdirectories.
	ms = googleDirRe.FindAllSubmatch(p, -1)
	dirs := make([]string, 0, len(ms))
	for _, m := range ms {
		dirName := strings.Split(string(m[1]), "?")[0]
		// Make sure we get directories.
		if strings.HasSuffix(dirName, "/") &&
			utils.FilterDirName(dirName) {
			dirs = append(dirs, strings.Replace(dirName, "/", "", -1))
		}
	}

	if len(files) == 0 && len(dirs) == 0 {
		return nil, com.NotFoundError{"Directory tree does not contain Go files and subdirs."}
	}

	// Fetch file from VCS.
	if err := fetchGoogleFiles(client, files); err != nil {
		return nil, err
	}

	// Get all tags.
	tags := getGoogleTags("code.google.com/p/go/"+importPath, "default", true)

	// Start generating data.
	w := &hv.Walker{
		LineFmt: "#%d",
		Pdoc: &hv.Package{
			PkgInfo: &hv.PkgInfo{
				ImportPath:  importPath,
				ProjectName: "Go",
				ProjectPath: "code.google.com/p/go/source/browse/src/pkg/?r=" + tag,
				ViewDirPath: "code.google.com/p/go/source/browse/src/pkg/" + importPath + "/?r=" + tag,
				IsGoRepo:    true,
				Tags:        strings.Join(tags, "|||"),
				Ptag:        etag,
				Vcs:         "Google Code",
			},
			PkgDecl: &hv.PkgDecl{
				Tag:  tag,
				Dirs: dirs,
			},
		},
	}

	srcs := make([]*hv.Source, 0, len(files))
	srcMap := make(map[string]*hv.Source)
	for _, f := range files {
		s, _ := f.(*hv.Source)
		srcs = append(srcs, s)

		if len(tag) == 0 && !strings.HasSuffix(f.Name(), "_test.go") {
			srcMap[f.Name()] = s
		}
	}

	pdoc, err := w.Build(&hv.WalkRes{
		WalkDepth: hv.WD_All,
		WalkType:  hv.WT_Memory,
		WalkMode:  hv.WM_All,
		Srcs:      srcs,
	})
	if err != nil {
		return nil, errors.New("doc.getStandardDoc(" + importPath + ") -> Fail to build: " + err.Error())
	}

	return pdoc, generateHv(importPath, srcMap)
//.........这里部分代码省略.........
开发者ID:NicholeGit,项目名称:gowalker,代码行数:101,代码来源:google.go


示例20: getGoogleDoc

func getGoogleDoc(client *http.Client, match map[string]string, tag, ptag string) (*hv.Package, error) {
	setupGoogleMatch(match)
	if m := googleEtagRe.FindStringSubmatch(ptag); m != nil {
		match["vcs"] = m[1]
	} else if err := getGoogleVCS(match); err != nil {
		return nil, err
	}

	match["tag"] = tag
	// Scrape the repo browser to find the project revision and individual Go files.
	stdout, _, err := com.ExecCmd("curl", com.Expand("http://{subrepo}{dot}{repo}.googlecode.com/{vcs}{dir}/?r={tag}", match))
	if err != nil {
		return nil, errors.New("doc.getGoogleDoc(" + match["importPath"] + ") -> " + err.Error())
	}
	p := []byte(stdout)

	// Check revision tag.
	var etag string
	if m := googleRevisionRe.FindSubmatch(p); m == nil {
		return nil, errors.New("doc.getGoogleDoc(" + match["importPath"] + ") -> Could not find revision")
	} else {
		etag = string(m[1])
		if etag == ptag {
			return nil, errNotModified
		}
	}

	match["browserUrlTpl"] = "code.google.com/p/{repo}/source/browse{dir}/{0}?repo={subrepo}&r={tag}"
	match["rawSrcUrlTpl"] = "http://{subrepo}{dot}{repo}.googlecode.com/{vcs}{dir}/{0}?r={tag}"
	var isGoPro bool
	var files []com.RawFile
	var dirs []string
	// Unrecord and non-SVN project can download archive.
	if len(ptag) == 0 || match["vcs"] == "svn" {
		tmpTag := match["tag"]
		if len(tmpTag) == 0 {
			tmpTag = defaultTags[match["vcs"]]
		}

		isGoPro, _, files, dirs, err = getRepoByArchive(match,
			com.Expand("http://{subrepo}{dot}{repo}.googlecode.com/archive/{0}.zip", match, tmpTag))
		if err != nil {
			return nil, errors.New("doc.getGoogleDoc(" + match["importPath"] + ") -> Fail to download archive: " + err.Error())
		}
	} else {
		// Get source file data.
		ms := googleFileRe.FindAllSubmatch(p, -1)
		files = make([]com.RawFile, 0, len(ms))
		for _, m := range ms {
			fname := strings.Split(string(m[1]), "?")[0]
			if utils.IsDocFile(fname) {
				isGoPro = true
				files = append(files, &hv.Source{
					SrcName:   fname,
					BrowseUrl: com.Expand(match["browserUrlTpl"], match, fname),
					RawSrcUrl: com.Expand(match["rawSrcUrlTpl"], match, fname),
				})
			}
		}

		// Get subdirectories.
		ms = googleDirRe.FindAllSubmatch(p, -1)
		dirs = make([]string, 0, len(ms))
		for _, m := range ms {
			dirName := strings.Split(string(m[1]), "?")[0]
			// Make sure we get directories.
			if strings.HasSuffix(dirName, "/") &&
				utils.FilterDirName(dirName) {
				dirs = append(dirs, strings.Replace(dirName, "/", "", -1))
			}
		}
	}

	if !isGoPro {
		return nil, com.NotFoundError{"Cannot find Go files, it's not a Go project."}
	}

	if len(files) == 0 && len(dirs) == 0 {
		return nil, com.NotFoundError{"Directory tree does not contain Go files and subdirs."}
	}

	// Fetch file from VCS.
	if err := fetchGoogleFiles(client, files); err != nil {
		return nil, err
	}

	// Get all tags.
	tags := getGoogleTags(match["importPath"], defaultTags[match["vcs"]], false)

	// Start generating data.
	w := &hv.Walker{
		LineFmt: "#%d",
		Pdoc: &hv.Package{
			PkgInfo: &hv.PkgInfo{
				ImportPath: match["importPath"],
				IsGoSubrepo: utils.IsGoSubrepoPath(strings.TrimPrefix(
					match["importPath"], "code.google.com/p/")),
				ProjectName: com.Expand("{repo}{dot}{subrepo}", match),
				ProjectPath: com.Expand("code.google.com/p/{repo}/source/browse/?repo={subrepo}&r={tag}", match),
				ViewDirPath: com.Expand("code.google.com/p/{repo}/source/browse{dir}?repo={subrepo}&r={tag}", match),
//.........这里部分代码省略.........
开发者ID:NicholeGit,项目名称:gowalker,代码行数:101,代码来源:google.go



注:本文中的github.com/Unknwon/com.ExecCmd函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang com.ExecCmdDir函数代码示例发布时间:2022-05-28
下一篇:
Golang com.Copy函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap