Skip to content

Commit

Permalink
Add github token support
Browse files Browse the repository at this point in the history
Signed-off-by: Saswata Mukherjee <saswataminsta@yahoo.com>
  • Loading branch information
saswatamcode committed Jun 1, 2021
1 parent 0e2b12a commit c46b6e4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
1 change: 1 addition & 0 deletions .github/workflows/go.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,5 @@ jobs:
- name: Run unit tests.
env:
GOBIN: /tmp/.bin
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: make test
35 changes: 29 additions & 6 deletions pkg/mdformatter/linktransformer/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"math"
"net/http"
"os"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -86,8 +87,30 @@ func getGitHubRegex(repoRe string) (*regexp.Regexp, int, error) {
var pullNum []GitHubResponse
var issueNum []GitHubResponse
max := 0
// All GitHub API reqs need to have User-Agent: https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required.
client := &http.Client{}
repoToken := os.Getenv("GITHUB_TOKEN")

// Check latest pull request number.
respPull, err := http.Get(fmt.Sprintf(gitHubAPIURL, reponame, "pulls"))
reqPull, err := http.NewRequest("GET", fmt.Sprintf(gitHubAPIURL, reponame, "pulls"), nil)
if err != nil {
return nil, math.MaxInt64, err
}
reqPull.Header.Set("User-Agent", "mdox")

// Check latest issue number and return whichever is greater.
reqIssue, err := http.NewRequest("GET", fmt.Sprintf(gitHubAPIURL, reponame, "issues"), nil)
if err != nil {
return nil, math.MaxInt64, err
}
reqIssue.Header.Set("User-Agent", "mdox")

if repoToken != "" {
reqPull.Header.Set("Authorization", "Bearer "+repoToken)
reqIssue.Header.Set("Authorization", "Bearer "+repoToken)
}

respPull, err := client.Do(reqPull)
if err != nil {
return nil, math.MaxInt64, err
}
Expand All @@ -98,12 +121,8 @@ func getGitHubRegex(repoRe string) (*regexp.Regexp, int, error) {
if err := json.NewDecoder(respPull.Body).Decode(&pullNum); err != nil {
return nil, math.MaxInt64, err
}
if len(pullNum) > 0 {
max = pullNum[0].Number
}

// Check latest issue number and return whichever is greater.
respIssue, err := http.Get(fmt.Sprintf(gitHubAPIURL, reponame, "issues"))
respIssue, err := client.Do(reqIssue)
if err != nil {
return nil, math.MaxInt64, err
}
Expand All @@ -114,6 +133,10 @@ func getGitHubRegex(repoRe string) (*regexp.Regexp, int, error) {
if err := json.NewDecoder(respIssue.Body).Decode(&issueNum); err != nil {
return nil, math.MaxInt64, err
}

if len(pullNum) > 0 {
max = pullNum[0].Number
}
if len(issueNum) > 0 && issueNum[0].Number > max {
max = issueNum[0].Number
}
Expand Down

0 comments on commit c46b6e4

Please sign in to comment.