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

Golang vcs.RepoRootForImportPath函数代码示例

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

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



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

示例1: repoForTool

// repoForTool returns the correct RepoRoot for the buildTool, or an error if
// the tool is unknown.
func repoForTool() (*vcs.RepoRoot, error) {
	switch *buildTool {
	case "go":
		return vcs.RepoRootForImportPath(*gcPath, *verbose)
	case "gccgo":
		return vcs.RepoRootForImportPath(gofrontendImportPath, *verbose)
	default:
		return nil, fmt.Errorf("unknown build tool: %s", *buildTool)
	}
}
开发者ID:dylanpoe,项目名称:golang.org,代码行数:12,代码来源:main.go


示例2: Behind

// Behind takes a github token and a godep file
//  and returns a list of dependencies and if they are out of date
func Behind(githubToken string, godepFile string) []ImportStatus {
	gh := NewGitHub(githubToken)
	gd, err := LoadGodepsFile(godepFile)
	if err != nil {
		log.Fatalf("Error loading godeps file %q: %s", godepFile, err)
	}

	roots := make(map[string]bool, len(gd.Deps))

	imports := make([]ImportStatus, 0, len(gd.Deps))

	for _, dep := range gd.Deps {
		rr, err := vcs.RepoRootForImportPath(dep.ImportPath, false)
		if err != nil {
			log.Printf("Unable to process %s: %s", dep.ImportPath, err)
			continue
		}
		if roots[rr.Root] {
			continue
		}
		roots[rr.Root] = true
		parts := strings.Split(dep.ImportPath, "/")
		if len(parts) < 2 {
			log.Printf("Skipping %s", dep.ImportPath)
			continue
		}
		if parts[0] == "golang.org" && parts[1] == "x" {
			parts[0] = "github.com"
			parts[1] = "golang"
		}

		if parts[0] != "github.com" {
			log.Printf("Skipping %s", dep.ImportPath)
			continue
		}

		compare, _, err := gh.Client.Repositories.CompareCommits(parts[1], parts[2], dep.Rev, "HEAD")
		if err != nil {
			log.Printf("got error reading repo %s: %s", dep.ImportPath, err)
			continue
		}
		status := ImportStatus{
			Root:    rr.Root,
			Status:  *compare.Status,
			Commits: make([]CommitMini, 0, len(compare.Commits)),
		}
		for _, c := range compare.Commits {
			msg := ""
			if c.Commit.Message != nil {
				msg = *c.Commit.Message
			}
			status.Commits = append(status.Commits, CommitMini{
				SHA: *c.SHA,
				Msg: msg,
			})
		}
		imports = append(imports, status)
	}
	return imports
}
开发者ID:client9,项目名称:gosupplychain,代码行数:62,代码来源:behind.go


示例3: computeVCSState

func (*workspace) computeVCSState(r *Repo) {
	if r.vcs == nil {
		// Go package not under VCS.
		return
	}

	r.DefaultBranch = r.vcs.DefaultBranch()
	if s, err := r.vcs.Status(r.Path); err == nil {
		r.Local.Status = s
	}
	if b, err := r.vcs.Branch(r.Path); err == nil {
		r.Local.Branch = b
	}
	if rev, err := r.vcs.LocalRevision(r.Path); err == nil {
		r.Local.Revision = rev
	}
	if s, err := r.vcs.Stash(r.Path); err == nil {
		r.Local.Stash = s
	}
	if remote, err := r.vcs.RemoteURL(r.Path); err == nil {
		r.Local.RemoteURL = remote
	}
	if rev, err := r.vcs.RemoteRevision(r.Path); err == nil {
		r.Remote.Revision = rev
	}
	if r.Remote.Revision != "" {
		if c, err := r.vcs.Contains(r.Path, r.Remote.Revision); err == nil {
			r.LocalContainsRemoteRevision = c
		}
	}
	if rr, err := vcs.RepoRootForImportPath(r.Root, false); err == nil {
		r.Remote.RepoURL = rr.Repo
	}
}
开发者ID:leobcn,项目名称:gostatus,代码行数:34,代码来源:workspace.go


示例4: getRepoRoot

// getRepoRoot takes an import path like github.com/sparrc/gdm
// and returns the VCS Repository information for it.
func getRepoRoot(importpath string) (*vcs.RepoRoot, error) {
	repo, err := vcs.RepoRootForImportPath(importpath, false)
	if err != nil {
		return nil, err
	}
	return repo, nil
}
开发者ID:markyjones,项目名称:gdm,代码行数:9,代码来源:imports.go


