Skip to content

Commit cc60e30

Browse files
committed
use go-gh package
1 parent 6ad5d49 commit cc60e30

File tree

3 files changed

+26
-86
lines changed

3 files changed

+26
-86
lines changed

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ require (
3434
github.com/charmbracelet/x/exp/strings v0.0.0-20251106172358-54469c29c2bc // indirect
3535
github.com/charmbracelet/x/term v0.2.2 // indirect
3636
github.com/cli/safeexec v1.0.1 // indirect
37+
github.com/cli/shurcooL-graphql v0.0.4 // indirect
3738
github.com/clipperhouse/displaywidth v0.5.0 // indirect
3839
github.com/clipperhouse/stringish v0.1.1 // indirect
3940
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
7373
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
7474
github.com/google/jsonschema-go v0.3.0 h1:6AH2TxVNtk3IlvkkhjrtbUc4S8AvO0Xii0DxIygDg+Q=
7575
github.com/google/jsonschema-go v0.3.0/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
76+
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
77+
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
7678
github.com/henvic/httpretty v0.1.4 h1:Jo7uwIRWVFxkqOnErcoYfH90o3ddQyVrSANeS4cxYmU=
7779
github.com/henvic/httpretty v0.1.4/go.mod h1:Dn60sQTZfbt2dYsdUSNsCljyF4AfdqnuJFDLJA1I4AM=
7880
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
@@ -159,5 +161,7 @@ golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ
159161
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
160162
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
161163
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
164+
gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY=
165+
gopkg.in/h2non/gock.v1 v1.1.2/go.mod h1:n7UGz/ckNChHiK05rDoiC4MYSunEC/lyaUm2WWaDva0=
162166
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
163167
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

internal/tools/ghsecret/main.go

Lines changed: 21 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,10 @@ import (
1010
"fmt"
1111
"io"
1212
"log"
13-
"net/http"
14-
"net/url"
1513
"os"
1614
"strings"
1715

16+
"github.com/cli/go-gh/v2/pkg/api"
1817
"golang.org/x/crypto/nacl/box"
1918
)
2019

@@ -45,48 +44,28 @@ func main() {
4544
os.Exit(1)
4645
}
4746

48-
apiBase := resolveAPIBase(*flagAPIBase)
49-
token, err := resolveToken()
47+
// Create GitHub REST client using go-gh
48+
opts := api.ClientOptions{}
49+
if *flagAPIBase != "" {
50+
opts.Host = strings.TrimPrefix(strings.TrimPrefix(*flagAPIBase, "https://"), "http://")
51+
}
52+
client, err := api.NewRESTClient(opts)
5053
if err != nil {
51-
log.Fatalf("cannot resolve GitHub token: %v", err)
54+
log.Fatalf("cannot create GitHub client: %v", err)
5255
}
5356

5457
secretValue, err := resolveSecretValue(*flagValueEnv, *flagValue)
5558
if err != nil {
5659
log.Fatalf("cannot resolve secret value: %v", err)
5760
}
5861

59-
if err := setRepoSecret(apiBase, token, *flagOwner, *flagRepo, *flagSecretName, secretValue); err != nil {
62+
if err := setRepoSecret(client, *flagOwner, *flagRepo, *flagSecretName, secretValue); err != nil {
6063
log.Fatalf("failed to set secret: %v", err)
6164
}
6265

6366
fmt.Printf("Secret %s updated for %s/%s\n", *flagSecretName, *flagOwner, *flagRepo)
6467
}
6568

66-
func resolveAPIBase(flagValue string) string {
67-
candidates := []string{
68-
strings.TrimSpace(flagValue),
69-
strings.TrimSpace(os.Getenv("GITHUB_API_URL")),
70-
}
71-
72-
for _, c := range candidates {
73-
if c != "" {
74-
return strings.TrimRight(c, "/")
75-
}
76-
}
77-
78-
return "https://api.github.com"
79-
}
80-
81-
func resolveToken() (string, error) {
82-
for _, name := range []string{"GITHUB_TOKEN", "GH_TOKEN"} {
83-
if v := strings.TrimSpace(os.Getenv(name)); v != "" {
84-
return v, nil
85-
}
86-
}
87-
return "", errors.New("no GitHub token found; set the GITHUB_TOKEN or GH_TOKEN environment variable with a personal access token (see https://github.com/settings/tokens)")
88-
}
89-
9069
func resolveSecretValue(fromEnv, fromFlag string) (string, error) {
9170
if fromEnv != "" {
9271
v := os.Getenv(fromEnv)
@@ -130,8 +109,8 @@ func resolveSecretValue(fromEnv, fromFlag string) (string, error) {
130109
return value, nil
131110
}
132111

133-
func setRepoSecret(apiBase, token, owner, repo, name, value string) error {
134-
pubKey, err := getRepoPublicKey(apiBase, token, owner, repo)
112+
func setRepoSecret(client *api.RESTClient, owner, repo, name, value string) error {
113+
pubKey, err := getRepoPublicKey(client, owner, repo)
135114
if err != nil {
136115
return fmt.Errorf("get repo public key: %w", err)
137116
}
@@ -141,32 +120,14 @@ func setRepoSecret(apiBase, token, owner, repo, name, value string) error {
141120
return fmt.Errorf("encrypt secret: %w", err)
142121
}
143122

144-
return putRepoSecret(apiBase, token, owner, repo, name, pubKey.ID, encrypted)
123+
return putRepoSecret(client, owner, repo, name, pubKey.ID, encrypted)
145124
}
146125

147-
func getRepoPublicKey(apiBase, token, owner, repo string) (*repoPublicKey, error) {
148-
endpoint := fmt.Sprintf("%s/repos/%s/%s/actions/secrets/public-key", apiBase, owner, repo)
149-
150-
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
151-
if err != nil {
152-
return nil, err
153-
}
154-
addGitHubHeaders(req, token)
155-
156-
resp, err := http.DefaultClient.Do(req)
157-
if err != nil {
158-
return nil, err
159-
}
160-
defer resp.Body.Close()
161-
162-
if resp.StatusCode != http.StatusOK {
163-
body, _ := io.ReadAll(resp.Body)
164-
return nil, fmt.Errorf("GitHub API %s: %s", resp.Status, string(body))
165-
}
166-
126+
func getRepoPublicKey(client *api.RESTClient, owner, repo string) (*repoPublicKey, error) {
167127
var key repoPublicKey
168-
if err := json.NewDecoder(resp.Body).Decode(&key); err != nil {
169-
return nil, err
128+
path := fmt.Sprintf("repos/%s/%s/actions/secrets/public-key", owner, repo)
129+
if err := client.Get(path, &key); err != nil {
130+
return nil, fmt.Errorf("get public key: %w", err)
170131
}
171132
if key.ID == "" || key.Key == "" {
172133
return nil, errors.New("public key response missing key_id or key")
@@ -194,43 +155,17 @@ func encryptWithPublicKey(publicKeyB64, plaintext string) (string, error) {
194155
return base64.StdEncoding.EncodeToString(ciphertext), nil
195156
}
196157

197-
func putRepoSecret(apiBase, token, owner, repo, name, keyID, encryptedValue string) error {
198-
endpoint := fmt.Sprintf("%s/repos/%s/%s/actions/secrets/%s",
199-
apiBase, owner, repo, url.PathEscape(name))
200-
201-
body, err := json.Marshal(secretPayload{
158+
func putRepoSecret(client *api.RESTClient, owner, repo, name, keyID, encryptedValue string) error {
159+
path := fmt.Sprintf("repos/%s/%s/actions/secrets/%s", owner, repo, name)
160+
payload := secretPayload{
202161
EncryptedValue: encryptedValue,
203162
KeyID: keyID,
204-
})
205-
if err != nil {
206-
return err
207-
}
208-
209-
req, err := http.NewRequest(http.MethodPut, endpoint, strings.NewReader(string(body)))
210-
if err != nil {
211-
return err
212163
}
213-
addGitHubHeaders(req, token)
214-
req.Header.Set("Content-Type", "application/json")
215164

216-
resp, err := http.DefaultClient.Do(req)
165+
body, err := json.Marshal(payload)
217166
if err != nil {
218167
return err
219168
}
220-
defer resp.Body.Close()
221-
222-
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusCreated {
223-
b, _ := io.ReadAll(resp.Body)
224-
return fmt.Errorf("GitHub API %s: %s", resp.Status, string(b))
225-
}
226-
227-
return nil
228-
}
229169

230-
func addGitHubHeaders(req *http.Request, token string) {
231-
req.Header.Set("Accept", "application/vnd.github+json")
232-
req.Header.Set("Authorization", "Bearer "+token)
233-
if req.Header.Get("X-GitHub-Api-Version") == "" {
234-
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
235-
}
170+
return client.Put(path, strings.NewReader(string(body)), nil)
236171
}

0 commit comments

Comments
 (0)