// Logs in to github using oauth. // Returns error if login fails. func Login(userkey string) error { file, err := ioutil.ReadFile(*Path + ".issue/config.json") if err != nil { GitLog.Println("open config: ", err) os.Exit(1) } temp := new(Config) if err = json.Unmarshal(file, temp); err != nil { GitLog.Println("parse config: ", err) os.Exit(1) } Conf = temp token := Conf.Token if Conf.Secure { key := []byte(userkey) token = encrypt.Decrypt(key, token) } ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) client = github.NewClient(tc) user, _, err := client.Users.Get("") if err != nil { GitLog.Printf("\nerror: %v\n", err) return err } log.Printf("\nLogged into: %v\n", github.Stringify(user.Login)) GitLog.Print("Logged into: ", github.Stringify(user.Login)) return nil }
func main() { r := bufio.NewReader(os.Stdin) fmt.Print("GitHub Username: "******"GitHub Password: "******"") // Is this a two-factor auth error? If so, prompt for OTP and try again. if _, ok := err.(*github.TwoFactorAuthError); err != nil && ok { fmt.Print("\nGitHub OTP: ") otp, _ := r.ReadString('\n') tp.OTP = strings.TrimSpace(otp) user, _, err = client.Users.Get("") } if err != nil { fmt.Printf("\nerror: %v\n", err) return } fmt.Printf("\n%v\n", github.Stringify(user)) }
func (b *Bot) CommentGithub(owner, repo string, number int, comment string) error { prc, res, err := b.gh.Issues.CreateComment(owner, repo, number, &github.IssueComment{ Body: &comment, }) defer closeRes(res) if err != nil { return err } log.Printf("Got: %v, %v, %v", github.Stringify(prc), res, err) return nil }
func (b *Bot) CheckPulls(owner, repo string) error { pulls, res, err := b.gh.PullRequests.List(owner, repo, nil) defer closeRes(res) if err != nil { return err } log.Printf("%d pulls", len(pulls)) for _, pr := range pulls { log.Printf("PR: %v", github.Stringify(pr)) } return nil }
func ExampleRepositoriesService_List() { client := github.NewClient(nil) user := "******" opt := &github.RepositoryListOptions{Type: "owner", Sort: "updated", Direction: "desc"} repos, _, err := client.Repositories.List(user, opt) if err != nil { fmt.Println(err) } fmt.Printf("Recently updated repositories by %q: %v", user, github.Stringify(repos)) }
func main() { fmt.Println("Recently updated repositories owned by user ramtiga:") t := &oauth.Transport{ Token: &oauth.Token{AccessToken: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, } client := github.NewClient(t.Client()) opt := &github.RepositoryListOptions{Type: "owner", Sort: "updated", Direction: "desc"} repos, _, err := client.Repositories.List("", opt) if err != nil { fmt.Printf("error: %v\n\n", err) } else { fmt.Printf("%v\n\n", github.Stringify(repos)) } }
func runGH( input io.Reader, createIssue func(owner string, repo string, issue *github.IssueRequest) (*github.Issue, *github.Response, error), ) error { sha, ok := os.LookupEnv(teamcityVCSNumberEnv) if !ok { return errors.Errorf("VCS number environment variable %s is not set", teamcityVCSNumberEnv) } suites, err := lib.ParseGotest(input, "") if err != nil { return errors.Wrap(err, "failed to parse `go test` output") } for _, suite := range suites { for _, test := range suite.Tests { switch test.Status { case lib.Failed: title := fmt.Sprintf("%s: %s failed under stress", suite.Name, test.Name) body := fmt.Sprintf(`SHA: https://github.com/cockroachdb/cockroach/commits/%s Stress build found a failed test: %s`, sha, "```\n"+test.Message+"\n```") issueRequest := &github.IssueRequest{ Title: &title, Body: &body, Labels: &[]string{ "Robot", "test-failure", }, } if _, _, err := createIssue("cockroachdb", "cockroach", issueRequest); err != nil { return errors.Wrapf(err, "failed to create GitHub issue %s", github.Stringify(issueRequest)) } } } } return nil }
func main() { client := github.NewClient(nil) fmt.Println("Recently updated repositories owned by user willnorris:") opt := &github.RepositoryListOptions{Type: "owner", Sort: "updated", Direction: "desc"} repos, _, err := client.Repositories.List("willnorris", opt) if err != nil { fmt.Printf("error: %v\n\n", err) } else { fmt.Printf("%v\n\n", github.Stringify(repos)) } rate, _, err := client.RateLimit() if err != nil { fmt.Printf("Error fetching rate limit: %#v\n\n", err) } else { fmt.Printf("API Rate Limit: %#v\n\n", rate) } }
func runGH( input io.Reader, createIssue func(owner string, repo string, issue *github.IssueRequest) (*github.Issue, *github.Response, error), ) error { sha, ok := os.LookupEnv(teamcityVCSNumberEnv) if !ok { return errors.Errorf("VCS number environment variable %s is not set", teamcityVCSNumberEnv) } buildID, ok := os.LookupEnv(teamcityBuildIDEnv) if !ok { log.Fatalf("teamcity build ID environment variable %s is not set", teamcityBuildIDEnv) } serverURL, ok := os.LookupEnv(teamcityServerURLEnv) if !ok { log.Fatalf("teamcity server URL environment variable %s is not set", teamcityServerURLEnv) } options := url.Values{} options.Add("buildId", buildID) options.Add("tab", "buildLog") u, err := url.Parse(serverURL) if err != nil { log.Fatal(err) } u.Scheme = "https" u.Path = "viewLog.html" u.RawQuery = options.Encode() var inputBuf bytes.Buffer input = io.TeeReader(input, &inputBuf) var parameters []string for _, parameter := range []string{ propEvalKVEnv, tagsEnv, goFlagsEnv, } { if val, ok := os.LookupEnv(parameter); ok { parameters = append(parameters, parameter+"="+val) } } newIssueRequest := func(packageName, testName, message string) *github.IssueRequest { title := fmt.Sprintf("%s: %s failed under stress", packageName, testName) body := fmt.Sprintf(`SHA: https://github.com/cockroachdb/cockroach/commits/%s Parameters: %s Stress build found a failed test: %s %s`, sha, "```\n"+strings.Join(parameters, "\n")+"\n```", u.String(), "```\n%s\n```") // We insert a raw "%s" above so we can figure out the length of the // body so far, without the actual error text. We need this length so we // can calculate the maximum amount of error text we can include in the // issue without exceeding GitHub's limit. We replace that %s in the // following Sprintf. body = fmt.Sprintf(body, trimIssueRequestBody(message, len(body))) return &github.IssueRequest{ Title: &title, Body: &body, Labels: &[]string{ "Robot", "test-failure", }, } } suites, err := lib.ParseGotest(input, "") if err != nil { return errors.Wrap(err, "failed to parse `go test` output") } posted := false for _, suite := range suites { packageName := suite.Name if packageName == "" { var ok bool packageName, ok = os.LookupEnv(pkgEnv) if !ok { log.Fatalf("package name environment variable %s is not set", pkgEnv) } } for _, test := range suite.Tests { switch test.Status { case lib.Failed: issueRequest := newIssueRequest(packageName, test.Name, test.Message) if _, _, err := createIssue("cockroachdb", "cockroach", issueRequest); err != nil { return errors.Wrapf(err, "failed to create GitHub issue %s", github.Stringify(issueRequest)) } posted = true } } } const unknown = "(unknown)" if !posted { packageName, ok := os.LookupEnv(pkgEnv) if !ok { packageName = unknown } issueRequest := newIssueRequest(packageName, unknown, inputBuf.String()) if _, _, err := createIssue("cockroachdb", "cockroach", issueRequest); err != nil { return errors.Wrapf(err, "failed to create GitHub issue %s", github.Stringify(issueRequest)) } } return nil }
func release(releaseName string, releaseAssets []string, options *commandLineOptions) { if options.Prerelease { log.Printf("Creating prerelease %s for repository: %s", releaseName, options.GithubRepository) } else { log.Printf("Creating release %s for repository: %s", releaseName, options.GithubRepository) } // Split the repository into two parts (owner and repository) repositoryParts := strings.Split(options.GithubRepository, "/") if len(repositoryParts) != 2 { exitAndError("github-repository is in the wrong format") } // If no tag was provided, use the name of the release tagName := options.Tag if tagName == "" { tagName = releaseName } // log.Printf("%s", repos) // log.Printf("name: %s", releaseName) // log.Printf("assets: %s", releaseAssets) // log.Printf("commit: %s", options.Commit) // log.Printf("tag: %s", tag) // Create an oAuth Token Source ts := &tokenSource{ &oauth2.Token{AccessToken: options.GithubAccessToken}, } // New oAuth client tc := oauth2.NewClient(oauth2.NoContext, ts) // Github Client client := github.NewClient(tc) // Create an object that represents the release release := &github.RepositoryRelease{ Name: &releaseName, TagName: &tagName, TargetCommitish: &options.Commit, Prerelease: &options.Prerelease, } // Create the GitHub release createdRelease, _, err := client.Repositories.CreateRelease(repositoryParts[0], repositoryParts[1], release) if err != nil { log.Fatalf("Failed to create release (%T %v)", err, err) } // log.Printf("DEBUG: %s", github.Stringify(createdRelease)) // Start uploading the assets for i := 0; i < len(releaseAssets); i++ { fileName := releaseAssets[i] file, err := os.Open(fileName) if err != nil { log.Fatalf("Could not open file \"%s\" (%T %v)", fileName, err, err) } releaseAssetOptions := &github.UploadOptions{Name: filepath.Base(fileName)} createdReleaseAsset, _, err := client.Repositories.UploadReleaseAsset(repositoryParts[0], repositoryParts[1], *createdRelease.ID, releaseAssetOptions, file) if err != nil { log.Fatalf("Failed to upload asset \"%s\" (%T %v)", fileName, err, err) } log.Printf("Successfully uploaded asset: %s", github.Stringify(createdReleaseAsset.URL)) } log.Printf("Successfully created release: %s", github.Stringify(createdRelease.HTMLURL)) }
func runGH( input io.Reader, createIssue func(owner string, repo string, issue *github.IssueRequest) (*github.Issue, *github.Response, error), ) error { sha, ok := os.LookupEnv(teamcityVCSNumberEnv) if !ok { return errors.Errorf("VCS number environment variable %s is not set", teamcityVCSNumberEnv) } host, ok := os.LookupEnv(teamcityServerURLEnv) if !ok { log.Fatalf("teamcity server URL environment variable %s is not set", teamcityServerURLEnv) } buildID, ok := os.LookupEnv(teamcityBuildIDEnv) if !ok { log.Fatalf("teamcity build ID environment variable %s is not set", teamcityBuildIDEnv) } var inputBuf bytes.Buffer input = io.TeeReader(input, &inputBuf) options := url.Values{} options.Add("buildId", buildID) u := (&url.URL{ Scheme: "https", Host: host, Path: "viewLog.html", RawQuery: options.Encode(), }).String() newIssueRequest := func(packageName, testName, message string) *github.IssueRequest { title := fmt.Sprintf("%s: %s failed under stress", packageName, testName) body := fmt.Sprintf(`SHA: https://github.com/cockroachdb/cockroach/commits/%s Stress build found a failed test: %s %s`, sha, u, "```\n"+trimIssueRequestBody(message)+"\n```") return &github.IssueRequest{ Title: &title, Body: &body, Labels: &[]string{ "Robot", "test-failure", }, } } suites, err := lib.ParseGotest(input, "") if err != nil { return errors.Wrap(err, "failed to parse `go test` output") } posted := false for _, suite := range suites { packageName := suite.Name if packageName == "" { var ok bool packageName, ok = os.LookupEnv(pkgEnv) if !ok { log.Fatalf("package name environment variable %s is not set", pkgEnv) } } for _, test := range suite.Tests { switch test.Status { case lib.Failed: issueRequest := newIssueRequest(packageName, test.Name, test.Message) if _, _, err := createIssue("cockroachdb", "cockroach", issueRequest); err != nil { return errors.Wrapf(err, "failed to create GitHub issue %s", github.Stringify(issueRequest)) } posted = true } } } if !posted { issueRequest := newIssueRequest("(unknown)", "(unknown)", inputBuf.String()) if _, _, err := createIssue("cockroachdb", "cockroach", issueRequest); err != nil { return errors.Wrapf(err, "failed to create GitHub issue %s", github.Stringify(issueRequest)) } } return nil }
func (h HookSchema) String() string { return github.Stringify(h) }