示例5: createRepo

func (custom *CmakeCustomizations) createRepo() error {
	Info(fmt.Sprintf("Downloading %s", custom.Configuration.Project))
	repo, err := vcs.RepoRootForImportPath(custom.Configuration.Project, false)
	if err != nil {
		return err
	}
	return repo.VCS.Create(custom.paths.src, repo.Repo)
}
开发者ID:sinfomicien,项目名称:rkt,代码行数:8,代码来源:cmake.go


示例6: RemoteRepo

// RemoteRepo constructs a *Repo representing a remote repository.
func RemoteRepo(url, path string) (*Repo, error) {
	rr, err := vcs.RepoRootForImportPath(url, *verbose)
	if err != nil {
		return nil, err
	}
	return &Repo{
		Path:   path,
		Master: rr,
	}, nil
}
开发者ID:rdterner,项目名称:build,代码行数:11,代码来源:vcs.go


示例7: FromImportPath

func FromImportPath(importPath string) (*VCS, error) {
	rr, err := vcs.RepoRootForImportPath(importPath, false)
	if err != nil {
		return nil, err
	}
	vcs := cmd[rr.VCS]
	if vcs == nil {
		return nil, fmt.Errorf("%s is unsupported: %s", rr.VCS.Name, importPath)
	}
	return vcs, nil
}
开发者ID:azylman,项目名称:govend,代码行数:11,代码来源:vcs.go


示例8: UpdateVcsFields

func (this *GoPackage) UpdateVcsFields() {
	if this.Dir.Repo == nil {
		return
	}

	gist7802150.MakeUpdated(this.Dir.Repo.VcsLocal)
	gist7802150.MakeUpdated(this.Dir.Repo.VcsRemote)

	repoImportPath := GetRepoImportPath(this.Dir.Repo.Vcs.RootPath(), this.Bpkg.SrcRoot)
	if repoRoot, err := vcs.RepoRootForImportPath(repoImportPath, false); err == nil {
		this.Dir.Repo.RepoRoot = repoRoot
	}
}
开发者ID:rexposadas,项目名称:gx,代码行数:13,代码来源:main.go


示例9: NewPackage

// NewPackage returns new package.
func NewPackage(name, gopath string) (*Package, error) {
	dir := filepath.Join(gopath, "src", name)
	repo, err := vcs.RepoRootForImportPath(name, false)
	if err != nil {
		// it's ok, silently discard errors here
		return nil, err
	}
	return &Package{
		Name: name,
		Dir:  dir,

		Repo: repo,
	}, nil
}
开发者ID:vibbix,项目名称:gofresh,代码行数:15,代码来源:package.go


示例10: mergeGodeps

// mergeGodeps will get one master list of revs.
func (w *workspace) mergeGodeps(dirGs map[string]Godeps) map[string]dirDep {
	roots := map[string]dirDep{}
	for dir, g := range dirGs {
		for _, dep := range g.Deps {
			repoRoot, err := vcs.RepoRootForImportPath(dep.ImportPath, false)
			if err != nil {
				fmt.Fprintf(os.Stderr, "for %q: %s\n", dep.ImportPath, err)
				continue
			}
			dd := dirDep{
				srcDir: dir,
				rev:    dep.Rev,
				repo:   repoRoot.Repo,
				root:   filepath.Join(w.vendorRootSrc(), repoRoot.Root),
				kind:   repoRoot.VCS.Cmd,
			}
			if orig, ok := roots[repoRoot.Repo]; ok {
				if orig != dd {
					fmt.Fprintf(os.Stderr, "conflict for %q: godeps in %q and %q do not match\n",
						dd.repo, orig.srcDir, dd.srcDir)
					continue
				}
			} else {
				roots[repoRoot.Root] = dd
			}
		}
	}

	// clear out nested
	var rootDirs sort.StringSlice
	for _, dd := range roots {
		rootDirs = append(rootDirs, dd.root)
	}
	sort.Sort(rootDirs)

	var last string
	for _, r := range rootDirs {
		if last != "" && strings.HasPrefix(r, last) {
			delete(roots, r)
			fmt.Fprintf(os.Stderr, "ignoring %q which is managed in %q\n", r, last)
		} else {
			last = r + string(filepath.Separator)
		}
	}

	return roots
}
开发者ID:abiosoft,项目名称:wgo,代码行数:48,代码来源:godep.go


