diff --git a/api/client.go b/api/client.go index 8e431be1a..a7ea0636c 100644 --- a/api/client.go +++ b/api/client.go @@ -56,10 +56,11 @@ func graphQL(query string, variables map[string]string, v interface{}) error { return err } - token, err := context.GetToken() + ctx, err := context.GetContext() if err != nil { return err } + token := ctx.Token req.Header.Set("Authorization", "token "+token) req.Header.Set("Content-Type", "application/json; charset=utf-8") diff --git a/api/queries.go b/api/queries.go index 51fe5d700..a72b75189 100644 --- a/api/queries.go +++ b/api/queries.go @@ -79,22 +79,18 @@ func PullRequests() (PullRequestsPayload, error) { } ` - ghRepo, rerr := context.CurrentGitHubRepository() - if rerr != nil { - return PullRequestsPayload{}, nil - } - - owner := ghRepo.Owner - repo := ghRepo.Name - currentBranch, cberr := context.CurrentBranch() - if cberr != nil { - return PullRequestsPayload{}, cberr - } - currentUsername, err := context.CurrentUsername() + ctx, err := context.GetContext() if err != nil { return PullRequestsPayload{}, err } + ghRepo := ctx.GHRepo + currentBranch := ctx.Branch + currentUsername := ctx.Username + + owner := ghRepo.Owner + repo := ghRepo.Name + viewerQuery := fmt.Sprintf("repo:%s/%s state:open is:pr author:%s", owner, repo, currentUsername) reviewerQuery := fmt.Sprintf("repo:%s/%s state:open review-requested:%s", owner, repo, currentUsername) diff --git a/context/context.go b/context/context.go index 85af0d8f9..ea9234a39 100644 --- a/context/context.go +++ b/context/context.go @@ -1,6 +1,7 @@ package context import ( + "fmt" "io/ioutil" "os/user" "regexp" @@ -10,6 +11,13 @@ import ( "github.com/github/gh-cli/github" ) +type Context struct { + Token string + Username string + Branch string + GHRepo *GitHubRepository +} + // GetToken returns the authentication token as stored in the config file for the user running gh-cli func GetToken() (string, error) { usr, err := user.Current() @@ -43,3 +51,44 @@ func CurrentBranch() (string, error) { return strings.Replace(currentBranch, "refs/heads/", "", 1), nil } + +func GetContext() (*Context, error) { + errors := []error{} + token, terr := GetToken() + if terr != nil { + errors = append(errors, terr) + } + + username, uerr := CurrentUsername() + if uerr != nil { + errors = append(errors, uerr) + } + + branch, berr := CurrentBranch() + if berr != nil { + errors = append(errors, berr) + } + + ghrepo, ghrerr := CurrentGitHubRepository() + if ghrerr != nil { + errors = append(errors, ghrerr) + } + + var err error = nil + + if len(errors) > 0 { + errStrings := []string{} + for _, e := range errors { + errStrings = append(errStrings, e.Error()) + } + + err = fmt.Errorf(strings.Join(errStrings, ", ")) + } + + return &Context{ + Token: token, + Username: username, + Branch: branch, + GHRepo: ghrepo, + }, err +}