@@ -4,20 +4,16 @@ import (
4
4
"context"
5
5
"net/http"
6
6
"os"
7
+ "strings"
7
8
8
9
"github.com/google/go-github/v62/github"
9
10
"golang.org/x/oauth2"
10
11
)
11
12
12
13
// NewGitHubClient returns a new github.Client configured with an access token
13
14
// and a http client, if available.
14
- func NewGitHubClient (ctx context.Context , httpClient * http.Client ) * github.Client {
15
- for _ , key := range []string {
16
- "CHEZMOI_GITHUB_ACCESS_TOKEN" ,
17
- "CHEZMOI_GITHUB_TOKEN" ,
18
- "GITHUB_ACCESS_TOKEN" ,
19
- "GITHUB_TOKEN" ,
20
- } {
15
+ func NewGitHubClient (ctx context.Context , httpClient * http.Client , host string ) * github.Client {
16
+ for _ , key := range accessTokenEnvKeys (host ) {
21
17
if accessToken := os .Getenv (key ); accessToken != "" {
22
18
httpClient = oauth2 .NewClient (
23
19
context .WithValue (ctx , oauth2 .HTTPClient , httpClient ),
@@ -29,3 +25,39 @@ func NewGitHubClient(ctx context.Context, httpClient *http.Client) *github.Clien
29
25
}
30
26
return github .NewClient (httpClient )
31
27
}
28
+
29
+ func accessTokenEnvKeys (host string ) []string {
30
+ var keys []string
31
+ for _ , chezmoiKey := range []string {"CHEZMOI" , "" } {
32
+ hostKeys := []string {makeHostKey (host )}
33
+ if host == "github.com" {
34
+ hostKeys = append (hostKeys , "GITHUB" )
35
+ }
36
+ for _ , hostKey := range hostKeys {
37
+ for _ , accessKey := range []string {"ACCESS" , "" } {
38
+ key := strings .Join (nonEmpty ([]string {chezmoiKey , hostKey , accessKey , "TOKEN" }), "_" )
39
+ keys = append (keys , key )
40
+ }
41
+ }
42
+ }
43
+ return keys
44
+ }
45
+
46
+ func makeHostKey (host string ) string {
47
+ // FIXME split host on non-ASCII characters
48
+ // FIXME convert everything to uppercase
49
+ // FIXME join components with _
50
+ return host
51
+ }
52
+
53
+ func nonEmpty [S []T , T comparable ](s S ) S {
54
+ // FIXME use something from slices for this
55
+ result := make ([]T , 0 , len (s ))
56
+ var zero T
57
+ for _ , e := range s {
58
+ if e != zero {
59
+ result = append (result , e )
60
+ }
61
+ }
62
+ return result
63
+ }
0 commit comments