示例11: getSpec

func getSpec(repoName string) (string, error) {
	repo, err := vcs.RepoRootForImportPath(repoName, true)
	if err != nil {
		return "", err
	}

	path := filepath.Join(GetQuiltPath(), repo.Root)
	if _, err := util.AppFs.Stat(path); os.IsNotExist(err) {
		log.Info(fmt.Sprintf("Cloning %s into %s", repo.Root, path))
		if err := create(repo, path); err != nil {
			return "", err
		}
	} else {
		log.Info(fmt.Sprintf("Updating %s in %s", repo.Root, path))
		download(repo, path)
	}
	return path, nil
}
开发者ID:yuenmeiwan,项目名称:quilt,代码行数:18,代码来源:get.go


示例12: commitWatcher

// commitWatcher polls hg for new commits and tells the dashboard about them.
func commitWatcher(goroot *Repo) {
	if *commitInterval == 0 {
		log.Printf("commitInterval is 0; disabling commitWatcher")
		return
	}
	if !*report {
		log.Printf("-report is false; disabling commitWatcher")
		return
	}
	// Create builder just to get master key.
	b, err := NewBuilder(goroot, "mercurial-commit")
	if err != nil {
		log.Fatal(err)
	}
	key := b.key

	benchMutex.RLock()
	for {
		if *verbose {
			log.Printf("poll...")
		}
		// Main Go repository.
		commitPoll(goroot, "", key)
		// Go sub-repositories.
		for _, pkg := range dashboardPackages("subrepo") {
			pkgmaster, err := vcs.RepoRootForImportPath(pkg, *verbose)
			if err != nil {
				log.Printf("Error finding subrepo (%s): %s", pkg, err)
				continue
			}
			pkgroot := &Repo{
				Path:   filepath.Join(*buildroot, pkg),
				Master: pkgmaster,
			}
			commitPoll(pkgroot, pkg, key)
		}
		benchMutex.RUnlock()
		if *verbose {
			log.Printf("sleep...")
		}
		time.Sleep(*commitInterval)
		benchMutex.RLock()
	}
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:45,代码来源:main.go


示例13: buildSubrepo

// buildSubrepo fetches the given package, updates it to the specified hash,
// and runs 'go test -short pkg/...'. It returns the build log and any error.
func (b *Builder) buildSubrepo(goRoot, goPath, pkg, hash string) (string, error) {
	goTool := filepath.Join(goRoot, "bin", "go") + exeExt
	env := append(b.envv(), "GOROOT="+goRoot, "GOPATH="+goPath)

	// add $GOROOT/bin and $GOPATH/bin to PATH
	for i, e := range env {
		const p = "PATH="
		if !strings.HasPrefix(e, p) {
			continue
		}
		sep := string(os.PathListSeparator)
		env[i] = p + filepath.Join(goRoot, "bin") + sep + filepath.Join(goPath, "bin") + sep + e[len(p):]
	}

	// HACK: check out to new sub-repo location instead of old location.
	pkg = strings.Replace(pkg, "code.google.com/p/go.", "golang.org/x/", 1)

	// fetch package and dependencies
	var outbuf bytes.Buffer
	err := run(exec.Command(goTool, "get", "-d", pkg+"/..."), runEnv(env), allOutput(&outbuf), runDir(goPath))
	if err != nil {
		return outbuf.String(), err
	}
	outbuf.Reset()

	// hg update to the specified hash
	pkgmaster, err := vcs.RepoRootForImportPath(pkg, *verbose)
	if err != nil {
		return "", fmt.Errorf("Error finding subrepo (%s): %s", pkg, err)
	}
	repo := &Repo{
		Path:   filepath.Join(goPath, "src", pkg),
		Master: pkgmaster,
	}
	if err := repo.UpdateTo(hash); err != nil {
		return "", err
	}

	// test the package
	err = run(exec.Command(goTool, "test", "-short", pkg+"/..."),
		runTimeout(*buildTimeout), runEnv(env), allOutput(&outbuf), runDir(goPath))
	return outbuf.String(), err
}
开发者ID:dylanpoe,项目名称:golang.org,代码行数:45,代码来源:main.go


示例14: ResolveRepo

// ResolveRepo on a default reporesolver is effectively go get wraped
// to use the url string.
func (dr *DefaultRepoResolver) ResolveRepo(importPath string, dep *CanticleDependency) (VCS, error) {
	// We guess our vcs based off our url path if present
	resolvePath := getResolvePath(importPath)

	LogVerbose("Attempting to use go get vcs for url: %s", resolvePath)
	vcs.Verbose = Verbose
	repo, err := vcs.RepoRootForImportPath(resolvePath, true)
	if err != nil {
		LogVerbose("Failed creating VCS for url: %s, err: %s", resolvePath, err.Error())
		return nil, err
	}

	// If we found something return non nil
	repo.Root, err = TrimPathToRoot(importPath, repo.Root)
	if err != nil {
		LogVerbose("Failed creating VCS for url: %s, err: %s", resolvePath, err.Error())
		return nil, err
	}
	v := &PackageVCS{Repo: repo, Gopath: dr.Gopath}
	LogVerbose("Created VCS for url: %s", resolvePath)
	return v, nil
}
开发者ID:Comcast,项目名称:Canticle,代码行数:24,代码来源:vcs.go


示例15: download

// download the given dependency.
// 2 Passes: 1) go get -d <pkg>, 2) git pull (if necessary)
func download(dep *Dependency) error {

	rr, err := vcs.RepoRootForImportPath(dep.ImportPath, debug)
	if err != nil {
		debugln("Error determining repo root for", dep.ImportPath)
		return err
	}
	ppln("rr", rr)

	dep.vcs = cmd[rr.VCS]

	// try to find an existing directory in the GOPATHs
	for _, gp := range filepath.SplitList(build.Default.GOPATH) {
		t := filepath.Join(gp, "src", rr.Root)
		fi, err := os.Stat(t)
		if err != nil {
			continue
		}
		if fi.IsDir() {
			dep.root = t
			break
		}
	}

	// If none found, just pick the first GOPATH entry (AFAICT that's what go get does)
	if dep.root == "" {
		dep.root = filepath.Join(filepath.SplitList(build.Default.GOPATH)[0], "src", rr.Root)
	}
	ppln("dep", dep)

	if downloaded[rr.Repo] {
		verboseln("Skipping already downloaded repo", rr.Repo)
		return nil
	}

	fi, err := os.Stat(dep.root)
	if err != nil {
		if os.IsNotExist(err) {
			if err := os.MkdirAll(filepath.Dir(dep.root), os.ModePerm); err != nil {
				debugln("Error creating base dir of", dep.root)
				return err
			}
			err := rr.VCS.CreateAtRev(dep.root, rr.Repo, dep.Rev)
			debugln("CreatedAtRev", dep.root, rr.Repo, dep.Rev)
			if err != nil {
				debugln("CreateAtRev error", err)
				return err
			}
			downloaded[rr.Repo] = true
			return nil
		}
		debugln("Error checking repo root for", dep.ImportPath, "at", dep.root, ":", err)
		return err
	}

	if !fi.IsDir() {
		return errors.New("repo root src dir exists, but isn't a directory for " + dep.ImportPath + " at " + dep.root)
	}

	if !dep.vcs.exists(dep.root, dep.Rev) {
		debugln("Updating existing", dep.root)
		if dep.vcs == vcsGit {
			detached, err := gitDetached(dep.root)
			if err != nil {
				return err
			}
			if detached {
				db, err := gitDefaultBranch(dep.root)
				if err != nil {
					return err
				}
				if err := gitCheckout(dep.root, db); err != nil {
					return err
				}
			}
		}

		dep.vcs.vcs.Download(dep.root)
		downloaded[rr.Repo] = true
	}

	debugln("Nothing to download")
	return nil
}
开发者ID:Cepave,项目名称:lvs-metrics,代码行数:86,代码来源:restore.go


示例16: makeUpstreamSourceTarball


//.........这里部分代码省略.........
	if err != nil {
		return "", "", dependencies, autoPkgType, err
	}

	log.Printf("Package version is %q\n", version)

	// If no import path defines a “main” package, we’re dealing with a
	// library, otherwise likely a program.
	log.Printf("Determining package type\n")
	cmd = exec.Command("go", "list", "-f", "{{.ImportPath}} {{.Name}}", gopkg+"/...")
	cmd.Stderr = os.Stderr
	cmd.Env = append([]string{
		fmt.Sprintf("GOPATH=%s", tempdir),
	}, passthroughEnv()...)

	out, err := cmd.Output()
	if err != nil {
		return "", "", dependencies, autoPkgType, err
	}
	for _, line := range strings.Split(string(out), "\n") {
		if strings.TrimSpace(line) == "" {
			continue
		}
		if strings.Contains(line, "/vendor/") ||
			strings.Contains(line, "/Godeps/") ||
			strings.Contains(line, "/samples/") ||
			strings.Contains(line, "/examples/") ||
			strings.Contains(line, "/example/") {
			continue
		}
		if strings.HasSuffix(line, " main") {
			if strings.TrimSpace(*pkgType) == "" {
				log.Printf("Assuming you are packaging a program (because %q defines a main package), use -type to override\n", line[:len(line)-len(" main")])
			}
			autoPkgType = "program"
			break
		}
	}

	log.Printf("Determining dependencies\n")

	cmd = exec.Command("go", "list", "-f", "{{join .Imports \"\\n\"}}\n{{join .TestImports \"\\n\"}}\n{{join .XTestImports \"\\n\"}}", gopkg+"/...")
	cmd.Stderr = os.Stderr
	cmd.Env = append([]string{
		fmt.Sprintf("GOPATH=%s", tempdir),
	}, passthroughEnv()...)

	out, err = cmd.Output()
	if err != nil {
		return "", "", dependencies, autoPkgType, err
	}

	var godependencies []string
	for _, p := range strings.Split(string(out), "\n") {
		if strings.TrimSpace(p) == "" {
			continue
		}
		// Strip packages that are included in the repository we are packaging.
		if strings.HasPrefix(p, gopkg) {
			continue
		}
		if p == "C" {
			// TODO: maybe parse the comments to figure out C deps from pkg-config files?
		} else {
			godependencies = append(godependencies, p)
		}
	}

	if len(godependencies) == 0 {
		return tempfile, version, dependencies, autoPkgType, nil
	}

	// Remove all packages which are in the standard lib.
	args := []string{"list", "-f", "{{.ImportPath}}: {{.Standard}}"}
	args = append(args, godependencies...)

	cmd = exec.Command("go", args...)
	cmd.Dir = filepath.Join(tempdir, "src", gopkg)
	cmd.Stderr = os.Stderr
	cmd.Env = append([]string{
		fmt.Sprintf("GOPATH=%s", tempdir),
	}, passthroughEnv()...)

	out, err = cmd.Output()
	if err != nil {
		return "", "", dependencies, autoPkgType, err
	}

	for _, p := range strings.Split(string(out), "\n") {
		if strings.HasSuffix(p, ": false") {
			importpath := p[:len(p)-len(": false")]
			rr, err := vcs.RepoRootForImportPath(importpath, false)
			if err != nil {
				log.Printf("Could not determine repo path for import path %q: %v\n", importpath, err)
			}
			dependencies[debianNameFromGopkg(rr.Root, "library")+"-dev"] = true
		}
	}
	return tempfile, version, dependencies, autoPkgType, nil
}
开发者ID:Debian,项目名称:dh-make-golang,代码行数:101,代码来源:make.go


