cli/pkg/cmd/ssh-key/shared/user_keys.go
copilot-swe-agent[bot] dca59d52b6 Fix linting issues: canonicalheader, embeddedstructfieldcheck, iotamixing, makezero, testableexamples, wastedassign, usetesting, tparallel, unconvert, intrange, iface
- canonicalheader: fix cacheTTL header value to canonical form
- embeddedstructfieldcheck: move embedded fields before regular fields in 4 structs
- iotamixing: split const blocks mixing iota with non-iota constants
- makezero: use make([]T, 0, n) instead of make([]T, n) before appending
- testableexamples: add missing Output: comment to ExampleOption_UnwrapOrZero
- wastedassign: remove wasted initial assignments in 4 locations
- usetesting: replace os.MkdirTemp/os.Setenv with t.TempDir/t.Setenv in tests
- tparallel: add t.Parallel() to 8 top-level test functions
- unconvert: remove 16 unnecessary type conversions
- intrange: convert 3 for loops to use integer range syntax
- iface: consolidate identical EditPrompter and Prompt interfaces via type alias

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-24 11:05:52 +00:00

95 lines
1.7 KiB
Go

package shared
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
)
const (
AuthenticationKey = "authentication"
SigningKey = "signing"
)
type sshKey struct {
ID int
Key string
Title string
Type string
CreatedAt time.Time `json:"created_at"`
}
func UserKeys(httpClient *http.Client, host, userHandle string) ([]sshKey, error) {
resource := "user/keys"
if userHandle != "" {
resource = fmt.Sprintf("users/%s/keys", userHandle)
}
url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100)
keys, err := getUserKeys(httpClient, url)
if err != nil {
return nil, err
}
for i := range keys {
keys[i].Type = AuthenticationKey
}
return keys, nil
}
func UserSigningKeys(httpClient *http.Client, host, userHandle string) ([]sshKey, error) {
resource := "user/ssh_signing_keys"
if userHandle != "" {
resource = fmt.Sprintf("users/%s/ssh_signing_keys", userHandle)
}
url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100)
keys, err := getUserKeys(httpClient, url)
if err != nil {
return nil, err
}
for i := range keys {
keys[i].Type = SigningKey
}
return keys, nil
}
func getUserKeys(httpClient *http.Client, url string) ([]sshKey, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var keys []sshKey
err = json.Unmarshal(b, &keys)
if err != nil {
return nil, err
}
return keys, nil
}