Skip to content

Commit

Permalink
Use GITHUB_TOKEN if found in environment
Browse files Browse the repository at this point in the history
  • Loading branch information
tebeka committed Nov 24, 2023
1 parent d5d1abb commit 30b08c1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
11 changes: 11 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,19 @@ var (
httpTimeout time.Duration
)

const (
tokenKey = "GITHUB_TOKEN"
)

func main() {
exe := path.Base(os.Args[0])
flag.BoolVar(&showVersion, "version", false, "show version and exit")
flag.DurationVar(&httpTimeout, "timeout", 3*time.Second, "HTTP timeout")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [options] [file]\nOptions:\n", exe)
flag.PrintDefaults()
fmt.Fprintln(os.Stderr)
fmt.Fprintf(os.Stderr, "If %s is found in the environment, it will be use to access GitHub API.\n", tokenKey)
}
flag.Parse()

Expand Down Expand Up @@ -139,6 +145,11 @@ func repoDesc(owner, repo string) (string, error) {
return "", err
}

token := os.Getenv(tokenKey)
if token != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
Expand Down
31 changes: 31 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package main
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"os/exec"
"path"
Expand Down Expand Up @@ -158,3 +160,32 @@ func TestExeFlags(t *testing.T) {
})
}
}

type mockTripper struct {
token string
}

func (t *mockTripper) RoundTrip(req *http.Request) (*http.Response, error) {
auth := req.Header.Get("Authorization")
i := len("Bearer ")
if len(auth) > i {
t.token = auth[i:]
}

return nil, fmt.Errorf("oopsie")
}

func TestGHToken(t *testing.T) {
token := "s3cr3t"
t.Setenv(tokenKey, token)

oldTransport := http.DefaultClient.Transport
var mt mockTripper
http.DefaultClient.Transport = &mt
t.Cleanup(func() {
http.DefaultClient.Transport = oldTransport
})

repoDesc("tebeka", "expmod")
require.Equal(t, token, mt.token)
}

0 comments on commit 30b08c1

Please sign in to comment.