示例17: fetchRoot

func (p *Plug) fetchRoot() (*vcs.RepoRoot, error) {
	return vcs.RepoRootForImportPath(p.Repo, false)
}
开发者ID:mijime,项目名称:gplum,代码行数:3,代码来源:plug.go


示例18: LoadDependencies

// LoadDependencies is not done
func LoadDependencies(pkgs []string, ignores []string) ([]Dependency, error) {

	stdlib, err := golist.Std()
	if err != nil {
		return nil, err
	}

	pkgs, err = golist.Deps(pkgs...)
	if err != nil {
		return nil, err
	}

	// faster to remove stdlib
	pkgs = removeIfEquals(pkgs, stdlib)
	pkgs = removeIfSubstring(pkgs, ignores)

	deps, err := golist.Packages(pkgs...)
	if err != nil {
		return nil, err
	}

	visited := make(map[string]string, len(deps))

	out := make([]Dependency, 0, len(deps))
	for _, v := range deps {
		src := filepath.Join(v.Root, "src")
		path := filepath.Join(src, filepath.FromSlash(v.ImportPath))
		cmd, _, err := vcs.FromDir(path, src)
		if err != nil {
			log.Printf("error computing vcs %s: %s", path, err)
			continue
		}
		rr, err := vcs.RepoRootForImportPath(v.ImportPath, false)
		if err != nil {
			log.Printf("error computing repo for %s: %s", v.ImportPath, err)
			continue
		}
		e := Dependency{
			Package: v,
		}
		e.Project.Repo = rr.Repo
		e.Project.VcsName = cmd.Name
		e.Project.VcsCmd = cmd.Cmd
		e.License = GetLicense(path)
		visited[v.ImportPath] = e.License.Type

		// if child have no license, parent has license, continue
		// if child has no license, parent has no license, carry on
		if e.License.Type == "" {
			lic, ok := visited[rr.Root]
			if ok && lic != "" {
				// case is child has no license, but parent does
				// => just ignore this package
				continue
			}
			// if ok && lic = "" => dont look up parent

			if !ok {
				// first time checking parent
				parentpkg, err := golist.GetPackage(rr.Root)
				if err == nil {
					parent := Dependency{
						Package: parentpkg,
						Project: e.Project,
					}
					path = filepath.Join(src, filepath.FromSlash(rr.Root))
					parent.License = GetLicense(path)
					visited[rr.Root] = parent.License.Type
					if parent.License.Type != "" {
						// case child has no license, parent does
						//  ignore child and use parent
						e = parent
					}
				}
			}
		}
		commit, err := GetLastCommit(path)
		if err == nil {
			e.Commit = commit
		}

		e.Project.LicenseLink = LinkToFile(e.ImportPath, e.License.File, e.Commit.Rev)

		out = append(out, e)
	}
	return out, err
}
开发者ID:mehulsbhatt,项目名称:gosupplychain,代码行数:88,代码来源:dependency.go


