]> khamidou — GitHub mirrors - prguy.git/commitdiff
handle error with repos that need saml auth
authorKarim Hamidou <karim@khamidou.com>
Wed, 3 Jul 2024 14:10:28 +0000 (07:10 -0700)
committerKarim Hamidou <karim@khamidou.com>
Wed, 3 Jul 2024 14:10:28 +0000 (07:10 -0700)
cmd/prguy/main.go
cmd/prguy/repos.go

index c24e93bb197e25d91611b56cb44d5b7e164e0b9e..ffc9b1fd0d5bec1958910095f928e52f2884bb52 100644 (file)
@@ -2,13 +2,13 @@ package main
 
 import (
        "context"
-    "reflect"
        "errors"
        "fmt"
        "io/ioutil"
        "net/http"
        "net/url"
        "os/exec"
+       "reflect"
        "strings"
        "time"
 
@@ -37,9 +37,9 @@ func setupMenu(ctx context.Context, cancel context.CancelFunc) {
 
        go func() {
                if !config.exists() {
-            mDoSetup := systray.AddMenuItem("GitHub setup", "Authenticate yourself to be able to see your pull requests.")
+                       mDoSetup := systray.AddMenuItem("GitHub setup", "Authenticate yourself to be able to see your pull requests.")
 
-            mQuitOrig := systray.AddMenuItem("Quit", "Quit the app")
+                       mQuitOrig := systray.AddMenuItem("Quit", "Quit the app")
 
                        for {
                                select {
@@ -57,75 +57,78 @@ func setupMenu(ctx context.Context, cancel context.CancelFunc) {
                        }
                } else {
                        cfg := Config{}
-            var channels []chan struct{}
-            var channelsMap = make(map[chan struct{}]pullRequest)
+                       var channels []chan struct{}
+                       var channelsMap = make(map[chan struct{}]pullRequest)
 
                        cfg.load()
-            systray.ResetMenu()
+                       systray.ResetMenu()
 
+                       fmt.Println("Fetching PRs...")
                        myPRs, otherPRs, err := listUserPRs(cfg.OAuthToken)
                        if err != nil {
-                               errorOut("Error fetching PRs", err.Error())
+                               fmt.Println("Error fetching PRs:", err)
+                               time.Sleep(35 * time.Second)
+                               return
+                       }
+
+                       if len(myPRs) == 0 {
+                               systray.AddMenuItem("No PRs out from you, let's get after it!", "")
+                       } else {
+                               for _, pr := range myPRs {
+                                       var pr_status string
+                                       if pr.mergeable {
+                                               pr_status = "✅"
+                                       } else {
+                                               pr_status = "❌"
+                                       }
+
+                                       title := fmt.Sprintf("%-*s %s", 50, pr.title, pr_status)
+                                       channel := systray.AddMenuItem(title, "")
+                                       channels = append(channels, channel.ClickedCh)
+                                       channelsMap[channel.ClickedCh] = pr
+                               }
+                       }
+
+                       systray.AddSeparator()
+
+                       if len(myPRs) != 0 && len(otherPRs) == 0 {
+                               systray.AddMenuItem("No PRs to review, no news is good news.", "")
+                       } else if len(otherPRs) != 0 {
+                               for _, pr := range otherPRs {
+                                       var pr_status string
+                                       if pr.mergeable {
+                                               pr_status = "✅"
+                                       } else {
+                                               pr_status = "❌"
+                                       }
+
+                                       title := fmt.Sprintf("%-*s %s", 50, pr.title, pr_status)
+                                       channel := systray.AddMenuItem(title, "")
+                                       channels = append(channels, channel.ClickedCh)
+                                       channelsMap[channel.ClickedCh] = pr
+                               }
                        }
 
-            if len(myPRs) == 0 {
-                systray.AddMenuItem("No PRs out from you, let's get after it!", "")
-            } else {
-                for _, pr := range myPRs {
-                    var pr_status string
-                    if pr.mergeable {
-                        pr_status = "✅"
-                    } else {
-                        pr_status = "❌"
-                    }
-
-                    title := fmt.Sprintf("%-*s %s", 50, pr.title, pr_status)
-                    channel := systray.AddMenuItem(title, "")
-                    channels = append(channels, channel.ClickedCh)
-                    channelsMap[channel.ClickedCh] = pr
-                }
-            }
-
-            systray.AddSeparator()
-
-            if len(myPRs) != 0 && len(otherPRs) == 0 {
-                systray.AddMenuItem("No PRs from others, no news is good news.", "")
-            } else if len(otherPRs) != 0 {
-                for _, pr := range otherPRs {
-                    var pr_status string
-                    if pr.mergeable {
-                        pr_status = "✅"
-                    } else {
-                        pr_status = "❌"
-                    }
-
-                    title := fmt.Sprintf("%-*s %s", 50, pr.title, pr_status)
-                    channel := systray.AddMenuItem(title, "")
-                    channels = append(channels, channel.ClickedCh)
-                    channelsMap[channel.ClickedCh] = pr
-                }
-            }
-
-            systray.AddSeparator()
+                       systray.AddSeparator()
 
                        mQuitOrig := systray.AddMenuItem("Quit", "Quit the app")
-            channels = append(channels, mQuitOrig.ClickedCh)
+                       channels = append(channels, mQuitOrig.ClickedCh)
 
                        for {
-                i, ok := selectChannels(channels)
-                if !ok {
-                    continue
-                }
-
-                if i == len(channels) - 1 {
-                    // quit
-                    fmt.Println("Requesting quit")
+                               i, ok := selectChannels(channels)
+                               if !ok {
+                                       continue
+                               }
+
+                               if i == len(channels)-1 {
+                                       // quit
+                                       fmt.Println("Requesting quit")
                                        systray.Quit()
-                } else {
-                    // open the PR
-                    pr := channelsMap[channels[i]]
-                    open.Run(pr.url)
-                }
+                               } else {
+                                       // open the PR
+                                       pr := channelsMap[channels[i]]
+                                       open.Run(pr.url)
+                               }
                        }
                }
        }()
@@ -134,27 +137,27 @@ func setupMenu(ctx context.Context, cancel context.CancelFunc) {
 
 func onReady() {
        go func() {
-        ticker := time.NewTicker(1 * time.Minute)
-        defer ticker.Stop() // Ensure the ticker is stopped when we're done with it
-
-        ctx, cancel := context.WithCancel(context.Background())
-        setupMenu(ctx, cancel)
-        for {
-            select {
-            case <-ticker.C:
-                // refresh the menu every 15 minutes
-                cancel()
-                ctx, cancel = context.WithCancel(context.Background())
-                setupMenu(ctx, cancel)
-            }
-        }
-    }()
+               ticker := time.NewTicker(1 * time.Minute)
+               defer ticker.Stop() // Ensure the ticker is stopped when we're done with it
+
+               ctx, cancel := context.WithCancel(context.Background())
+               setupMenu(ctx, cancel)
+               for {
+                       select {
+                       case <-ticker.C:
+                               // refresh the menu every 15 minutes
+                               cancel()
+                               ctx, cancel = context.WithCancel(context.Background())
+                               setupMenu(ctx, cancel)
+                       }
+               }
+       }()
 }
 
 func startGithubDeviceAuth(cancel context.CancelFunc) {
        formData := url.Values{
                "client_id": []string{GH_CLIENT_ID},
-        "scope":     []string{"notifications repo"},
+               "scope":     []string{"notifications repo"},
        }
 
        encodedForm := formData.Encode()
@@ -174,9 +177,6 @@ func startGithubDeviceAuth(cancel context.CancelFunc) {
        }
 
        if resp.StatusCode != 200 {
-               errorOut("Github API error",
-                       fmt.Sprintf("Got a '%s'error from the Github API. Please retry in a bit.",
-                               resp.Status))
                return
        }
        defer resp.Body.Close()
@@ -272,10 +272,6 @@ func pollGithubDeviceAuth(deviceCode string, cancel context.CancelFunc) error {
                if resp.StatusCode == 429 {
                        continue
                } else if resp.StatusCode != 200 {
-                       errorOut("Github API error",
-                               "Got a "+string(resp.Status)+
-                                       "error from the Github API. "+
-                                       "Please retry in a bit.")
                        return errors.New("api_error")
                }
 
@@ -335,7 +331,7 @@ func writeToClipboard(text string) error {
 }
 
 func selectChannels(chans []chan struct{}) (int, bool) {
-    // straight from https://go.dev/play/p/wCchjGndBC
+       // straight from https://go.dev/play/p/wCchjGndBC
        var cases []reflect.SelectCase
        for _, ch := range chans {
                cases = append(cases, reflect.SelectCase{
@@ -346,5 +342,5 @@ func selectChannels(chans []chan struct{}) (int, bool) {
        }
 
        i, _, ok := reflect.Select(cases)
-    return i, ok
+       return i, ok
 }
index 513db8bccffb855eede385efee8fa985cd9d9c63..d97780eb068755225e970a80083faa386916713b 100644 (file)
@@ -10,6 +10,8 @@ import (
 
 type buildStatus int
 
+var errNoAccessToPR = errors.New("No access to PR")
+
 const (
        buildPending = iota
        buildSuccess
@@ -18,9 +20,9 @@ const (
 )
 
 type pullRequest struct {
-       url    string
-       title  string
-    mergeable bool
+       url       string
+       title     string
+       mergeable bool
 }
 
 func listUserPRs(token string) ([]pullRequest, []pullRequest, error) {
@@ -51,10 +53,10 @@ func listUserPRs(token string) ([]pullRequest, []pullRequest, error) {
        }
 
        var myPRs []pullRequest
-    var otherPRs []pullRequest
+       var otherPRs []pullRequest
 
        var jsonData []map[string]interface{}
-    var PRsSeen = make(map[string]bool)
+       var PRsSeen = make(map[string]bool)
 
        err = json.Unmarshal(body, &jsonData)
        if err != nil {
@@ -68,65 +70,70 @@ func listUserPRs(token string) ([]pullRequest, []pullRequest, error) {
                }
 
                subject := pr["subject"].(map[string]interface{})
-        prAPIUrl := subject["url"].(string)
-        prData, err := fetchOneRESTObject(prAPIUrl, token)
-        if err != nil {
-            return nil, nil, err
-        }
-
-        prUrl := prData["_links"].(map[string]interface{})["html"].(map[string]interface{})["href"].(string)
-        if _, ok := PRsSeen[prUrl]; ok {
-            continue
-        }
-
-        PRsSeen[prUrl] = true
-        if reason == "author" {
-            myPRs = append(myPRs, pullRequest{
-                url:   prUrl,
-                title: subject["title"].(string),
-                mergeable: prData["mergeable"].(bool),
-            })
-        } else {
-            otherPRs = append(otherPRs, pullRequest{
-                url:   prUrl,
-                title: subject["title"].(string),
-                mergeable: prData["mergeable"].(bool),
-            })
-        }
+               prAPIUrl := subject["url"].(string)
+               fmt.Println("fetching one PR", subject["title"].(string))
+
+               prData, err := fetchOneRESTObject(prAPIUrl, token)
+               if err == errNoAccessToPR {
+                       // Skip PRs we don't have access to
+                       continue
+               } else if err != nil {
+                       return nil, nil, err
+               }
+
+               prUrl := prData["_links"].(map[string]interface{})["html"].(map[string]interface{})["href"].(string)
+               if _, ok := PRsSeen[prUrl]; ok {
+                       continue
+               }
+
+               PRsSeen[prUrl] = true
+               if reason == "author" {
+                       myPRs = append(myPRs, pullRequest{
+                               url:       prUrl,
+                               title:     subject["title"].(string),
+                               mergeable: prData["mergeable"].(bool),
+                       })
+               } else {
+                       otherPRs = append(otherPRs, pullRequest{
+                               url:       prUrl,
+                               title:     subject["title"].(string),
+                               mergeable: prData["mergeable"].(bool),
+                       })
+               }
        }
 
        return myPRs, otherPRs, nil
 }
 
 func fetchOneRESTObject(url string, token string) (map[string]interface{}, error) {
-    req, err := http.NewRequest("GET", url, nil)
-    if err != nil {
-        return nil, err
-    }
-
-    req.Header.Set("Authorization", "Bearer "+token)
-    client := &http.Client{}
-    resp, err := client.Do(req)
-    if err != nil {
-        return nil, err
-    }
-
-    if resp.StatusCode != 200 {
-        return nil, errors.New(fmt.Sprintf("Got a '%s'error from the Github API. Please retry in a bit.", resp.Status))
-    }
-
-    defer resp.Body.Close()
-
-    body, err := ioutil.ReadAll(resp.Body)
-    if err != nil {
-        return nil, err
-    }
-
-    var jsonData map[string]interface{}
-    err = json.Unmarshal(body, &jsonData)
-    if err != nil {
-        return nil, err
-    }
-
-    return jsonData, nil
+       req, err := http.NewRequest("GET", url, nil)
+       if err != nil {
+               return nil, err
+       }
+
+       req.Header.Set("Authorization", "Bearer "+token)
+       client := &http.Client{}
+       resp, err := client.Do(req)
+       if err != nil {
+               return nil, err
+       }
+
+       defer resp.Body.Close()
+
+       body, err := ioutil.ReadAll(resp.Body)
+       if err != nil {
+               return nil, err
+       }
+
+       var jsonData map[string]interface{}
+       err = json.Unmarshal(body, &jsonData)
+       if err != nil {
+               return nil, err
+       }
+
+       if _, ok := jsonData["message"]; ok && jsonData["message"] == "Resource protected by organization SAML enforcement. You must grant your OAuth token access to this organization." {
+               return nil, errNoAccessToPR
+       }
+
+       return jsonData, nil
 }