本文整理汇总了Golang中v/io/jiri/collect.Error函数的典型用法代码示例。如果您正苦于以下问题:Golang Error函数的具体用法?Golang Error怎么用?Golang Error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: hostCredentials
// hostCredentials returns credentials for the given Gerrit host. The
// function uses best effort to scan common locations where the
// credentials could exist.
func hostCredentials(seq runutil.Sequence, hostUrl *url.URL) (_ *credentials, e error) {
// Look for the host credentials in the .netrc file.
netrcPath := filepath.Join(os.Getenv("HOME"), ".netrc")
file, err := seq.Open(netrcPath)
if err != nil {
if !runutil.IsNotExist(err) {
return nil, err
}
} else {
defer collect.Error(func() error { return file.Close() }, &e)
credsMap, err := parseNetrcFile(file)
if err != nil {
return nil, err
}
creds, ok := credsMap[hostUrl.Host]
if ok {
return creds, nil
}
}
// Look for the host credentials in the git cookie file.
args := []string{"config", "--get", "http.cookiefile"}
var stdout, stderr bytes.Buffer
if err := seq.Capture(&stdout, &stderr).Last("git", args...); err == nil {
cookieFilePath := strings.TrimSpace(stdout.String())
file, err := seq.Open(cookieFilePath)
if err != nil {
if !runutil.IsNotExist(err) {
return nil, err
}
} else {
defer collect.Error(func() error { return file.Close() }, &e)
credsMap, err := parseGitCookieFile(file)
if err != nil {
return nil, err
}
creds, ok := credsMap[hostUrl.Host]
if ok {
return creds, nil
}
// Account for site-wide credentials. Namely, the git cookie
// file can contain credentials of the form ".<name>", which
// should match any host "*.<name>".
for host, creds := range credsMap {
if strings.HasPrefix(host, ".") && strings.HasSuffix(hostUrl.Host, host) {
return creds, nil
}
}
}
}
return nil, fmt.Errorf("cannot find credentials for %q", hostUrl.String())
}
示例2: runRebuild
func runRebuild(jirix *jiri.X, args []string) (e error) {
projects, tools, err := project.LoadManifest(jirix)
if err != nil {
return err
}
// Create a temporary directory in which tools will be built.
tmpDir, err := jirix.NewSeq().TempDir("", "tmp-jiri-rebuild")
if err != nil {
return fmt.Errorf("TempDir() failed: %v", err)
}
// Make sure we cleanup the temp directory.
defer collect.Error(func() error { return jirix.NewSeq().RemoveAll(tmpDir).Done() }, &e)
// Paranoid sanity checking.
if _, ok := tools[project.JiriName]; !ok {
return fmt.Errorf("tool %q not found", project.JiriName)
}
// Build and install tools.
if err := project.BuildTools(jirix, projects, tools, tmpDir); err != nil {
return err
}
return project.InstallTools(jirix, tmpDir)
}
示例3: commitAndPushChanges
// commitAndPushChanges commits changes identified by the given manifest file
// and label to the containing repository and pushes these changes to the
// remote repository.
func commitAndPushChanges(jirix *jiri.X, snapshotDir, snapshotFile, label string) (e error) {
cwd, err := os.Getwd()
if err != nil {
return err
}
defer collect.Error(func() error { return jirix.NewSeq().Chdir(cwd).Done() }, &e)
if err := jirix.NewSeq().Chdir(snapshotDir).Done(); err != nil {
return err
}
relativeSnapshotPath := strings.TrimPrefix(snapshotFile, snapshotDir+string(os.PathSeparator))
git := gitutil.New(jirix.NewSeq())
// Pull from master so we are up-to-date.
if err := git.Pull("origin", "master"); err != nil {
return err
}
if err := git.Add(relativeSnapshotPath); err != nil {
return err
}
if err := git.Add(label); err != nil {
return err
}
name := strings.TrimPrefix(snapshotFile, snapshotDir)
if err := git.CommitNoVerify(fmt.Sprintf("adding snapshot %q for label %q", name, label)); err != nil {
return err
}
if err := git.Push("origin", "master", gitutil.VerifyOpt(false)); err != nil {
return err
}
return nil
}
示例4: writeMetadata
// writeMetadata stores the given project metadata in the directory
// identified by the given path.
func writeMetadata(ctx *tool.Context, project Project, dir string) (e error) {
metadataDir := filepath.Join(dir, metadataDirName)
cwd, err := os.Getwd()
if err != nil {
return err
}
defer collect.Error(func() error { return ctx.Run().Chdir(cwd) }, &e)
if err := ctx.Run().MkdirAll(metadataDir, os.FileMode(0755)); err != nil {
return err
}
if err := ctx.Run().Chdir(metadataDir); err != nil {
return err
}
// Replace absolute project paths with relative paths to make it
// possible to move the $JIRI_ROOT directory locally.
relPath, err := ToRel(project.Path)
if err != nil {
return err
}
project.Path = relPath
bytes, err := xml.Marshal(project)
if err != nil {
return fmt.Errorf("Marhsal() failed: %v", err)
}
metadataFile := filepath.Join(metadataDir, metadataFileName)
tmpMetadataFile := metadataFile + ".tmp"
if err := ctx.Run().WriteFile(tmpMetadataFile, bytes, os.FileMode(0644)); err != nil {
return err
}
if err := ctx.Run().Rename(tmpMetadataFile, metadataFile); err != nil {
return err
}
return nil
}
示例5: invoke
// invoke invokes the Jenkins API using the given suffix, values and
// HTTP method.
func (j *Jenkins) invoke(method, suffix string, values url.Values) (_ []byte, err error) {
// Return mock result in test mode.
if j.testMode {
return j.invokeMockResults[suffix], nil
}
apiURL, err := url.Parse(j.host)
if err != nil {
return nil, fmt.Errorf("Parse(%q) failed: %v", j.host, err)
}
apiURL.Path = fmt.Sprintf("%s/%s", apiURL.Path, suffix)
apiURL.RawQuery = values.Encode()
var body io.Reader
url, body := apiURL.String(), nil
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, fmt.Errorf("NewRequest(%q, %q, %v) failed: %v", method, url, body, err)
}
req.Header.Add("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Do(%v) failed: %v", req, err)
}
defer collect.Error(func() error { return res.Body.Close() }, &err)
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
// queue/cancelItem API returns 404 even successful.
// See: https://issues.jenkins-ci.org/browse/JENKINS-21311.
if suffix != "queue/cancelItem" && res.StatusCode >= http.StatusBadRequest {
return nil, fmt.Errorf("HTTP request %q returned %d:\n%s", url, res.StatusCode, string(bytes))
}
return bytes, nil
}
示例6: setProjectRevisions
// setProjectRevisions sets the current project revision from the master for
// each project as found on the filesystem
func setProjectRevisions(ctx *tool.Context, projects Projects) (_ Projects, e error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
defer collect.Error(func() error { return ctx.Run().Chdir(cwd) }, &e)
for name, project := range projects {
switch project.Protocol {
case "git":
if err := ctx.Run().Chdir(project.Path); err != nil {
return nil, err
}
revision, err := ctx.Git().CurrentRevisionOfBranch("master")
if err != nil {
return nil, err
}
project.Revision = revision
default:
return nil, UnsupportedProtocolErr(project.Protocol)
}
projects[name] = project
}
return projects, nil
}
示例7: SetTopic
// SetTopic sets the topic of the given Gerrit reference.
func (g *Gerrit) SetTopic(cl string, opts CLOpts) (e error) {
cred, err := hostCredentials(g.r, g.host)
if err != nil {
return err
}
topic := Topic{opts.Topic}
data, err := json.Marshal(topic)
if err != nil {
return fmt.Errorf("Marshal(%#v) failed: %v", topic, err)
}
url := fmt.Sprintf("%s/a/changes/%s/topic", g.host, cl)
method, body := "PUT", bytes.NewReader(data)
req, err := http.NewRequest(method, url, body)
if err != nil {
return fmt.Errorf("NewRequest(%q, %q, %v) failed: %v", method, url, body, err)
}
req.Header.Add("Content-Type", "application/json;charset=UTF-8")
req.SetBasicAuth(cred.username, cred.password)
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("Do(%v) failed: %v", req, err)
}
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusNoContent {
return fmt.Errorf("SetTopic:Do(%v) failed: %v", req, res.StatusCode)
}
defer collect.Error(func() error { return res.Body.Close() }, &e)
return nil
}
示例8: UpdateUniverse
// UpdateUniverse updates all local projects and tools to match the
// remote counterparts identified by the given manifest. Optionally,
// the 'gc' flag can be used to indicate that local projects that no
// longer exist remotely should be removed.
func UpdateUniverse(ctx *tool.Context, gc bool) (e error) {
ctx.TimerPush("update universe")
defer ctx.TimerPop()
_, remoteProjects, remoteTools, remoteHooks, err := readManifest(ctx, true)
if err != nil {
return err
}
// 1. Update all local projects to match their remote counterparts.
if err := updateProjects(ctx, remoteProjects, gc); err != nil {
return err
}
// 2. Build all tools in a temporary directory.
tmpDir, err := ctx.Run().TempDir("", "tmp-jiri-tools-build")
if err != nil {
return fmt.Errorf("TempDir() failed: %v", err)
}
defer collect.Error(func() error { return ctx.Run().RemoveAll(tmpDir) }, &e)
if err := buildToolsFromMaster(ctx, remoteTools, tmpDir); err != nil {
return err
}
// 3. Install the tools into $JIRI_ROOT/devtools/bin.
if err := InstallTools(ctx, tmpDir); err != nil {
return err
}
// 4. Run all specified hooks
return runHooks(ctx, remoteHooks)
}
示例9: Query
// Query returns a list of QueryResult entries matched by the given
// Gerrit query string from the given Gerrit instance. The result is
// sorted by the last update time, most recently updated to oldest
// updated.
//
// See the following links for more details about Gerrit search syntax:
// - https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
// - https://gerrit-review.googlesource.com/Documentation/user-search.html
func (g *Gerrit) Query(query string) (_ []Change, e error) {
cred, err := hostCredentials(g.r, g.host)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/a/changes/?o=CURRENT_REVISION&o=CURRENT_COMMIT&o=LABELS&o=DETAILED_ACCOUNTS&q=%s", g.host, url.QueryEscape(query))
var body io.Reader
method, body := "GET", nil
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, fmt.Errorf("NewRequest(%q, %q, %v) failed: %v", method, url, body, err)
}
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(cred.username, cred.password)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Do(%v) failed: %v", req, err)
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Query:Do(%v) failed: %v", req, res.StatusCode)
}
defer collect.Error(func() error { return res.Body.Close() }, &e)
return parseQueryResults(res.Body)
}
示例10: revisionChanges
// revisionChanges commits changes identified by the given manifest
// file and label to the manifest repository and (if applicable)
// pushes these changes to the remote repository.
func revisionChanges(ctx *tool.Context, snapshotDir, snapshotFile, label string) (e error) {
cwd, err := os.Getwd()
if err != nil {
return err
}
defer collect.Error(func() error { return ctx.Run().Chdir(cwd) }, &e)
if err := ctx.Run().Chdir(snapshotDir); err != nil {
return err
}
relativeSnapshotPath := strings.TrimPrefix(snapshotFile, snapshotDir+string(os.PathSeparator))
if err := ctx.Git().Add(relativeSnapshotPath); err != nil {
return err
}
if err := ctx.Git().Add(label); err != nil {
return err
}
name := strings.TrimPrefix(snapshotFile, snapshotDir)
if err := ctx.Git().CommitWithMessage(fmt.Sprintf("adding snapshot %q for label %q", name, label)); err != nil {
return err
}
if remoteFlag {
if err := ctx.Git().Push("origin", "master", gitutil.VerifyOpt(false)); err != nil {
return err
}
}
return nil
}
示例11: reportNonMaster
// reportNonMaster checks if the given project is on master branch and
// if not, reports this fact along with information on how to update it.
func reportNonMaster(ctx *tool.Context, project Project) (e error) {
cwd, err := os.Getwd()
if err != nil {
return err
}
defer collect.Error(func() error { return ctx.Run().Chdir(cwd) }, &e)
if err := ctx.Run().Chdir(project.Path); err != nil {
return err
}
switch project.Protocol {
case "git":
current, err := ctx.Git().CurrentBranchName()
if err != nil {
return err
}
if current != "master" {
line1 := fmt.Sprintf(`NOTE: "jiri update" only updates the "master" branch and the current branch is %q`, current)
line2 := fmt.Sprintf(`to update the %q branch once the master branch is updated, run "git merge master"`, current)
opts := runutil.Opts{Verbose: true}
ctx.Run().OutputWithOpts(opts, []string{line1, line2})
}
return nil
default:
return UnsupportedProtocolErr(project.Protocol)
}
}
示例12: runRebuild
func runRebuild(env *cmdline.Env, args []string) (e error) {
ctx := tool.NewContextFromEnv(env)
_, tools, err := project.ReadManifest(ctx)
if err != nil {
return err
}
// Create a temporary directory in which tools will be built.
tmpDir, err := ctx.Run().TempDir("", "tmp-jiri-rebuild")
if err != nil {
return fmt.Errorf("TempDir() failed: %v", err)
}
// Make sure we cleanup the temp directory.
defer collect.Error(func() error { return ctx.Run().RemoveAll(tmpDir) }, &e)
// Paranoid sanity checking.
if _, ok := tools[project.JiriName]; !ok {
return fmt.Errorf("tool %q not found", project.JiriName)
}
// Build and install tools.
if err := project.BuildTools(ctx, tools, tmpDir); err != nil {
return err
}
return project.InstallTools(ctx, tmpDir)
}
示例13: ApplyToLocalMaster
// ApplyToLocalMaster applies an operation expressed as the given function to
// the local master branch of the given projects.
func ApplyToLocalMaster(ctx *tool.Context, projects Projects, fn func() error) (e error) {
cwd, err := os.Getwd()
if err != nil {
return err
}
defer collect.Error(func() error { return ctx.Run().Chdir(cwd) }, &e)
// Loop through all projects, checking out master and stashing any unstaged
// changes.
for _, project := range projects {
p := project
if err := ctx.Run().Chdir(p.Path); err != nil {
return err
}
switch p.Protocol {
case "git":
branch, err := ctx.Git().CurrentBranchName()
if err != nil {
return err
}
stashed, err := ctx.Git().Stash()
if err != nil {
return err
}
if err := ctx.Git().CheckoutBranch("master"); err != nil {
return err
}
// After running the function, return to this project's directory,
// checkout the original branch, and stash pop if necessary.
defer collect.Error(func() error {
if err := ctx.Run().Chdir(p.Path); err != nil {
return err
}
if err := ctx.Git().CheckoutBranch(branch); err != nil {
return err
}
if stashed {
return ctx.Git().StashPop()
}
return nil
}, &e)
default:
return UnsupportedProtocolErr(p.Protocol)
}
}
return fn()
}
示例14: listCommitters
func listCommitters(ctx *tool.Context) (_ []string, e error) {
branch, err := ctx.Git().CurrentBranchName()
if err != nil {
return nil, err
}
stashed, err := ctx.Git().Stash()
if err != nil {
return nil, err
}
if stashed {
defer collect.Error(func() error { return ctx.Git().StashPop() }, &e)
}
if err := ctx.Git().CheckoutBranch("master"); err != nil {
return nil, err
}
defer collect.Error(func() error { return ctx.Git().CheckoutBranch(branch) }, &e)
return ctx.Git().Committers()
}
示例15: Submit
// Submit submits the given changelist through Gerrit.
func (g *Gerrit) Submit(changeID string) (e error) {
cred, err := hostCredentials(g.r, g.host)
if err != nil {
return err
}
// Encode data needed for Submit.
data := struct {
WaitForMerge bool `json:"wait_for_merge"`
}{
WaitForMerge: true,
}
encodedBytes, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("Marshal(%#v) failed: %v", data, err)
}
// Call Submit API.
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-change
url := fmt.Sprintf("%s/a/changes/%s/submit", g.host, changeID)
var body io.Reader
method, body := "POST", bytes.NewReader(encodedBytes)
req, err := http.NewRequest(method, url, body)
if err != nil {
return fmt.Errorf("NewRequest(%q, %q, %v) failed: %v", method, url, body, err)
}
req.Header.Add("Content-Type", "application/json;charset=UTF-8")
req.SetBasicAuth(cred.username, cred.password)
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("Do(%v) failed: %v", req, err)
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("Submit:Do(%v) failed: %v", req, res.StatusCode)
}
defer collect.Error(func() error { return res.Body.Close() }, &e)
// Check response.
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
resContent := string(bytes)
// For a "TBR" CL, the response code is not 200 but the submit will still succeed.
// In those cases, the "error" message will be "change is new".
// We don't treat this case as error.
if res.StatusCode != http.StatusOK && strings.TrimSpace(resContent) != "change is new" {
return fmt.Errorf("Failed to submit CL %q:\n%s", changeID, resContent)
}
return nil
}