示例19: CheckHandler

// CheckHandler handles the request for checking a repo
func CheckHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	repo := r.FormValue("repo")

	repoRoot, err := vcs.RepoRootForImportPath(repo, true)
	if err != nil || repoRoot.Root == "" || repoRoot.Repo == "" {
		log.Println("Failed to create repoRoot:", repoRoot, err)
		b, marshalErr := json.Marshal("Please enter a valid 'go get'-able package name")
		if marshalErr != nil {
			log.Println("JSON marshal error:", marshalErr)
		}
		w.WriteHeader(http.StatusBadRequest)
		w.Write(b)
		return
	}

	log.Printf("Checking repo %q...", repo)

	forceRefresh := r.Method != "GET" // if this is a GET request, try to fetch from cached version in boltdb first
	resp, err := newChecksResp(repo, forceRefresh)
	if err != nil {
		log.Println("ERROR: from newChecksResp:", err)
		b, marshalErr := json.Marshal("Could not go get the repository.")
		if marshalErr != nil {
			log.Println("JSON marshal error:", marshalErr)
		}
		w.WriteHeader(http.StatusBadRequest)
		w.Write(b)
		return
	}

	respBytes, err := json.Marshal(resp)
	if err != nil {
		log.Println("ERROR: could not marshal json:", err)
		http.Error(w, err.Error(), 500)
		return
	}
	w.Write(respBytes)

	// write to boltdb
	db, err := bolt.Open(DBPath, 0755, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		log.Println("Failed to open bolt database: ", err)
		return
	}
	defer db.Close()

	// is this a new repo? if so, increase the count in the high scores bucket later
	isNewRepo := false
	err = db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(RepoBucket))
		if b == nil {
			return fmt.Errorf("repo bucket not found")
		}
		isNewRepo = b.Get([]byte(repo)) == nil
		return nil
	})
	if err != nil {
		log.Println(err)
	}

	// if this is a new repo, or the user force-refreshed, update the cache
	if isNewRepo || forceRefresh {
		err = db.Update(func(tx *bolt.Tx) error {
			log.Printf("Saving repo %q to cache...", repo)

			b := tx.Bucket([]byte(RepoBucket))
			if b == nil {
				return fmt.Errorf("repo bucket not found")
			}

			// save repo to cache
			err = b.Put([]byte(repo), respBytes)
			if err != nil {
				return err
			}

			// fetch meta-bucket
			mb := tx.Bucket([]byte(MetaBucket))
			if mb == nil {
				return fmt.Errorf("high score bucket not found")
			}

			// update total repos count
			if isNewRepo {
				err = updateReposCount(mb, resp, repo)
				if err != nil {
					return err
				}
			}

			return updateHighScores(mb, resp, repo)
		})

		if err != nil {
			log.Println("Bolt writing error:", err)
		}
	}
//.........这里部分代码省略.........
开发者ID:winhowes,项目名称:goreportcard,代码行数:101,代码来源:check.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang godoc.Presentation类代码示例发布时间:2022-05-28
下一篇:
Golang typeutil.MethodSetCache类代码示例发布时间: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