repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/http/config.go | transport/internet/http/config.go | // +build !confonly
package http
import (
"v2ray.com/core/common"
"v2ray.com/core/common/dice"
"v2ray.com/core/transport/internet"
)
const protocolName = "http"
func (c *Config) getHosts() []string {
if len(c.Host) == 0 {
return []string{"www.example.com"}
}
return c.Host
}
func (c *Config) isValidHost(host string) bool {
hosts := c.getHosts()
for _, h := range hosts {
if h == host {
return true
}
}
return false
}
func (c *Config) getRandomHost() string {
hosts := c.getHosts()
return hosts[dice.Roll(len(hosts))]
}
func (c *Config) getNormalizedPath() string {
if c.Path == "" {
return "/"
}
if c.Path[0] != '/' {
return "/" + c.Path
}
return c.Path
}
func init() {
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
return new(Config)
}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/http/http_test.go | transport/internet/http/http_test.go | package http_test
import (
"context"
"crypto/rand"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol/tls/cert"
"v2ray.com/core/testing/servers/tcp"
"v2ray.com/core/transport/internet"
. "v2ray.com/core/transport/internet/http"
"v2ray.com/core/transport/internet/tls"
)
func TestHTTPConnection(t *testing.T) {
port := tcp.PickPort()
listener, err := Listen(context.Background(), net.LocalHostIP, port, &internet.MemoryStreamConfig{
ProtocolName: "http",
ProtocolSettings: &Config{},
SecurityType: "tls",
SecuritySettings: &tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil, cert.CommonName("www.v2ray.com")))},
},
}, func(conn internet.Connection) {
go func() {
defer conn.Close()
b := buf.New()
defer b.Release()
for {
if _, err := b.ReadFrom(conn); err != nil {
return
}
_, err := conn.Write(b.Bytes())
common.Must(err)
}
}()
})
common.Must(err)
defer listener.Close()
time.Sleep(time.Second)
dctx := context.Background()
conn, err := Dial(dctx, net.TCPDestination(net.LocalHostIP, port), &internet.MemoryStreamConfig{
ProtocolName: "http",
ProtocolSettings: &Config{},
SecurityType: "tls",
SecuritySettings: &tls.Config{
ServerName: "www.v2ray.com",
AllowInsecure: true,
},
})
common.Must(err)
defer conn.Close()
const N = 1024
b1 := make([]byte, N)
common.Must2(rand.Read(b1))
b2 := buf.New()
nBytes, err := conn.Write(b1)
common.Must(err)
if nBytes != N {
t.Error("write: ", nBytes)
}
b2.Clear()
common.Must2(b2.ReadFullFrom(conn, N))
if r := cmp.Diff(b2.Bytes(), b1); r != "" {
t.Error(r)
}
nBytes, err = conn.Write(b1)
common.Must(err)
if nBytes != N {
t.Error("write: ", nBytes)
}
b2.Clear()
common.Must2(b2.ReadFullFrom(conn, N))
if r := cmp.Diff(b2.Bytes(), b1); r != "" {
t.Error(r)
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/http/http.go | transport/internet/http/http.go | package http
//go:generate go run v2ray.com/core/common/errors/errorgen
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/http/config.pb.go | transport/internet/http/config.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.13.0
// source: transport/internet/http/config.proto
package http
import (
proto "github.com/golang/protobuf/proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
type Config struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Host []string `protobuf:"bytes,1,rep,name=host,proto3" json:"host,omitempty"`
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
}
func (x *Config) Reset() {
*x = Config{}
if protoimpl.UnsafeEnabled {
mi := &file_transport_internet_http_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_http_config_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_transport_internet_http_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetHost() []string {
if x != nil {
return x.Host
}
return nil
}
func (x *Config) GetPath() string {
if x != nil {
return x.Path
}
return ""
}
var File_transport_internet_http_config_proto protoreflect.FileDescriptor
var file_transport_internet_http_config_proto_rawDesc = []byte{
0x0a, 0x24, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65,
0x72, 0x6e, 0x65, 0x74, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x22, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
0x72, 0x65, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74,
0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x22, 0x30, 0x0a, 0x06, 0x43, 0x6f,
0x6e, 0x66, 0x69, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, 0x03,
0x28, 0x09, 0x52, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68,
0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x42, 0x77, 0x0a, 0x26,
0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x74,
0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65,
0x74, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x50, 0x01, 0x5a, 0x26, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f,
0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2f, 0x68, 0x74, 0x74, 0x70,
0xaa, 0x02, 0x22, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x54, 0x72,
0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74,
0x2e, 0x48, 0x74, 0x74, 0x70, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_transport_internet_http_config_proto_rawDescOnce sync.Once
file_transport_internet_http_config_proto_rawDescData = file_transport_internet_http_config_proto_rawDesc
)
func file_transport_internet_http_config_proto_rawDescGZIP() []byte {
file_transport_internet_http_config_proto_rawDescOnce.Do(func() {
file_transport_internet_http_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_transport_internet_http_config_proto_rawDescData)
})
return file_transport_internet_http_config_proto_rawDescData
}
var file_transport_internet_http_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_transport_internet_http_config_proto_goTypes = []interface{}{
(*Config)(nil), // 0: v2ray.core.transport.internet.http.Config
}
var file_transport_internet_http_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_transport_internet_http_config_proto_init() }
func file_transport_internet_http_config_proto_init() {
if File_transport_internet_http_config_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_transport_internet_http_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Config); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_transport_internet_http_config_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_transport_internet_http_config_proto_goTypes,
DependencyIndexes: file_transport_internet_http_config_proto_depIdxs,
MessageInfos: file_transport_internet_http_config_proto_msgTypes,
}.Build()
File_transport_internet_http_config_proto = out.File
file_transport_internet_http_config_proto_rawDesc = nil
file_transport_internet_http_config_proto_goTypes = nil
file_transport_internet_http_config_proto_depIdxs = nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/hub.go | transport/internet/websocket/hub.go | // +build !confonly
package websocket
import (
"context"
"crypto/tls"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/pires/go-proxyproto"
"v2ray.com/core/common"
"v2ray.com/core/common/net"
http_proto "v2ray.com/core/common/protocol/http"
"v2ray.com/core/common/session"
"v2ray.com/core/transport/internet"
v2tls "v2ray.com/core/transport/internet/tls"
)
type requestHandler struct {
path string
ln *Listener
}
var upgrader = &websocket.Upgrader{
ReadBufferSize: 4 * 1024,
WriteBufferSize: 4 * 1024,
HandshakeTimeout: time.Second * 4,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if request.URL.Path != h.path {
writer.WriteHeader(http.StatusNotFound)
return
}
conn, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
newError("failed to convert to WebSocket connection").Base(err).WriteToLog()
return
}
forwardedAddrs := http_proto.ParseXForwardedFor(request.Header)
remoteAddr := conn.RemoteAddr()
if len(forwardedAddrs) > 0 && forwardedAddrs[0].Family().IsIP() {
remoteAddr.(*net.TCPAddr).IP = forwardedAddrs[0].IP()
}
h.ln.addConn(newConnection(conn, remoteAddr))
}
type Listener struct {
sync.Mutex
server http.Server
listener net.Listener
config *Config
addConn internet.ConnHandler
}
func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSettings *internet.MemoryStreamConfig, addConn internet.ConnHandler) (internet.Listener, error) {
listener, err := internet.ListenSystem(ctx, &net.TCPAddr{
IP: address.IP(),
Port: int(port),
}, streamSettings.SocketSettings)
if err != nil {
return nil, newError("failed to listen TCP(for WS) on", address, ":", port).Base(err)
}
newError("listening TCP(for WS) on ", address, ":", port).WriteToLog(session.ExportIDToError(ctx))
wsSettings := streamSettings.ProtocolSettings.(*Config)
if wsSettings.AcceptProxyProtocol {
policyFunc := func(upstream net.Addr) (proxyproto.Policy, error) { return proxyproto.REQUIRE, nil }
listener = &proxyproto.Listener{Listener: listener, Policy: policyFunc}
newError("accepting PROXY protocol").AtWarning().WriteToLog(session.ExportIDToError(ctx))
}
if config := v2tls.ConfigFromStreamSettings(streamSettings); config != nil {
if tlsConfig := config.GetTLSConfig(); tlsConfig != nil {
listener = tls.NewListener(listener, tlsConfig)
}
}
l := &Listener{
config: wsSettings,
addConn: addConn,
listener: listener,
}
l.server = http.Server{
Handler: &requestHandler{
path: wsSettings.GetNormalizedPath(),
ln: l,
},
ReadHeaderTimeout: time.Second * 4,
MaxHeaderBytes: 2048,
}
go func() {
if err := l.server.Serve(l.listener); err != nil {
newError("failed to serve http for WebSocket").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx))
}
}()
return l, err
}
// Addr implements net.Listener.Addr().
func (ln *Listener) Addr() net.Addr {
return ln.listener.Addr()
}
// Close implements net.Listener.Close().
func (ln *Listener) Close() error {
return ln.listener.Close()
}
func init() {
common.Must(internet.RegisterTransportListener(protocolName, ListenWS))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/ws.go | transport/internet/websocket/ws.go | /*Package websocket implements Websocket transport
Websocket transport implements an HTTP(S) compliable, surveillance proof transport method with plausible deniability.
*/
package websocket
//go:generate go run v2ray.com/core/common/errors/errorgen
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/dialer.go | transport/internet/websocket/dialer.go | // +build !confonly
package websocket
import (
"context"
"time"
"github.com/gorilla/websocket"
"v2ray.com/core/common"
"v2ray.com/core/common/net"
"v2ray.com/core/common/session"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/tls"
)
// Dial dials a WebSocket connection to the given destination.
func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx))
conn, err := dialWebsocket(ctx, dest, streamSettings)
if err != nil {
return nil, newError("failed to dial WebSocket").Base(err)
}
return internet.Connection(conn), nil
}
func init() {
common.Must(internet.RegisterTransportDialer(protocolName, Dial))
}
func dialWebsocket(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (net.Conn, error) {
wsSettings := streamSettings.ProtocolSettings.(*Config)
dialer := &websocket.Dialer{
NetDial: func(network, addr string) (net.Conn, error) {
return internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
},
ReadBufferSize: 4 * 1024,
WriteBufferSize: 4 * 1024,
HandshakeTimeout: time.Second * 8,
}
protocol := "ws"
if config := tls.ConfigFromStreamSettings(streamSettings); config != nil {
protocol = "wss"
dialer.TLSClientConfig = config.GetTLSConfig(tls.WithDestination(dest), tls.WithNextProto("http/1.1"))
}
host := dest.NetAddr()
if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
host = dest.Address.String()
}
uri := protocol + "://" + host + wsSettings.GetNormalizedPath()
conn, resp, err := dialer.Dial(uri, wsSettings.GetRequestHeader())
if err != nil {
var reason string
if resp != nil {
reason = resp.Status
}
return nil, newError("failed to dial to (", uri, "): ", reason).Base(err)
}
return newConnection(conn, conn.RemoteAddr()), nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/errors.generated.go | transport/internet/websocket/errors.generated.go | package websocket
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/config.go | transport/internet/websocket/config.go | // +build !confonly
package websocket
import (
"net/http"
"v2ray.com/core/common"
"v2ray.com/core/transport/internet"
)
const protocolName = "websocket"
func (c *Config) GetNormalizedPath() string {
path := c.Path
if path == "" {
return "/"
}
if path[0] != '/' {
return "/" + path
}
return path
}
func (c *Config) GetRequestHeader() http.Header {
header := http.Header{}
for _, h := range c.Header {
header.Add(h.Key, h.Value)
}
return header
}
func init() {
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
return new(Config)
}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/connection.go | transport/internet/websocket/connection.go | // +build !confonly
package websocket
import (
"io"
"net"
"time"
"github.com/gorilla/websocket"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/serial"
)
var (
_ buf.Writer = (*connection)(nil)
)
// connection is a wrapper for net.Conn over WebSocket connection.
type connection struct {
conn *websocket.Conn
reader io.Reader
remoteAddr net.Addr
}
func newConnection(conn *websocket.Conn, remoteAddr net.Addr) *connection {
return &connection{
conn: conn,
remoteAddr: remoteAddr,
}
}
// Read implements net.Conn.Read()
func (c *connection) Read(b []byte) (int, error) {
for {
reader, err := c.getReader()
if err != nil {
return 0, err
}
nBytes, err := reader.Read(b)
if errors.Cause(err) == io.EOF {
c.reader = nil
continue
}
return nBytes, err
}
}
func (c *connection) getReader() (io.Reader, error) {
if c.reader != nil {
return c.reader, nil
}
_, reader, err := c.conn.NextReader()
if err != nil {
return nil, err
}
c.reader = reader
return reader, nil
}
// Write implements io.Writer.
func (c *connection) Write(b []byte) (int, error) {
if err := c.conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
return 0, err
}
return len(b), nil
}
func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
mb = buf.Compact(mb)
mb, err := buf.WriteMultiBuffer(c, mb)
buf.ReleaseMulti(mb)
return err
}
func (c *connection) Close() error {
var errors []interface{}
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
errors = append(errors, err)
}
if err := c.conn.Close(); err != nil {
errors = append(errors, err)
}
if len(errors) > 0 {
return newError("failed to close connection").Base(newError(serial.Concat(errors...)))
}
return nil
}
func (c *connection) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *connection) RemoteAddr() net.Addr {
return c.remoteAddr
}
func (c *connection) SetDeadline(t time.Time) error {
if err := c.SetReadDeadline(t); err != nil {
return err
}
return c.SetWriteDeadline(t)
}
func (c *connection) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
func (c *connection) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/config.pb.go | transport/internet/websocket/config.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.13.0
// source: transport/internet/websocket/config.proto
package websocket
import (
proto "github.com/golang/protobuf/proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
type Header struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *Header) Reset() {
*x = Header{}
if protoimpl.UnsafeEnabled {
mi := &file_transport_internet_websocket_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Header) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Header) ProtoMessage() {}
func (x *Header) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_websocket_config_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Header.ProtoReflect.Descriptor instead.
func (*Header) Descriptor() ([]byte, []int) {
return file_transport_internet_websocket_config_proto_rawDescGZIP(), []int{0}
}
func (x *Header) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
func (x *Header) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
type Config struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// URL path to the WebSocket service. Empty value means root(/).
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
Header []*Header `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty"`
AcceptProxyProtocol bool `protobuf:"varint,4,opt,name=accept_proxy_protocol,json=acceptProxyProtocol,proto3" json:"accept_proxy_protocol,omitempty"`
}
func (x *Config) Reset() {
*x = Config{}
if protoimpl.UnsafeEnabled {
mi := &file_transport_internet_websocket_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_websocket_config_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_transport_internet_websocket_config_proto_rawDescGZIP(), []int{1}
}
func (x *Config) GetPath() string {
if x != nil {
return x.Path
}
return ""
}
func (x *Config) GetHeader() []*Header {
if x != nil {
return x.Header
}
return nil
}
func (x *Config) GetAcceptProxyProtocol() bool {
if x != nil {
return x.AcceptProxyProtocol
}
return false
}
var File_transport_internet_websocket_config_proto protoreflect.FileDescriptor
var file_transport_internet_websocket_config_proto_rawDesc = []byte{
0x0a, 0x29, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65,
0x72, 0x6e, 0x65, 0x74, 0x2f, 0x77, 0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x2f, 0x63,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x27, 0x76, 0x32, 0x72,
0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x77, 0x65, 0x62, 0x73, 0x6f,
0x63, 0x6b, 0x65, 0x74, 0x22, 0x30, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x10,
0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79,
0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x9f, 0x01, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69,
0x67, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x47, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18,
0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
0x72, 0x65, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74,
0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x77, 0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x2e,
0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x32,
0x0a, 0x15, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x5f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x5f, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x13, 0x61,
0x63, 0x63, 0x65, 0x70, 0x74, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63,
0x6f, 0x6c, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x42, 0x86, 0x01, 0x0a, 0x2b, 0x63, 0x6f, 0x6d,
0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x74, 0x72, 0x61, 0x6e,
0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x77,
0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x2b, 0x76, 0x32, 0x72, 0x61,
0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73,
0x70, 0x6f, 0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2f, 0x77, 0x65,
0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0xaa, 0x02, 0x27, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e,
0x43, 0x6f, 0x72, 0x65, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x49,
0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x57, 0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65,
0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_transport_internet_websocket_config_proto_rawDescOnce sync.Once
file_transport_internet_websocket_config_proto_rawDescData = file_transport_internet_websocket_config_proto_rawDesc
)
func file_transport_internet_websocket_config_proto_rawDescGZIP() []byte {
file_transport_internet_websocket_config_proto_rawDescOnce.Do(func() {
file_transport_internet_websocket_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_transport_internet_websocket_config_proto_rawDescData)
})
return file_transport_internet_websocket_config_proto_rawDescData
}
var file_transport_internet_websocket_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_transport_internet_websocket_config_proto_goTypes = []interface{}{
(*Header)(nil), // 0: v2ray.core.transport.internet.websocket.Header
(*Config)(nil), // 1: v2ray.core.transport.internet.websocket.Config
}
var file_transport_internet_websocket_config_proto_depIdxs = []int32{
0, // 0: v2ray.core.transport.internet.websocket.Config.header:type_name -> v2ray.core.transport.internet.websocket.Header
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_transport_internet_websocket_config_proto_init() }
func file_transport_internet_websocket_config_proto_init() {
if File_transport_internet_websocket_config_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_transport_internet_websocket_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Header); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_transport_internet_websocket_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Config); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_transport_internet_websocket_config_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_transport_internet_websocket_config_proto_goTypes,
DependencyIndexes: file_transport_internet_websocket_config_proto_depIdxs,
MessageInfos: file_transport_internet_websocket_config_proto_msgTypes,
}.Build()
File_transport_internet_websocket_config_proto = out.File
file_transport_internet_websocket_config_proto_rawDesc = nil
file_transport_internet_websocket_config_proto_goTypes = nil
file_transport_internet_websocket_config_proto_depIdxs = nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/internet/websocket/ws_test.go | transport/internet/websocket/ws_test.go | package websocket_test
import (
"context"
"runtime"
"testing"
"time"
"v2ray.com/core/common"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol/tls/cert"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/tls"
. "v2ray.com/core/transport/internet/websocket"
)
func Test_listenWSAndDial(t *testing.T) {
listen, err := ListenWS(context.Background(), net.LocalHostIP, 13146, &internet.MemoryStreamConfig{
ProtocolName: "websocket",
ProtocolSettings: &Config{
Path: "ws",
},
}, func(conn internet.Connection) {
go func(c internet.Connection) {
defer c.Close()
var b [1024]byte
_, err := c.Read(b[:])
if err != nil {
return
}
common.Must2(c.Write([]byte("Response")))
}(conn)
})
common.Must(err)
ctx := context.Background()
streamSettings := &internet.MemoryStreamConfig{
ProtocolName: "websocket",
ProtocolSettings: &Config{Path: "ws"},
}
conn, err := Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146), streamSettings)
common.Must(err)
_, err = conn.Write([]byte("Test connection 1"))
common.Must(err)
var b [1024]byte
n, err := conn.Read(b[:])
common.Must(err)
if string(b[:n]) != "Response" {
t.Error("response: ", string(b[:n]))
}
common.Must(conn.Close())
<-time.After(time.Second * 5)
conn, err = Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146), streamSettings)
common.Must(err)
_, err = conn.Write([]byte("Test connection 2"))
common.Must(err)
n, err = conn.Read(b[:])
common.Must(err)
if string(b[:n]) != "Response" {
t.Error("response: ", string(b[:n]))
}
common.Must(conn.Close())
common.Must(listen.Close())
}
func TestDialWithRemoteAddr(t *testing.T) {
listen, err := ListenWS(context.Background(), net.LocalHostIP, 13148, &internet.MemoryStreamConfig{
ProtocolName: "websocket",
ProtocolSettings: &Config{
Path: "ws",
},
}, func(conn internet.Connection) {
go func(c internet.Connection) {
defer c.Close()
var b [1024]byte
_, err := c.Read(b[:])
//common.Must(err)
if err != nil {
return
}
_, err = c.Write([]byte("Response"))
common.Must(err)
}(conn)
})
common.Must(err)
conn, err := Dial(context.Background(), net.TCPDestination(net.DomainAddress("localhost"), 13148), &internet.MemoryStreamConfig{
ProtocolName: "websocket",
ProtocolSettings: &Config{Path: "ws", Header: []*Header{{Key: "X-Forwarded-For", Value: "1.1.1.1"}}},
})
common.Must(err)
_, err = conn.Write([]byte("Test connection 1"))
common.Must(err)
var b [1024]byte
n, err := conn.Read(b[:])
common.Must(err)
if string(b[:n]) != "Response" {
t.Error("response: ", string(b[:n]))
}
common.Must(listen.Close())
}
func Test_listenWSAndDial_TLS(t *testing.T) {
if runtime.GOARCH == "arm64" {
return
}
start := time.Now()
streamSettings := &internet.MemoryStreamConfig{
ProtocolName: "websocket",
ProtocolSettings: &Config{
Path: "wss",
},
SecurityType: "tls",
SecuritySettings: &tls.Config{
AllowInsecure: true,
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil, cert.CommonName("localhost")))},
},
}
listen, err := ListenWS(context.Background(), net.LocalHostIP, 13143, streamSettings, func(conn internet.Connection) {
go func() {
_ = conn.Close()
}()
})
common.Must(err)
defer listen.Close()
conn, err := Dial(context.Background(), net.TCPDestination(net.DomainAddress("localhost"), 13143), streamSettings)
common.Must(err)
_ = conn.Close()
end := time.Now()
if !end.Before(start.Add(time.Second * 5)) {
t.Error("end: ", end, " start: ", start)
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/pipe/pipe_test.go | transport/pipe/pipe_test.go | package pipe_test
import (
"errors"
"io"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"golang.org/x/sync/errgroup"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
. "v2ray.com/core/transport/pipe"
)
func TestPipeReadWrite(t *testing.T) {
pReader, pWriter := New(WithSizeLimit(1024))
b := buf.New()
b.WriteString("abcd")
common.Must(pWriter.WriteMultiBuffer(buf.MultiBuffer{b}))
b2 := buf.New()
b2.WriteString("efg")
common.Must(pWriter.WriteMultiBuffer(buf.MultiBuffer{b2}))
rb, err := pReader.ReadMultiBuffer()
common.Must(err)
if r := cmp.Diff(rb.String(), "abcdefg"); r != "" {
t.Error(r)
}
}
func TestPipeInterrupt(t *testing.T) {
pReader, pWriter := New(WithSizeLimit(1024))
payload := []byte{'a', 'b', 'c', 'd'}
b := buf.New()
b.Write(payload)
common.Must(pWriter.WriteMultiBuffer(buf.MultiBuffer{b}))
pWriter.Interrupt()
rb, err := pReader.ReadMultiBuffer()
if err != io.ErrClosedPipe {
t.Fatal("expect io.ErrClosePipe, but got ", err)
}
if !rb.IsEmpty() {
t.Fatal("expect empty buffer, but got ", rb.Len())
}
}
func TestPipeClose(t *testing.T) {
pReader, pWriter := New(WithSizeLimit(1024))
payload := []byte{'a', 'b', 'c', 'd'}
b := buf.New()
common.Must2(b.Write(payload))
common.Must(pWriter.WriteMultiBuffer(buf.MultiBuffer{b}))
common.Must(pWriter.Close())
rb, err := pReader.ReadMultiBuffer()
common.Must(err)
if rb.String() != string(payload) {
t.Fatal("expect content ", string(payload), " but actually ", rb.String())
}
rb, err = pReader.ReadMultiBuffer()
if err != io.EOF {
t.Fatal("expected EOF, but got ", err)
}
if !rb.IsEmpty() {
t.Fatal("expect empty buffer, but got ", rb.String())
}
}
func TestPipeLimitZero(t *testing.T) {
pReader, pWriter := New(WithSizeLimit(0))
bb := buf.New()
common.Must2(bb.Write([]byte{'a', 'b'}))
common.Must(pWriter.WriteMultiBuffer(buf.MultiBuffer{bb}))
var errg errgroup.Group
errg.Go(func() error {
b := buf.New()
b.Write([]byte{'c', 'd'})
return pWriter.WriteMultiBuffer(buf.MultiBuffer{b})
})
errg.Go(func() error {
time.Sleep(time.Second)
var container buf.MultiBufferContainer
if err := buf.Copy(pReader, &container); err != nil {
return err
}
if r := cmp.Diff(container.String(), "abcd"); r != "" {
return errors.New(r)
}
return nil
})
errg.Go(func() error {
time.Sleep(time.Second * 2)
return pWriter.Close()
})
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestPipeWriteMultiThread(t *testing.T) {
pReader, pWriter := New(WithSizeLimit(0))
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(func() error {
b := buf.New()
b.WriteString("abcd")
return pWriter.WriteMultiBuffer(buf.MultiBuffer{b})
})
}
time.Sleep(time.Millisecond * 100)
pWriter.Close()
errg.Wait()
b, err := pReader.ReadMultiBuffer()
common.Must(err)
if r := cmp.Diff(b[0].Bytes(), []byte{'a', 'b', 'c', 'd'}); r != "" {
t.Error(r)
}
}
func TestInterfaces(t *testing.T) {
_ = (buf.Reader)(new(Reader))
_ = (buf.TimeoutReader)(new(Reader))
_ = (common.Interruptible)(new(Reader))
_ = (common.Interruptible)(new(Writer))
_ = (common.Closable)(new(Writer))
}
func BenchmarkPipeReadWrite(b *testing.B) {
reader, writer := New(WithoutSizeLimit())
a := buf.New()
a.Extend(buf.Size)
c := buf.MultiBuffer{a}
b.ResetTimer()
for i := 0; i < b.N; i++ {
common.Must(writer.WriteMultiBuffer(c))
d, err := reader.ReadMultiBuffer()
common.Must(err)
c = d
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/pipe/writer.go | transport/pipe/writer.go | package pipe
import (
"v2ray.com/core/common/buf"
)
// Writer is a buf.Writer that writes data into a pipe.
type Writer struct {
pipe *pipe
}
// WriteMultiBuffer implements buf.Writer.
func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error {
return w.pipe.WriteMultiBuffer(mb)
}
// Close implements io.Closer. After the pipe is closed, writing to the pipe will return io.ErrClosedPipe, while reading will return io.EOF.
func (w *Writer) Close() error {
return w.pipe.Close()
}
// Interrupt implements common.Interruptible.
func (w *Writer) Interrupt() {
w.pipe.Interrupt()
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/pipe/reader.go | transport/pipe/reader.go | package pipe
import (
"time"
"v2ray.com/core/common/buf"
)
// Reader is a buf.Reader that reads content from a pipe.
type Reader struct {
pipe *pipe
}
// ReadMultiBuffer implements buf.Reader.
func (r *Reader) ReadMultiBuffer() (buf.MultiBuffer, error) {
return r.pipe.ReadMultiBuffer()
}
// ReadMultiBufferTimeout reads content from a pipe within the given duration, or returns buf.ErrTimeout otherwise.
func (r *Reader) ReadMultiBufferTimeout(d time.Duration) (buf.MultiBuffer, error) {
return r.pipe.ReadMultiBufferTimeout(d)
}
// Interrupt implements common.Interruptible.
func (r *Reader) Interrupt() {
r.pipe.Interrupt()
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/pipe/impl.go | transport/pipe/impl.go | package pipe
import (
"errors"
"io"
"runtime"
"sync"
"time"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/signal"
"v2ray.com/core/common/signal/done"
)
type state byte
const (
open state = iota
closed
errord
)
type pipeOption struct {
limit int32 // maximum buffer size in bytes
discardOverflow bool
}
func (o *pipeOption) isFull(curSize int32) bool {
return o.limit >= 0 && curSize > o.limit
}
type pipe struct {
sync.Mutex
data buf.MultiBuffer
readSignal *signal.Notifier
writeSignal *signal.Notifier
done *done.Instance
option pipeOption
state state
}
var errBufferFull = errors.New("buffer full")
var errSlowDown = errors.New("slow down")
func (p *pipe) getState(forRead bool) error {
switch p.state {
case open:
if !forRead && p.option.isFull(p.data.Len()) {
return errBufferFull
}
return nil
case closed:
if !forRead {
return io.ErrClosedPipe
}
if !p.data.IsEmpty() {
return nil
}
return io.EOF
case errord:
return io.ErrClosedPipe
default:
panic("impossible case")
}
}
func (p *pipe) readMultiBufferInternal() (buf.MultiBuffer, error) {
p.Lock()
defer p.Unlock()
if err := p.getState(true); err != nil {
return nil, err
}
data := p.data
p.data = nil
return data, nil
}
func (p *pipe) ReadMultiBuffer() (buf.MultiBuffer, error) {
for {
data, err := p.readMultiBufferInternal()
if data != nil || err != nil {
p.writeSignal.Signal()
return data, err
}
select {
case <-p.readSignal.Wait():
case <-p.done.Wait():
}
}
}
func (p *pipe) ReadMultiBufferTimeout(d time.Duration) (buf.MultiBuffer, error) {
timer := time.NewTimer(d)
defer timer.Stop()
for {
data, err := p.readMultiBufferInternal()
if data != nil || err != nil {
p.writeSignal.Signal()
return data, err
}
select {
case <-p.readSignal.Wait():
case <-p.done.Wait():
case <-timer.C:
return nil, buf.ErrReadTimeout
}
}
}
func (p *pipe) writeMultiBufferInternal(mb buf.MultiBuffer) error {
p.Lock()
defer p.Unlock()
if err := p.getState(false); err != nil {
return err
}
if p.data == nil {
p.data = mb
return nil
}
p.data, _ = buf.MergeMulti(p.data, mb)
return errSlowDown
}
func (p *pipe) WriteMultiBuffer(mb buf.MultiBuffer) error {
if mb.IsEmpty() {
return nil
}
for {
err := p.writeMultiBufferInternal(mb)
if err == nil {
p.readSignal.Signal()
return nil
}
if err == errSlowDown {
p.readSignal.Signal()
// Yield current goroutine. Hopefully the reading counterpart can pick up the payload.
runtime.Gosched()
return nil
}
if err == errBufferFull && p.option.discardOverflow {
buf.ReleaseMulti(mb)
return nil
}
if err != errBufferFull {
buf.ReleaseMulti(mb)
p.readSignal.Signal()
return err
}
select {
case <-p.writeSignal.Wait():
case <-p.done.Wait():
return io.ErrClosedPipe
}
}
}
func (p *pipe) Close() error {
p.Lock()
defer p.Unlock()
if p.state == closed || p.state == errord {
return nil
}
p.state = closed
common.Must(p.done.Close())
return nil
}
// Interrupt implements common.Interruptible.
func (p *pipe) Interrupt() {
p.Lock()
defer p.Unlock()
if p.state == closed || p.state == errord {
return
}
p.state = errord
if !p.data.IsEmpty() {
buf.ReleaseMulti(p.data)
p.data = nil
}
common.Must(p.done.Close())
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/transport/pipe/pipe.go | transport/pipe/pipe.go | package pipe
import (
"context"
"v2ray.com/core/common/signal"
"v2ray.com/core/common/signal/done"
"v2ray.com/core/features/policy"
)
// Option for creating new Pipes.
type Option func(*pipeOption)
// WithoutSizeLimit returns an Option for Pipe to have no size limit.
func WithoutSizeLimit() Option {
return func(opt *pipeOption) {
opt.limit = -1
}
}
// WithSizeLimit returns an Option for Pipe to have the given size limit.
func WithSizeLimit(limit int32) Option {
return func(opt *pipeOption) {
opt.limit = limit
}
}
// DiscardOverflow returns an Option for Pipe to discard writes if full.
func DiscardOverflow() Option {
return func(opt *pipeOption) {
opt.discardOverflow = true
}
}
// OptionsFromContext returns a list of Options from context.
func OptionsFromContext(ctx context.Context) []Option {
var opt []Option
bp := policy.BufferPolicyFromContext(ctx)
if bp.PerConnection >= 0 {
opt = append(opt, WithSizeLimit(bp.PerConnection))
} else {
opt = append(opt, WithoutSizeLimit())
}
return opt
}
// New creates a new Reader and Writer that connects to each other.
func New(opts ...Option) (*Reader, *Writer) {
p := &pipe{
readSignal: signal.NewNotifier(),
writeSignal: signal.NewNotifier(),
done: done.New(),
option: pipeOption{
limit: -1,
},
}
for _, opt := range opts {
opt(&(p.option))
}
return &Reader{
pipe: p,
}, &Writer{
pipe: p,
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/release.go | pkg/cmd/release/release.go | package release
import (
cmdCreate "github.com/cli/cli/v2/pkg/cmd/release/create"
cmdDelete "github.com/cli/cli/v2/pkg/cmd/release/delete"
cmdDeleteAsset "github.com/cli/cli/v2/pkg/cmd/release/delete-asset"
cmdDownload "github.com/cli/cli/v2/pkg/cmd/release/download"
cmdUpdate "github.com/cli/cli/v2/pkg/cmd/release/edit"
cmdList "github.com/cli/cli/v2/pkg/cmd/release/list"
cmdUpload "github.com/cli/cli/v2/pkg/cmd/release/upload"
cmdVerify "github.com/cli/cli/v2/pkg/cmd/release/verify"
cmdVerifyAsset "github.com/cli/cli/v2/pkg/cmd/release/verify-asset"
cmdView "github.com/cli/cli/v2/pkg/cmd/release/view"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdRelease(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "release <command>",
Short: "Manage releases",
GroupID: "core",
}
cmdutil.EnableRepoOverride(cmd, f)
cmdutil.AddGroup(cmd, "General commands",
cmdList.NewCmdList(f, nil),
cmdCreate.NewCmdCreate(f, nil),
)
cmdutil.AddGroup(cmd, "Targeted commands",
cmdView.NewCmdView(f, nil),
cmdUpdate.NewCmdEdit(f, nil),
cmdUpload.NewCmdUpload(f, nil),
cmdDownload.NewCmdDownload(f, nil),
cmdDelete.NewCmdDelete(f, nil),
cmdDeleteAsset.NewCmdDeleteAsset(f, nil),
cmdVerify.NewCmdVerify(f, nil),
cmdVerifyAsset.NewCmdVerifyAsset(f, nil),
)
return cmd
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/verify/verify.go | pkg/cmd/release/verify/verify.go | package verify
import (
"context"
"fmt"
"net/http"
"github.com/MakeNowJust/heredoc"
v1 "github.com/in-toto/attestation/go/v1"
"google.golang.org/protobuf/encoding/protojson"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmd/attestation/api"
"github.com/cli/cli/v2/pkg/cmd/attestation/artifact"
att_io "github.com/cli/cli/v2/pkg/cmd/attestation/io"
"github.com/cli/cli/v2/pkg/cmd/attestation/verification"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
type VerifyOptions struct {
TagName string
BaseRepo ghrepo.Interface
Exporter cmdutil.Exporter
TrustedRoot string
}
type VerifyConfig struct {
HttpClient *http.Client
IO *iostreams.IOStreams
Opts *VerifyOptions
AttClient api.Client
AttVerifier shared.Verifier
}
func NewCmdVerify(f *cmdutil.Factory, runF func(config *VerifyConfig) error) *cobra.Command {
opts := &VerifyOptions{}
cmd := &cobra.Command{
Use: "verify [<tag>]",
Short: "Verify the attestation for a release",
Args: cobra.MaximumNArgs(1),
Long: heredoc.Doc(`
Verify that a GitHub Release is accompanied by a valid cryptographically signed attestation.
An attestation is a claim made by GitHub regarding a release and its assets.
This command checks that the specified release (or the latest release, if no tag is given) has a valid attestation.
It fetches the attestation for the release and prints metadata about all assets referenced in the attestation, including their digests.
`),
Example: heredoc.Doc(`
# Verify the latest release
gh release verify
# Verify a specific release by tag
gh release verify v1.2.3
# Verify a specific release by tag and output the attestation in JSON format
gh release verify v1.2.3 --format json
`),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
opts.TagName = args[0]
}
baseRepo, err := f.BaseRepo()
if err != nil {
return fmt.Errorf("failed to determine base repository: %w", err)
}
opts.BaseRepo = baseRepo
httpClient, err := f.HttpClient()
if err != nil {
return err
}
io := f.IOStreams
attClient := api.NewLiveClient(httpClient, baseRepo.RepoHost(), att_io.NewHandler(io))
attVerifier := &shared.AttestationVerifier{
AttClient: attClient,
HttpClient: httpClient,
IO: io,
TrustedRoot: opts.TrustedRoot,
}
config := &VerifyConfig{
Opts: opts,
HttpClient: httpClient,
AttClient: attClient,
AttVerifier: attVerifier,
IO: io,
}
if runF != nil {
return runF(config)
}
return verifyRun(config)
},
}
cmdutil.AddFormatFlags(cmd, &opts.Exporter)
cmd.Flags().StringVarP(&opts.TrustedRoot, "custom-trusted-root", "", "", "Path to a trusted_root.jsonl file; likely for offline verification.")
cmd.Flags().MarkHidden("custom-trusted-root")
return cmd
}
func verifyRun(config *VerifyConfig) error {
ctx := context.Background()
opts := config.Opts
baseRepo := opts.BaseRepo
tagName := opts.TagName
if tagName == "" {
release, err := shared.FetchLatestRelease(ctx, config.HttpClient, baseRepo)
if err != nil {
return err
}
tagName = release.TagName
}
// Retrieve the ref for the release tag
ref, err := shared.FetchRefSHA(ctx, config.HttpClient, baseRepo, tagName)
if err != nil {
return err
}
releaseRefDigest := artifact.NewDigestedArtifactForRelease(ref, "sha1")
// Find all the attestations for the release tag SHA
attestations, err := config.AttClient.GetByDigest(api.FetchParams{
Digest: releaseRefDigest.DigestWithAlg(),
PredicateType: "release",
Owner: baseRepo.RepoOwner(),
Repo: baseRepo.RepoOwner() + "/" + baseRepo.RepoName(),
Initiator: "github",
// TODO: Allow this value to be set via a flag.
// The limit is set to 100 to ensure we fetch all attestations for a given SHA.
// While multiple attestations can exist for a single SHA,
// only one attestation is associated with each release tag.
Limit: 100,
})
if err != nil {
return fmt.Errorf("no attestations for tag %s (%s)", tagName, releaseRefDigest.DigestWithAlg())
}
// Filter attestations by tag name
filteredAttestations, err := shared.FilterAttestationsByTag(attestations, tagName)
if err != nil {
return fmt.Errorf("error parsing attestations for tag %s: %w", tagName, err)
}
if len(filteredAttestations) == 0 {
return fmt.Errorf("no attestations found for release %s in %s", tagName, baseRepo.RepoName())
}
if len(filteredAttestations) > 1 {
return fmt.Errorf("duplicate attestations found for release %s in %s", tagName, baseRepo.RepoName())
}
// Verify attestation
verified, err := config.AttVerifier.VerifyAttestation(releaseRefDigest, filteredAttestations[0])
if err != nil {
return fmt.Errorf("failed to verify attestations for tag %s: %w", tagName, err)
}
// If an exporter is provided with the --json flag, write the results to the terminal in JSON format
if opts.Exporter != nil {
return opts.Exporter.Write(config.IO, verified)
}
io := config.IO
cs := io.ColorScheme()
fmt.Fprintf(io.Out, "Resolved tag %s to %s\n", tagName, releaseRefDigest.DigestWithAlg())
fmt.Fprint(io.Out, "Loaded attestation from GitHub API\n")
fmt.Fprintf(io.Out, cs.Green("%s Release %s verified!\n"), cs.SuccessIcon(), tagName)
fmt.Fprintln(io.Out)
if err := printVerifiedSubjects(io, verified); err != nil {
return err
}
return nil
}
func printVerifiedSubjects(io *iostreams.IOStreams, att *verification.AttestationProcessingResult) error {
cs := io.ColorScheme()
w := io.Out
statement := att.Attestation.Bundle.GetDsseEnvelope().Payload
var statementData v1.Statement
err := protojson.Unmarshal([]byte(statement), &statementData)
if err != nil {
return err
}
// If there aren't at least two subjects, there are no assets to display
if len(statementData.Subject) < 2 {
return nil
}
fmt.Fprintln(w, cs.Bold("Assets"))
table := tableprinter.New(io, tableprinter.WithHeader("Name", "Digest"))
for _, s := range statementData.Subject {
name := s.Name
digest := s.Digest
if name != "" {
digestStr := ""
for key, value := range digest {
digestStr = key + ":" + value
}
table.AddField(name)
table.AddField(digestStr)
table.EndRow()
}
}
err = table.Render()
if err != nil {
return err
}
fmt.Fprintln(w)
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/verify/verify_test.go | pkg/cmd/release/verify/verify_test.go | package verify
import (
"bytes"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/attestation/api"
"github.com/cli/cli/v2/pkg/cmd/attestation/test/data"
"github.com/cli/cli/v2/pkg/cmd/attestation/verification"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdVerify_Args(t *testing.T) {
tests := []struct {
name string
args []string
wantTag string
wantErr string
}{
{
name: "valid tag arg",
args: []string{"v1.2.3"},
wantTag: "v1.2.3",
},
{
name: "no tag arg",
args: []string{},
wantTag: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
testIO, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: testIO,
HttpClient: func() (*http.Client, error) {
return nil, nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
}
var cfg *VerifyConfig
cmd := NewCmdVerify(f, func(c *VerifyConfig) error {
cfg = c
return nil
})
cmd.SetArgs(tt.args)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err := cmd.ExecuteC()
require.NoError(t, err)
assert.Equal(t, tt.wantTag, cfg.Opts.TagName)
})
}
}
func Test_verifyRun_Success(t *testing.T) {
ios, _, _, _ := iostreams.Test()
tagName := "v6"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
result := &verification.AttestationProcessingResult{
Attestation: &api.Attestation{
Bundle: data.GitHubReleaseBundle(t),
BundleURL: "https://example.com",
},
VerificationResult: nil,
}
cfg := &VerifyConfig{
Opts: &VerifyOptions{
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewTestClient(),
AttVerifier: shared.NewMockVerifier(result),
}
err = verifyRun(cfg)
require.NoError(t, err)
}
func Test_verifyRun_FailedNoAttestations(t *testing.T) {
ios, _, _, _ := iostreams.Test()
tagName := "v1"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
cfg := &VerifyConfig{
Opts: &VerifyOptions{
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewFailTestClient(),
AttVerifier: nil,
}
err = verifyRun(cfg)
require.ErrorContains(t, err, "no attestations for tag v1")
}
func Test_verifyRun_FailedTagNotInAttestation(t *testing.T) {
ios, _, _, _ := iostreams.Test()
// Tag name does not match the one present in the attestation which
// will be returned by the mock client. Simulates a scenario where
// multiple releases may point to the same commit SHA, but not all
// of them are attested.
tagName := "v1.2.3"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
cfg := &VerifyConfig{
Opts: &VerifyOptions{
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewTestClient(),
AttVerifier: nil,
}
err = verifyRun(cfg)
require.ErrorContains(t, err, "no attestations found for release v1.2.3")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/delete-asset/delete_asset_test.go | pkg/cmd/release/delete-asset/delete_asset_test.go | package deleteasset
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdDeleteAsset(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want DeleteAssetOptions
wantErr string
}{
{
name: "tag and asset arguments",
args: "v1.2.3 test-asset",
isTTY: true,
want: DeleteAssetOptions{
TagName: "v1.2.3",
SkipConfirm: false,
AssetName: "test-asset",
},
},
{
name: "skip confirm",
args: "v1.2.3 test-asset -y",
isTTY: true,
want: DeleteAssetOptions{
TagName: "v1.2.3",
SkipConfirm: true,
AssetName: "test-asset",
},
},
{
name: "no arguments",
args: "",
isTTY: true,
wantErr: "accepts 2 arg(s), received 0",
},
{
name: "one arguments",
args: "v1.2.3",
isTTY: true,
wantErr: "accepts 2 arg(s), received 1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *DeleteAssetOptions
cmd := NewCmdDeleteAsset(f, func(o *DeleteAssetOptions) error {
opts = o
return nil
})
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.TagName, opts.TagName)
assert.Equal(t, tt.want.SkipConfirm, opts.SkipConfirm)
assert.Equal(t, tt.want.AssetName, opts.AssetName)
})
}
}
func Test_deleteAssetRun(t *testing.T) {
tests := []struct {
name string
isTTY bool
opts DeleteAssetOptions
prompterStubs func(*prompter.PrompterMock)
wantErr string
wantStdout string
wantStderr string
}{
{
name: "interactive confirm",
isTTY: true,
opts: DeleteAssetOptions{
TagName: "v1.2.3",
AssetName: "test-asset",
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.ConfirmFunc = func(p string, d bool) (bool, error) {
if p == "Delete asset test-asset in release v1.2.3 in OWNER/REPO?" {
return true, nil
}
return false, prompter.NoSuchPromptErr(p)
}
},
wantStdout: ``,
wantStderr: "✓ Deleted asset test-asset from release v1.2.3\n",
},
{
name: "skipping confirmation",
isTTY: true,
opts: DeleteAssetOptions{
TagName: "v1.2.3",
SkipConfirm: true,
AssetName: "test-asset",
},
wantStdout: ``,
wantStderr: "✓ Deleted asset test-asset from release v1.2.3\n",
},
{
name: "non-interactive",
isTTY: false,
opts: DeleteAssetOptions{
TagName: "v1.2.3",
SkipConfirm: false,
AssetName: "test-asset",
},
wantStdout: ``,
wantStderr: ``,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
shared.StubFetchRelease(t, fakeHTTP, "OWNER", "REPO", tt.opts.TagName, `{
"tag_name": "v1.2.3",
"draft": false,
"url": "https://api.github.com/repos/OWNER/REPO/releases/23456",
"assets": [
{
"url": "https://api.github.com/repos/OWNER/REPO/releases/assets/1",
"id": 1,
"name": "test-asset"
}
]
}`)
fakeHTTP.Register(httpmock.REST("DELETE", "repos/OWNER/REPO/releases/assets/1"), httpmock.StatusStringResponse(204, ""))
pm := &prompter.PrompterMock{}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
tt.opts.IO = ios
tt.opts.Prompter = pm
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: fakeHTTP}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
err := deleteAssetRun(&tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/delete-asset/delete_asset.go | pkg/cmd/release/delete-asset/delete_asset.go | package deleteasset
import (
"context"
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type iprompter interface {
Confirm(string, bool) (bool, error)
}
type DeleteAssetOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Prompter iprompter
TagName string
SkipConfirm bool
AssetName string
}
func NewCmdDeleteAsset(f *cmdutil.Factory, runF func(*DeleteAssetOptions) error) *cobra.Command {
opts := &DeleteAssetOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "delete-asset <tag> <asset-name>",
Short: "Delete an asset from a release",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
opts.TagName = args[0]
opts.AssetName = args[1]
if runF != nil {
return runF(opts)
}
return deleteAssetRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.SkipConfirm, "yes", "y", false, "Skip the confirmation prompt")
return cmd
}
func deleteAssetRun(opts *DeleteAssetOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
release, err := shared.FetchRelease(context.Background(), httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
if !opts.SkipConfirm && opts.IO.CanPrompt() {
confirmed, err := opts.Prompter.Confirm(
fmt.Sprintf("Delete asset %s in release %s in %s?", opts.AssetName, release.TagName, ghrepo.FullName(baseRepo)),
true)
if err != nil {
return err
}
if !confirmed {
return cmdutil.CancelError
}
}
var assetURL string
for _, a := range release.Assets {
if a.Name == opts.AssetName {
assetURL = a.APIURL
break
}
}
if assetURL == "" {
return fmt.Errorf("asset %s not found in release %s", opts.AssetName, release.TagName)
}
err = deleteAsset(httpClient, assetURL)
if err != nil {
return err
}
if !opts.IO.IsStdoutTTY() || !opts.IO.IsStderrTTY() {
return nil
}
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.ErrOut, "%s Deleted asset %s from release %s\n", cs.SuccessIconWithColor(cs.Red), opts.AssetName, release.TagName)
return nil
}
func deleteAsset(httpClient *http.Client, assetURL string) error {
req, err := http.NewRequest("DELETE", assetURL, nil)
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/delete/delete.go | pkg/cmd/release/delete/delete.go | package delete
import (
"context"
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type iprompter interface {
Confirm(string, bool) (bool, error)
}
type DeleteOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
RepoOverride string
Prompter iprompter
TagName string
SkipConfirm bool
CleanupTag bool
}
func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command {
opts := &DeleteOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "delete <tag>",
Short: "Delete a release",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
opts.RepoOverride, _ = cmd.Flags().GetString("repo")
opts.TagName = args[0]
if runF != nil {
return runF(opts)
}
return deleteRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.SkipConfirm, "yes", "y", false, "Skip the confirmation prompt")
cmd.Flags().BoolVar(&opts.CleanupTag, "cleanup-tag", false, "Delete the specified tag in addition to its release")
return cmd
}
func deleteRun(opts *DeleteOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
release, err := shared.FetchRelease(context.Background(), httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
if !opts.SkipConfirm && opts.IO.CanPrompt() {
confirmed, err := opts.Prompter.Confirm(
fmt.Sprintf("Delete release %s in %s?", release.TagName, ghrepo.FullName(baseRepo)), true)
if err != nil {
return err
}
if !confirmed {
return cmdutil.CancelError
}
}
err = deleteRelease(httpClient, release.APIURL)
if err != nil {
return err
}
var cleanupMessage string
if opts.CleanupTag {
if err := deleteTag(httpClient, baseRepo, release.TagName); err != nil {
return err
}
if opts.RepoOverride == "" {
_ = opts.GitClient.DeleteLocalTag(context.Background(), release.TagName)
}
cleanupMessage = " and tag"
}
if !opts.IO.IsStdoutTTY() || !opts.IO.IsStderrTTY() {
return nil
}
iofmt := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.ErrOut, "%s Deleted release%s %s\n", iofmt.SuccessIconWithColor(iofmt.Red), cleanupMessage, release.TagName)
if !release.IsDraft && !opts.CleanupTag {
fmt.Fprintf(opts.IO.ErrOut, "%s Note that the %s git tag still remains in the repository\n", iofmt.WarningIcon(), release.TagName)
}
return nil
}
func deleteRelease(httpClient *http.Client, releaseURL string) error {
req, err := http.NewRequest("DELETE", releaseURL, nil)
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
return nil
}
func deleteTag(httpClient *http.Client, baseRepo ghrepo.Interface, tagName string) error {
path := fmt.Sprintf("repos/%s/%s/git/refs/tags/%s", baseRepo.RepoOwner(), baseRepo.RepoName(), tagName)
url := ghinstance.RESTPrefix(baseRepo.RepoHost()) + path
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/delete/delete_test.go | pkg/cmd/release/delete/delete_test.go | package delete
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdDelete(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want DeleteOptions
wantErr string
}{
{
name: "version argument",
args: "v1.2.3",
isTTY: true,
want: DeleteOptions{
TagName: "v1.2.3",
SkipConfirm: false,
CleanupTag: false,
},
},
{
name: "skip confirm",
args: "v1.2.3 -y",
isTTY: true,
want: DeleteOptions{
TagName: "v1.2.3",
SkipConfirm: true,
CleanupTag: false,
},
},
{
name: "cleanup tag",
args: "v1.2.3 --cleanup-tag",
isTTY: true,
want: DeleteOptions{
TagName: "v1.2.3",
SkipConfirm: false,
CleanupTag: true,
},
},
{
name: "no arguments",
args: "",
isTTY: true,
wantErr: "accepts 1 arg(s), received 0",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *DeleteOptions
cmd := NewCmdDelete(f, func(o *DeleteOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.TagName, opts.TagName)
assert.Equal(t, tt.want.SkipConfirm, opts.SkipConfirm)
assert.Equal(t, tt.want.CleanupTag, opts.CleanupTag)
})
}
}
func Test_deleteRun(t *testing.T) {
tests := []struct {
name string
isTTY bool
opts DeleteOptions
prompterStubs func(*prompter.PrompterMock)
runStubs func(*run.CommandStubber)
wantErr string
wantStdout string
wantStderr string
}{
{
name: "interactive confirm",
isTTY: true,
opts: DeleteOptions{
TagName: "v1.2.3",
},
wantStdout: "",
wantStderr: "✓ Deleted release v1.2.3\n! Note that the v1.2.3 git tag still remains in the repository\n",
prompterStubs: func(pm *prompter.PrompterMock) {
pm.ConfirmFunc = func(p string, d bool) (bool, error) {
if p == "Delete release v1.2.3 in OWNER/REPO?" {
return true, nil
}
return false, prompter.NoSuchPromptErr(p)
}
},
},
{
name: "skipping confirmation",
isTTY: true,
opts: DeleteOptions{
TagName: "v1.2.3",
SkipConfirm: true,
CleanupTag: false,
},
wantStdout: ``,
wantStderr: heredoc.Doc(`
✓ Deleted release v1.2.3
! Note that the v1.2.3 git tag still remains in the repository
`),
},
{
name: "non-interactive",
isTTY: false,
opts: DeleteOptions{
TagName: "v1.2.3",
SkipConfirm: false,
CleanupTag: false,
},
wantStdout: ``,
wantStderr: ``,
},
{
name: "cleanup-tag & skipping confirmation",
isTTY: true,
opts: DeleteOptions{
TagName: "v1.2.3",
SkipConfirm: true,
CleanupTag: true,
},
runStubs: func(rs *run.CommandStubber) {
rs.Register(`git tag -d v1.2.3`, 0, "")
},
wantStdout: ``,
wantStderr: heredoc.Doc(`
✓ Deleted release and tag v1.2.3
`),
},
{
name: "cleanup-tag",
isTTY: false,
opts: DeleteOptions{
TagName: "v1.2.3",
SkipConfirm: false,
CleanupTag: true,
},
runStubs: func(rs *run.CommandStubber) {
rs.Register(`git tag -d v1.2.3`, 0, "")
},
wantStdout: ``,
wantStderr: ``,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
pm := &prompter.PrompterMock{}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
fakeHTTP := &httpmock.Registry{}
shared.StubFetchRelease(t, fakeHTTP, "OWNER", "REPO", tt.opts.TagName, `{
"tag_name": "v1.2.3",
"draft": false,
"url": "https://api.github.com/repos/OWNER/REPO/releases/23456"
}`)
fakeHTTP.Register(httpmock.REST("DELETE", "repos/OWNER/REPO/releases/23456"), httpmock.StatusStringResponse(204, ""))
fakeHTTP.Register(httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/tags/v1.2.3"), httpmock.StatusStringResponse(204, ""))
rs, teardown := run.Stub()
defer teardown(t)
if tt.runStubs != nil {
tt.runStubs(rs)
}
tt.opts.IO = ios
tt.opts.Prompter = pm
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: fakeHTTP}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
tt.opts.GitClient = &git.Client{GitPath: "some/path/git"}
err := deleteRun(&tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/list/list_test.go | pkg/cmd/release/list/list_test.go | package list
import (
"bytes"
"fmt"
"io"
"net/http"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdList(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want ListOptions
wantErr string
}{
{
name: "no arguments",
args: "",
isTTY: true,
want: ListOptions{
LimitResults: 30,
ExcludeDrafts: false,
ExcludePreReleases: false,
Order: "desc",
},
},
{
name: "exclude drafts",
args: "--exclude-drafts",
want: ListOptions{
LimitResults: 30,
ExcludeDrafts: true,
ExcludePreReleases: false,
Order: "desc",
},
},
{
name: "exclude pre-releases",
args: "--exclude-pre-releases",
want: ListOptions{
LimitResults: 30,
ExcludeDrafts: false,
ExcludePreReleases: true,
Order: "desc",
},
},
{
name: "with order",
args: "--order asc",
want: ListOptions{
LimitResults: 30,
ExcludeDrafts: false,
ExcludePreReleases: false,
Order: "asc",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *ListOptions
cmd := NewCmdList(f, func(o *ListOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.LimitResults, opts.LimitResults)
assert.Equal(t, tt.want.ExcludeDrafts, opts.ExcludeDrafts)
assert.Equal(t, tt.want.ExcludePreReleases, opts.ExcludePreReleases)
assert.Equal(t, tt.want.Order, opts.Order)
})
}
}
func Test_listRun(t *testing.T) {
oneDayAgo := time.Now().Add(time.Duration(-24) * time.Hour)
frozenTime, err := time.Parse(time.RFC3339, "2020-08-31T15:44:24+02:00")
require.NoError(t, err)
httpStubs := func(createdAt time.Time) func(t *testing.T, reg *httpmock.Registry) {
return func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`\bRepositoryReleaseList\(`),
httpmock.GraphQLQuery(
fmt.Sprintf(`
{ "data": { "repository": { "releases": {
"nodes": [
{
"name": "",
"tagName": "v1.1.0",
"isLatest": false,
"isDraft": true,
"isPrerelease": false,
"immutable": false,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
},
{
"name": "The big 1.0",
"tagName": "v1.0.0",
"isLatest": true,
"isDraft": false,
"isPrerelease": false,
"immutable": false,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
},
{
"name": "1.0 release candidate",
"tagName": "v1.0.0-pre.2",
"isLatest": false,
"isDraft": false,
"isPrerelease": true,
"immutable": true,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
},
{
"name": "New features",
"tagName": "v0.9.2",
"isLatest": false,
"isDraft": false,
"isPrerelease": false,
"immutable": true,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
}
]
} } } }`, createdAt.Format(time.RFC3339)),
func(s string, m map[string]interface{}) {
// Assert "immutable" field is requested
assert.Regexp(t, `\bimmutable\b`, s)
},
),
)
}
}
// TODO: immutableReleaseFullSupport
// Delete this when covered GHES versions support immutable releases.
httpStubsWithoutImmutableReleases := func(createdAt time.Time) func(t *testing.T, reg *httpmock.Registry) {
return func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`\bRepositoryReleaseList\(`),
httpmock.GraphQLQuery(
fmt.Sprintf(`
{ "data": { "repository": { "releases": {
"nodes": [
{
"name": "",
"tagName": "v1.1.0",
"isLatest": false,
"isDraft": true,
"isPrerelease": false,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
},
{
"name": "The big 1.0",
"tagName": "v1.0.0",
"isLatest": true,
"isDraft": false,
"isPrerelease": false,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
},
{
"name": "1.0 release candidate",
"tagName": "v1.0.0-pre.2",
"isLatest": false,
"isDraft": false,
"isPrerelease": true,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
},
{
"name": "New features",
"tagName": "v0.9.2",
"isLatest": false,
"isDraft": false,
"isPrerelease": false,
"createdAt": "%[1]s",
"publishedAt": "%[1]s"
}
]
} } } }`, createdAt.Format(time.RFC3339)),
func(s string, m map[string]interface{}) {
// Assert "immutable" field is NOT requested
assert.NotRegexp(t, `\bimmutable\b`, s)
},
),
)
}
}
tests := []struct {
name string
isTTY bool
opts ListOptions
jsonFields []string
httpStubs func(*testing.T, *httpmock.Registry)
wantErr string
wantStdout string
wantStderr string
}{
{
// TODO: immutableReleaseFullSupport
// Delete this when covered GHES versions support immutable releases.
name: "list releases, immutable releases unsupported",
isTTY: true,
opts: ListOptions{
Detector: &fd.DisabledDetectorMock{},
LimitResults: 30,
},
httpStubs: httpStubsWithoutImmutableReleases(oneDayAgo),
wantStdout: heredoc.Doc(`
TITLE TYPE TAG NAME PUBLISHED
v1.1.0 Draft v1.1.0 about 1 day ago
The big 1.0 Latest v1.0.0 about 1 day ago
1.0 release candidate Pre-release v1.0.0-pre.2 about 1 day ago
New features v0.9.2 about 1 day ago
`),
wantStderr: ``,
},
{
name: "list releases, immutable releases supported",
isTTY: true,
opts: ListOptions{
Detector: &fd.EnabledDetectorMock{},
LimitResults: 30,
},
httpStubs: httpStubs(oneDayAgo),
wantStdout: heredoc.Doc(`
TITLE TYPE TAG NAME PUBLISHED
v1.1.0 Draft v1.1.0 about 1 day ago
The big 1.0 Latest v1.0.0 about 1 day ago
1.0 release candidate Pre-release v1.0.0-pre.2 about 1 day ago
New features v0.9.2 about 1 day ago
`),
wantStderr: ``,
},
{
// TODO: immutableReleaseFullSupport
// Delete this when covered GHES versions support immutable releases.
name: "machine-readable, immutable releases unsupported",
isTTY: false,
opts: ListOptions{
Detector: &fd.DisabledDetectorMock{},
LimitResults: 30,
},
httpStubs: httpStubsWithoutImmutableReleases(frozenTime),
wantStdout: heredoc.Doc(`
v1.1.0 Draft v1.1.0 2020-08-31T15:44:24+02:00
The big 1.0 Latest v1.0.0 2020-08-31T15:44:24+02:00
1.0 release candidate Pre-release v1.0.0-pre.2 2020-08-31T15:44:24+02:00
New features v0.9.2 2020-08-31T15:44:24+02:00
`),
wantStderr: ``,
},
{
name: "machine-readable, immutable releases supported",
isTTY: false,
opts: ListOptions{
Detector: &fd.EnabledDetectorMock{},
LimitResults: 30,
},
httpStubs: httpStubs(frozenTime),
wantStdout: heredoc.Doc(`
v1.1.0 Draft v1.1.0 2020-08-31T15:44:24+02:00
The big 1.0 Latest v1.0.0 2020-08-31T15:44:24+02:00
1.0 release candidate Pre-release v1.0.0-pre.2 2020-08-31T15:44:24+02:00
New features v0.9.2 2020-08-31T15:44:24+02:00
`),
wantStderr: ``,
},
{
// TODO: immutableReleaseFullSupport
// Delete this when covered GHES versions support immutable releases.
//
// This test ensures on unsupported hosts, "isImmutable" always defaults to false.
name: "JSON, immutable releases unsupported",
isTTY: false,
jsonFields: []string{"name", "isImmutable"},
opts: ListOptions{
Detector: &fd.DisabledDetectorMock{},
LimitResults: 30,
},
httpStubs: httpStubsWithoutImmutableReleases(frozenTime),
wantStdout: `[{"isImmutable":false,"name":""},{"isImmutable":false,"name":"The big 1.0"},{"isImmutable":false,"name":"1.0 release candidate"},{"isImmutable":false,"name":"New features"}]` + "\n",
wantStderr: ``,
},
{
name: "JSON, immutable releases supported",
isTTY: false,
jsonFields: []string{"name", "isImmutable"},
opts: ListOptions{
Detector: &fd.EnabledDetectorMock{},
LimitResults: 30,
},
httpStubs: httpStubs(frozenTime),
wantStdout: `[{"isImmutable":false,"name":""},{"isImmutable":false,"name":"The big 1.0"},{"isImmutable":true,"name":"1.0 release candidate"},{"isImmutable":true,"name":"New features"}]` + "\n",
wantStderr: ``,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(t, fakeHTTP)
}
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: fakeHTTP}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
if tt.jsonFields != nil {
exporter := cmdutil.NewJSONExporter()
exporter.SetFields(tt.jsonFields)
tt.opts.Exporter = exporter
}
err := listRun(&tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
func TestExportReleases(t *testing.T) {
ios, _, stdout, _ := iostreams.Test()
createdAt, _ := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z")
publishedAt, _ := time.Parse(time.RFC3339, "2024-02-01T00:00:00Z")
rs := []Release{{
Name: "v1",
TagName: "tag",
IsDraft: true,
IsLatest: false,
IsPrerelease: true,
IsImmutable: true,
CreatedAt: createdAt,
PublishedAt: publishedAt,
}}
exporter := cmdutil.NewJSONExporter()
exporter.SetFields(releaseFields)
require.NoError(t, exporter.Write(ios, rs))
require.JSONEq(t,
`[{"createdAt":"2024-01-01T00:00:00Z","isDraft":true,"isLatest":false,"isPrerelease":true,"isImmutable":true,"name":"v1","publishedAt":"2024-02-01T00:00:00Z","tagName":"tag"}]`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/list/list.go | pkg/cmd/release/list/list.go | package list
import (
"fmt"
"net/http"
"time"
"github.com/cli/cli/v2/api"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type ListOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Exporter cmdutil.Exporter
Detector fd.Detector
LimitResults int
ExcludeDrafts bool
ExcludePreReleases bool
Order string
}
func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
opts := &ListOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "list",
Short: "List releases in a repository",
Aliases: []string{"ls"},
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if runF != nil {
return runF(opts)
}
return listRun(opts)
},
}
cmd.Flags().IntVarP(&opts.LimitResults, "limit", "L", 30, "Maximum number of items to fetch")
cmd.Flags().BoolVar(&opts.ExcludeDrafts, "exclude-drafts", false, "Exclude draft releases")
cmd.Flags().BoolVar(&opts.ExcludePreReleases, "exclude-pre-releases", false, "Exclude pre-releases")
cmdutil.StringEnumFlag(cmd, &opts.Order, "order", "O", "desc", []string{"asc", "desc"}, "Order of releases returned")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, releaseFields)
return cmd
}
func listRun(opts *ListOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
// TODO: immutableReleaseFullSupport
// The detector is not needed when covered GHES versions fully support
// immutable releases (probably when 3.18 goes EOL).
if opts.Detector == nil {
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, baseRepo.RepoHost())
}
releaseFeatures, err := opts.Detector.ReleaseFeatures()
if err != nil {
return err
}
releases, err := fetchReleases(httpClient, baseRepo, opts.LimitResults, opts.ExcludeDrafts, opts.ExcludePreReleases, opts.Order, releaseFeatures)
if err != nil {
return err
}
if len(releases) == 0 && opts.Exporter == nil {
return cmdutil.NewNoResultsError("no releases found")
}
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, releases)
}
table := tableprinter.New(opts.IO, tableprinter.WithHeader("Title", "Type", "Tag name", "Published"))
cs := opts.IO.ColorScheme()
for _, rel := range releases {
title := text.RemoveExcessiveWhitespace(rel.Name)
if title == "" {
title = rel.TagName
}
table.AddField(title)
badge := ""
var badgeColor func(string) string
if rel.IsLatest {
badge = "Latest"
badgeColor = cs.Green
} else if rel.IsDraft {
badge = "Draft"
badgeColor = cs.Red
} else if rel.IsPrerelease {
badge = "Pre-release"
badgeColor = cs.Yellow
}
table.AddField(badge, tableprinter.WithColor(badgeColor))
table.AddField(rel.TagName, tableprinter.WithTruncate(nil))
pubDate := rel.PublishedAt
if rel.PublishedAt.IsZero() {
pubDate = rel.CreatedAt
}
table.AddTimeField(time.Now(), pubDate, cs.Muted)
table.EndRow()
}
err = table.Render()
if err != nil {
return err
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/list/http.go | pkg/cmd/release/list/http.go | package list
import (
"net/http"
"strings"
"time"
"github.com/cli/cli/v2/api"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/shurcooL/githubv4"
)
var releaseFields = []string{
"name",
"tagName",
"isDraft",
"isLatest",
"isPrerelease",
"isImmutable",
"createdAt",
"publishedAt",
}
type Release struct {
Name string
TagName string
IsDraft bool
IsImmutable bool `graphql:"immutable"`
IsLatest bool
IsPrerelease bool
CreatedAt time.Time
PublishedAt time.Time
}
func (r *Release) ExportData(fields []string) map[string]interface{} {
return cmdutil.StructExportData(r, fields)
}
func fetchReleases(httpClient *http.Client, repo ghrepo.Interface, limit int, excludeDrafts bool, excludePreReleases bool, order string, releaseFeatures fd.ReleaseFeatures) ([]Release, error) {
// TODO: immutableReleaseFullSupport
// This is a temporary workaround until all supported GHES versions fully
// support immutable releases, which would probably be when GHES 3.18 goes
// EOL. At that point we can remove this if statement.
//
// Note 1: This could have been done differently by using two separate query
// types or even using plain text/string queries. But, both would require us
// to refactor them back in the future, to the single, strongly-typed query
// approach as it was before. So, duplicating the entire function for now
// seems like the lesser evil, with a quicker and less risky clean up in the
// near future.
//
// Note 2: We couldn't use GraphQL directives like `@include(condition)` or
// `@skip(condition)` here because if the field doesn't exist on the schema
// then the whole query would still fail regardless of the condition being
// met or not.
if !releaseFeatures.ImmutableReleases {
return fetchReleasesWithoutImmutableReleases(httpClient, repo, limit, excludeDrafts, excludePreReleases, order)
}
type responseData struct {
Repository struct {
Releases struct {
Nodes []Release
PageInfo struct {
HasNextPage bool
EndCursor string
}
} `graphql:"releases(first: $perPage, orderBy: {field: CREATED_AT, direction: $direction}, after: $endCursor)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
perPage := limit
if limit > 100 {
perPage = 100
}
variables := map[string]interface{}{
"owner": githubv4.String(repo.RepoOwner()),
"name": githubv4.String(repo.RepoName()),
"perPage": githubv4.Int(perPage),
"endCursor": (*githubv4.String)(nil),
"direction": githubv4.OrderDirection(strings.ToUpper(order)),
}
gql := api.NewClientFromHTTP(httpClient)
var releases []Release
loop:
for {
var query responseData
err := gql.Query(repo.RepoHost(), "RepositoryReleaseList", &query, variables)
if err != nil {
return nil, err
}
for _, r := range query.Repository.Releases.Nodes {
if excludeDrafts && r.IsDraft {
continue
}
if excludePreReleases && r.IsPrerelease {
continue
}
releases = append(releases, r)
if len(releases) == limit {
break loop
}
}
if !query.Repository.Releases.PageInfo.HasNextPage {
break
}
variables["endCursor"] = githubv4.String(query.Repository.Releases.PageInfo.EndCursor)
}
return releases, nil
}
// TODO: immutableReleaseFullSupport
// This is a temporary workaround until all supported GHES versions fully
// support immutable releases, which would be when GHES 3.18 goes EOL. At that
// point we can remove this function.
func fetchReleasesWithoutImmutableReleases(httpClient *http.Client, repo ghrepo.Interface, limit int, excludeDrafts bool, excludePreReleases bool, order string) ([]Release, error) {
type releaseOld struct {
Name string
TagName string
IsDraft bool
IsLatest bool
IsPrerelease bool
CreatedAt time.Time
PublishedAt time.Time
}
fromReleaseOld := func(old releaseOld) Release {
return Release{
Name: old.Name,
TagName: old.TagName,
IsDraft: old.IsDraft,
IsLatest: old.IsLatest,
IsPrerelease: old.IsPrerelease,
CreatedAt: old.CreatedAt,
PublishedAt: old.PublishedAt,
}
}
type responseData struct {
Repository struct {
Releases struct {
Nodes []releaseOld
PageInfo struct {
HasNextPage bool
EndCursor string
}
} `graphql:"releases(first: $perPage, orderBy: {field: CREATED_AT, direction: $direction}, after: $endCursor)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
perPage := limit
if limit > 100 {
perPage = 100
}
variables := map[string]interface{}{
"owner": githubv4.String(repo.RepoOwner()),
"name": githubv4.String(repo.RepoName()),
"perPage": githubv4.Int(perPage),
"endCursor": (*githubv4.String)(nil),
"direction": githubv4.OrderDirection(strings.ToUpper(order)),
}
gql := api.NewClientFromHTTP(httpClient)
var releases []Release
loop:
for {
var query responseData
err := gql.Query(repo.RepoHost(), "RepositoryReleaseList", &query, variables)
if err != nil {
return nil, err
}
for _, r := range query.Repository.Releases.Nodes {
if excludeDrafts && r.IsDraft {
continue
}
if excludePreReleases && r.IsPrerelease {
continue
}
releases = append(releases, fromReleaseOld(r))
if len(releases) == limit {
break loop
}
}
if !query.Repository.Releases.PageInfo.HasNextPage {
break
}
variables["endCursor"] = githubv4.String(query.Repository.Releases.PageInfo.EndCursor)
}
return releases, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/edit/edit.go | pkg/cmd/release/edit/edit.go | package edit
import (
"context"
"fmt"
"net/http"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type EditOptions struct {
IO *iostreams.IOStreams
HttpClient func() (*http.Client, error)
BaseRepo func() (ghrepo.Interface, error)
TagName string
Target string
Name *string
Body *string
DiscussionCategory *string
Draft *bool
Prerelease *bool
IsLatest *bool
VerifyTag bool
}
func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Command {
opts := &EditOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
var notesFile string
cmd := &cobra.Command{
DisableFlagsInUseLine: true,
Use: "edit <tag>",
Short: "Edit a release",
Example: heredoc.Doc(`
# Publish a release that was previously a draft
$ gh release edit v1.0 --draft=false
# Update the release notes from the content of a file
$ gh release edit v1.0 --notes-file /path/to/release_notes.md
`),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.BaseRepo = f.BaseRepo
if cmd.Flags().NFlag() == 0 {
return cmdutil.FlagErrorf("use flags to specify properties to edit")
}
if notesFile != "" {
b, err := cmdutil.ReadFile(notesFile, opts.IO.In)
if err != nil {
return err
}
body := string(b)
opts.Body = &body
}
if runF != nil {
return runF(opts)
}
return editRun(args[0], opts)
},
}
cmdutil.NilBoolFlag(cmd, &opts.Draft, "draft", "", "Save the release as a draft instead of publishing it")
cmdutil.NilBoolFlag(cmd, &opts.Prerelease, "prerelease", "", "Mark the release as a prerelease")
cmdutil.NilBoolFlag(cmd, &opts.IsLatest, "latest", "", "Explicitly mark the release as \"Latest\"")
cmdutil.NilStringFlag(cmd, &opts.Body, "notes", "n", "Release notes")
cmdutil.NilStringFlag(cmd, &opts.Name, "title", "t", "Release title")
cmdutil.NilStringFlag(cmd, &opts.DiscussionCategory, "discussion-category", "", "Start a discussion in the specified category when publishing a draft")
cmd.Flags().StringVar(&opts.Target, "target", "", "Target `branch` or full commit SHA (default [main branch])")
cmd.Flags().StringVar(&opts.TagName, "tag", "", "The name of the tag")
cmd.Flags().StringVarP(¬esFile, "notes-file", "F", "", "Read release notes from `file` (use \"-\" to read from standard input)")
cmd.Flags().BoolVar(&opts.VerifyTag, "verify-tag", false, "Abort in case the git tag doesn't already exist in the remote repository")
_ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "target")
return cmd
}
func editRun(tag string, opts *EditOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
release, err := shared.FetchRelease(context.Background(), httpClient, baseRepo, tag)
if err != nil {
return err
}
params := getParams(opts)
// If we don't provide any tag name, the API will remove the current tag from the release
if _, ok := params["tag_name"]; !ok {
params["tag_name"] = release.TagName
}
if opts.VerifyTag && opts.TagName != "" {
remoteTagPresent, err := remoteTagExists(httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
if !remoteTagPresent {
return fmt.Errorf("tag %s doesn't exist in the repo %s, aborting due to --verify-tag flag",
opts.TagName, ghrepo.FullName(baseRepo))
}
}
editedRelease, err := editRelease(httpClient, baseRepo, release.DatabaseID, params)
if err != nil {
return err
}
fmt.Fprintf(opts.IO.Out, "%s\n", editedRelease.URL)
return nil
}
func getParams(opts *EditOptions) map[string]interface{} {
params := map[string]interface{}{}
if opts.Body != nil {
params["body"] = opts.Body
}
if opts.DiscussionCategory != nil {
params["discussion_category_name"] = *opts.DiscussionCategory
}
if opts.Draft != nil {
params["draft"] = *opts.Draft
}
if opts.Name != nil {
params["name"] = opts.Name
}
if opts.Prerelease != nil {
params["prerelease"] = *opts.Prerelease
}
if opts.TagName != "" {
params["tag_name"] = opts.TagName
}
if opts.Target != "" {
params["target_commitish"] = opts.Target
}
if opts.IsLatest != nil {
// valid values: true/false/legacy
params["make_latest"] = fmt.Sprintf("%v", *opts.IsLatest)
}
return params
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/edit/edit_test.go | pkg/cmd/release/edit/edit_test.go | package edit
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdEdit(t *testing.T) {
tempDir := t.TempDir()
tf, err := os.CreateTemp(tempDir, "release-create")
require.NoError(t, err)
fmt.Fprint(tf, "MY NOTES")
tf.Close()
tests := []struct {
name string
args string
isTTY bool
stdin string
want EditOptions
wantErr string
}{
{
name: "no arguments notty",
args: "",
isTTY: false,
wantErr: "accepts 1 arg(s), received 0",
},
{
name: "provide title and notes",
args: "v1.2.3 --title 'Some Title' --notes 'Some Notes'",
isTTY: false,
want: EditOptions{
TagName: "",
Name: stringPtr("Some Title"),
Body: stringPtr("Some Notes"),
},
},
{
name: "provide discussion category",
args: "v1.2.3 --discussion-category some-category",
isTTY: false,
want: EditOptions{
TagName: "",
DiscussionCategory: stringPtr("some-category"),
},
},
{
name: "provide tag and target commitish",
args: "v1.2.3 --tag v9.8.7 --target 97ea5e77b4d61d5d80ed08f7512847dee3ec9af5",
isTTY: false,
want: EditOptions{
TagName: "v9.8.7",
Target: "97ea5e77b4d61d5d80ed08f7512847dee3ec9af5",
},
},
{
name: "provide prerelease",
args: "v1.2.3 --prerelease",
isTTY: false,
want: EditOptions{
TagName: "",
Prerelease: boolPtr(true),
},
},
{
name: "provide prerelease=false",
args: "v1.2.3 --prerelease=false",
isTTY: false,
want: EditOptions{
TagName: "",
Prerelease: boolPtr(false),
},
},
{
name: "provide draft",
args: "v1.2.3 --draft",
isTTY: false,
want: EditOptions{
TagName: "",
Draft: boolPtr(true),
},
},
{
name: "provide draft=false",
args: "v1.2.3 --draft=false",
isTTY: false,
want: EditOptions{
TagName: "",
Draft: boolPtr(false),
},
},
{
name: "latest",
args: "v1.2.3 --latest",
isTTY: false,
want: EditOptions{
TagName: "",
IsLatest: boolPtr(true),
},
},
{
name: "not latest",
args: "v1.2.3 --latest=false",
isTTY: false,
want: EditOptions{
TagName: "",
IsLatest: boolPtr(false),
},
},
{
name: "provide notes from file",
args: fmt.Sprintf(`v1.2.3 -F '%s'`, tf.Name()),
isTTY: false,
want: EditOptions{
TagName: "",
Body: stringPtr("MY NOTES"),
},
},
{
name: "provide notes from stdin",
args: "v1.2.3 -F -",
isTTY: false,
stdin: "MY NOTES",
want: EditOptions{
TagName: "",
Body: stringPtr("MY NOTES"),
},
},
{
name: "verify-tag",
args: "v1.2.0 --tag=v1.1.0 --verify-tag",
isTTY: false,
want: EditOptions{
TagName: "v1.1.0",
VerifyTag: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
if tt.stdin == "" {
ios.SetStdinTTY(tt.isTTY)
} else {
ios.SetStdinTTY(false)
fmt.Fprint(stdin, tt.stdin)
}
ios.SetStdoutTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *EditOptions
cmd := NewCmdEdit(f, func(o *EditOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.TagName, opts.TagName)
assert.Equal(t, tt.want.Target, opts.Target)
assert.Equal(t, tt.want.Name, opts.Name)
assert.Equal(t, tt.want.Body, opts.Body)
assert.Equal(t, tt.want.DiscussionCategory, opts.DiscussionCategory)
assert.Equal(t, tt.want.Draft, opts.Draft)
assert.Equal(t, tt.want.Prerelease, opts.Prerelease)
assert.Equal(t, tt.want.IsLatest, opts.IsLatest)
assert.Equal(t, tt.want.VerifyTag, opts.VerifyTag)
})
}
}
func Test_editRun(t *testing.T) {
tests := []struct {
name string
isTTY bool
opts EditOptions
httpStubs func(t *testing.T, reg *httpmock.Registry)
wantErr string
wantStdout string
wantStderr string
}{
{
name: "edit the tag name",
isTTY: true,
opts: EditOptions{
TagName: "v1.2.4",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.4",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit the target",
isTTY: true,
opts: EditOptions{
Target: "c0ff33",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"target_commitish": "c0ff33",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit the release name",
isTTY: true,
opts: EditOptions{
Name: stringPtr("Hot Release #1"),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"name": "Hot Release #1",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit the discussion category",
isTTY: true,
opts: EditOptions{
DiscussionCategory: stringPtr("some-category"),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"discussion_category_name": "some-category",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit the latest marker",
isTTY: false,
opts: EditOptions{
IsLatest: boolPtr(true),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"make_latest": "true",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit the release name (empty)",
isTTY: true,
opts: EditOptions{
Name: stringPtr(""),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"name": "",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit the release notes",
isTTY: true,
opts: EditOptions{
Body: stringPtr("Release Notes:\n- Fix Bug #1\n- Fix Bug #2"),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"body": "Release Notes:\n- Fix Bug #1\n- Fix Bug #2",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit the release notes (empty)",
isTTY: true,
opts: EditOptions{
Body: stringPtr(""),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"body": "",
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit draft (true)",
isTTY: true,
opts: EditOptions{
Draft: boolPtr(true),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": true,
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit draft (false)",
isTTY: true,
opts: EditOptions{
Draft: boolPtr(false),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": false,
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit prerelease (true)",
isTTY: true,
opts: EditOptions{
Prerelease: boolPtr(true),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"prerelease": true,
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "edit prerelease (false)",
isTTY: true,
opts: EditOptions{
Prerelease: boolPtr(false),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockSuccessfulEditResponse(reg, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"prerelease": false,
}, params)
})
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: "",
},
{
name: "error when remote tag does not exist and verify-tag flag is set",
isTTY: true,
opts: EditOptions{
TagName: "v1.2.4",
VerifyTag: true,
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.GraphQL("RepositoryFindRef"),
httpmock.StringResponse(`{"data":{"repository":{"ref": {"id": ""}}}}`))
},
wantErr: "tag v1.2.4 doesn't exist in the repo OWNER/REPO, aborting due to --verify-tag flag",
wantStdout: "",
wantStderr: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
shared.StubFetchRelease(t, fakeHTTP, "OWNER", "REPO", "v1.2.3", `{
"id": 12345,
"tag_name": "v1.2.3"
}`)
if tt.httpStubs != nil {
tt.httpStubs(t, fakeHTTP)
}
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: fakeHTTP}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
err := editRun("v1.2.3", &tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
func mockSuccessfulEditResponse(reg *httpmock.Registry, cb func(params map[string]interface{})) {
matcher := httpmock.REST("PATCH", "repos/OWNER/REPO/releases/12345")
responder := httpmock.RESTPayload(201, `{
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, cb)
reg.Register(matcher, responder)
}
func boolPtr(b bool) *bool {
return &b
}
func stringPtr(s string) *string {
return &s
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/edit/http.go | pkg/cmd/release/edit/http.go | package edit
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/shurcooL/githubv4"
)
func editRelease(httpClient *http.Client, repo ghrepo.Interface, releaseID int64, params map[string]interface{}) (*shared.Release, error) {
bodyBytes, err := json.Marshal(params)
if err != nil {
return nil, err
}
path := fmt.Sprintf("repos/%s/%s/releases/%d", repo.RepoOwner(), repo.RepoName(), releaseID)
url := ghinstance.RESTPrefix(repo.RepoHost()) + path
req, err := http.NewRequest("PATCH", url, bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var newRelease shared.Release
err = json.Unmarshal(b, &newRelease)
return &newRelease, err
}
func remoteTagExists(httpClient *http.Client, repo ghrepo.Interface, tagName string) (bool, error) {
gql := api.NewClientFromHTTP(httpClient)
qualifiedTagName := fmt.Sprintf("refs/tags/%s", tagName)
var query struct {
Repository struct {
Ref struct {
ID string
} `graphql:"ref(qualifiedName: $tagName)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]interface{}{
"owner": githubv4.String(repo.RepoOwner()),
"name": githubv4.String(repo.RepoName()),
"tagName": githubv4.String(qualifiedTagName),
}
err := gql.Query(repo.RepoHost(), "RepositoryFindRef", &query, variables)
return query.Repository.Ref.ID != "", err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/upload/upload_test.go | pkg/cmd/release/upload/upload_test.go | package upload
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_SanitizeFileName(t *testing.T) {
tests := []struct {
name string
expected string
}{
{
name: "foo",
expected: "foo",
},
{
name: "foo bar",
expected: "foo.bar",
},
{
name: ".foo",
expected: "default.foo",
},
{
name: "Foo bar",
expected: "Foo.bar",
},
{
name: "Hello, दुनिया",
expected: "default.Hello",
},
{
name: "this+has+plusses.jpg",
expected: "this+has+plusses.jpg",
},
{
name: "this@has@at@signs.jpg",
expected: "this@has@at@signs.jpg",
},
{
name: "façade.exposé",
expected: "facade.expose",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expected, sanitizeFileName(tt.name))
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/upload/upload.go | pkg/cmd/release/upload/upload.go | package upload
import (
"context"
"fmt"
"net/http"
"regexp"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type UploadOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
TagName string
Assets []*shared.AssetForUpload
// maximum number of simultaneous uploads
Concurrency int
OverwriteExisting bool
}
func NewCmdUpload(f *cmdutil.Factory, runF func(*UploadOptions) error) *cobra.Command {
opts := &UploadOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "upload <tag> <files>...",
Short: "Upload assets to a release",
Long: heredoc.Docf(`
Upload asset files to a GitHub Release.
To define a display label for an asset, append text starting with %[1]s#%[1]s after the
file name.
`, "`"),
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
opts.TagName = args[0]
var err error
opts.Assets, err = shared.AssetsFromArgs(args[1:])
if err != nil {
return err
}
opts.Concurrency = 5
if runF != nil {
return runF(opts)
}
return uploadRun(opts)
},
}
cmd.Flags().BoolVar(&opts.OverwriteExisting, "clobber", false, "Overwrite existing assets of the same name")
return cmd
}
func uploadRun(opts *UploadOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
release, err := shared.FetchRelease(context.Background(), httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
uploadURL := release.UploadURL
if idx := strings.IndexRune(uploadURL, '{'); idx > 0 {
uploadURL = uploadURL[:idx]
}
var existingNames []string
for _, a := range opts.Assets {
sanitizedFileName := sanitizeFileName(a.Name)
for _, ea := range release.Assets {
if ea.Name == sanitizedFileName {
a.ExistingURL = ea.APIURL
existingNames = append(existingNames, ea.Name)
break
}
}
}
if len(existingNames) > 0 && !opts.OverwriteExisting {
return fmt.Errorf("asset under the same name already exists: %v", existingNames)
}
opts.IO.StartProgressIndicator()
err = shared.ConcurrentUpload(httpClient, uploadURL, opts.Concurrency, opts.Assets)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
if opts.IO.IsStdoutTTY() {
iofmt := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.Out, "Successfully uploaded %s to %s\n",
text.Pluralize(len(opts.Assets), "asset"),
iofmt.Bold(release.TagName))
}
return nil
}
// this method attempts to mimic the same functionality on the client that the platform does on
// uploaded assets in order to allow the --clobber logic work correctly, since that feature is
// one that only exists in the client
func sanitizeFileName(name string) string {
value := text.RemoveDiacritics(name)
// Stripped all non-ascii characters, provide default name.
if strings.HasPrefix(value, ".") {
value = "default" + value
}
// Replace special characters with the separator
value = regexp.MustCompile(`(?i)[^a-z0-9\-_\+@]+`).ReplaceAllLiteralString(value, ".")
// No more than one of the separator in a row.
value = regexp.MustCompile(`\.{2,}`).ReplaceAllLiteralString(value, ".")
// Remove leading/trailing separator.
value = strings.Trim(value, ".")
// Just file extension left, add default name.
if name != value && !strings.Contains(value, ".") {
value = "default." + value
}
return value
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/verify-asset/verify_asset.go | pkg/cmd/release/verify-asset/verify_asset.go | package verifyasset
import (
"context"
"fmt"
"net/http"
"path/filepath"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/attestation/api"
"github.com/cli/cli/v2/pkg/cmd/attestation/artifact"
att_io "github.com/cli/cli/v2/pkg/cmd/attestation/io"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
type VerifyAssetOptions struct {
TagName string
BaseRepo ghrepo.Interface
Exporter cmdutil.Exporter
AssetFilePath string
TrustedRoot string
}
type VerifyAssetConfig struct {
HttpClient *http.Client
IO *iostreams.IOStreams
Opts *VerifyAssetOptions
AttClient api.Client
AttVerifier shared.Verifier
}
func NewCmdVerifyAsset(f *cmdutil.Factory, runF func(*VerifyAssetConfig) error) *cobra.Command {
opts := &VerifyAssetOptions{}
cmd := &cobra.Command{
Use: "verify-asset [<tag>] <file-path>",
Short: "Verify that a given asset originated from a release",
Long: heredoc.Doc(`
Verify that a given asset file originated from a specific GitHub Release using cryptographically signed attestations.
An attestation is a claim made by GitHub regarding a release and its assets.
This command checks that the asset you provide matches a valid attestation for the specified release (or the latest release, if no tag is given).
It ensures the asset's integrity by validating that the asset's digest matches the subject in the attestation and that the attestation is associated with the release.
`),
Args: cobra.MaximumNArgs(2),
Example: heredoc.Doc(`
# Verify an asset from the latest release
$ gh release verify-asset ./dist/my-asset.zip
# Verify an asset from a specific release tag
$ gh release verify-asset v1.2.3 ./dist/my-asset.zip
# Verify an asset from a specific release tag and output the attestation in JSON format
$ gh release verify-asset v1.2.3 ./dist/my-asset.zip --format json
`),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 2 {
opts.TagName = args[0]
opts.AssetFilePath = args[1]
} else if len(args) == 1 {
opts.AssetFilePath = args[0]
} else {
return cmdutil.FlagErrorf("you must specify an asset filepath")
}
opts.AssetFilePath = filepath.Clean(opts.AssetFilePath)
baseRepo, err := f.BaseRepo()
if err != nil {
return fmt.Errorf("failed to determine base repository: %w", err)
}
opts.BaseRepo = baseRepo
httpClient, err := f.HttpClient()
if err != nil {
return err
}
io := f.IOStreams
attClient := api.NewLiveClient(httpClient, baseRepo.RepoHost(), att_io.NewHandler(io))
attVerifier := &shared.AttestationVerifier{
AttClient: attClient,
HttpClient: httpClient,
IO: io,
TrustedRoot: opts.TrustedRoot,
}
config := &VerifyAssetConfig{
Opts: opts,
HttpClient: httpClient,
AttClient: attClient,
AttVerifier: attVerifier,
IO: io,
}
if runF != nil {
return runF(config)
}
return verifyAssetRun(config)
},
}
cmdutil.AddFormatFlags(cmd, &opts.Exporter)
cmd.Flags().StringVarP(&opts.TrustedRoot, "custom-trusted-root", "", "", "Path to a trusted_root.jsonl file; likely for offline verification.")
cmd.Flags().MarkHidden("custom-trusted-root")
return cmd
}
func verifyAssetRun(config *VerifyAssetConfig) error {
ctx := context.Background()
opts := config.Opts
baseRepo := opts.BaseRepo
tagName := opts.TagName
if tagName == "" {
release, err := shared.FetchLatestRelease(ctx, config.HttpClient, baseRepo)
if err != nil {
return err
}
tagName = release.TagName
}
fileName := getFileName(opts.AssetFilePath)
// Calculate the digest of the file
fileDigest, err := artifact.NewDigestedArtifact(nil, opts.AssetFilePath, "sha256")
if err != nil {
return err
}
ref, err := shared.FetchRefSHA(ctx, config.HttpClient, baseRepo, tagName)
if err != nil {
return err
}
releaseRefDigest := artifact.NewDigestedArtifactForRelease(ref, "sha1")
// Find attestations for the release tag SHA
attestations, err := config.AttClient.GetByDigest(api.FetchParams{
Digest: releaseRefDigest.DigestWithAlg(),
PredicateType: "release",
Owner: baseRepo.RepoOwner(),
Repo: baseRepo.RepoOwner() + "/" + baseRepo.RepoName(),
// TODO: Allow this value to be set via a flag.
// The limit is set to 100 to ensure we fetch all attestations for a given SHA.
// While multiple attestations can exist for a single SHA,
// only one attestation is associated with each release tag.
Initiator: "github",
Limit: 100,
})
if err != nil {
return fmt.Errorf("no attestations found for tag %s (%s)", tagName, releaseRefDigest.DigestWithAlg())
}
// Filter attestations by tag name
filteredAttestations, err := shared.FilterAttestationsByTag(attestations, tagName)
if err != nil {
return fmt.Errorf("error parsing attestations for tag %s: %w", tagName, err)
}
if len(filteredAttestations) == 0 {
return fmt.Errorf("no attestations found for release %s in %s/%s", tagName, baseRepo.RepoOwner(), baseRepo.RepoName())
}
// Filter attestations by subject digest
filteredAttestations, err = shared.FilterAttestationsByFileDigest(filteredAttestations, fileDigest.Digest())
if err != nil {
return fmt.Errorf("error parsing attestations for digest %s: %w", fileDigest.DigestWithAlg(), err)
}
if len(filteredAttestations) == 0 {
return fmt.Errorf("attestation for %s does not contain subject %s", tagName, fileDigest.DigestWithAlg())
}
// Verify attestation
verified, err := config.AttVerifier.VerifyAttestation(releaseRefDigest, filteredAttestations[0])
if err != nil {
return fmt.Errorf("failed to verify attestation for tag %s: %w", tagName, err)
}
// If an exporter is provided with the --json flag, write the results to the terminal in JSON format
if opts.Exporter != nil {
return opts.Exporter.Write(config.IO, verified)
}
io := config.IO
cs := io.ColorScheme()
fmt.Fprintf(io.Out, "Calculated digest for %s: %s\n", fileName, fileDigest.DigestWithAlg())
fmt.Fprintf(io.Out, "Resolved tag %s to %s\n", tagName, releaseRefDigest.DigestWithAlg())
fmt.Fprint(io.Out, "Loaded attestation from GitHub API\n\n")
fmt.Fprintf(io.Out, cs.Green("%s Verification succeeded! %s is present in release %s\n"), cs.SuccessIcon(), fileName, tagName)
return nil
}
func getFileName(filePath string) string {
// Get the file name from the file path
_, fileName := filepath.Split(filePath)
return fileName
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/verify-asset/verify_asset_test.go | pkg/cmd/release/verify-asset/verify_asset_test.go | package verifyasset
import (
"bytes"
"net/http"
"testing"
"github.com/cli/cli/v2/pkg/cmd/attestation/api"
"github.com/cli/cli/v2/pkg/cmd/attestation/test"
"github.com/cli/cli/v2/pkg/cmd/attestation/test/data"
"github.com/cli/cli/v2/pkg/cmd/attestation/verification"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/cli/cli/v2/internal/ghrepo"
)
func TestNewCmdVerifyAsset_Args(t *testing.T) {
tests := []struct {
name string
args []string
wantTag string
wantFile string
wantErr string
}{
{
name: "valid args",
args: []string{"v1.2.3", "../../attestation/test/data/github_release_artifact.zip"},
wantTag: "v1.2.3",
wantFile: test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact.zip"),
},
{
name: "valid flag with no tag",
args: []string{"../../attestation/test/data/github_release_artifact.zip"},
wantFile: test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact.zip"),
},
{
name: "no args",
args: []string{},
wantErr: "you must specify an asset filepath",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
testIO, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: testIO,
HttpClient: func() (*http.Client, error) {
return nil, nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
}
var cfg *VerifyAssetConfig
cmd := NewCmdVerifyAsset(f, func(c *VerifyAssetConfig) error {
cfg = c
return nil
})
cmd.SetArgs(tt.args)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err := cmd.ExecuteC()
if tt.wantErr != "" {
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
} else {
require.NoError(t, err)
assert.Equal(t, tt.wantTag, cfg.Opts.TagName)
assert.Equal(t, tt.wantFile, cfg.Opts.AssetFilePath)
}
})
}
}
func Test_verifyAssetRun_Success(t *testing.T) {
ios, _, _, _ := iostreams.Test()
tagName := "v6"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
result := &verification.AttestationProcessingResult{
Attestation: &api.Attestation{
Bundle: data.GitHubReleaseBundle(t),
BundleURL: "https://example.com",
},
VerificationResult: nil,
}
releaseAssetPath := test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact.zip")
cfg := &VerifyAssetConfig{
Opts: &VerifyAssetOptions{
AssetFilePath: releaseAssetPath,
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewTestClient(),
AttVerifier: shared.NewMockVerifier(result),
}
err = verifyAssetRun(cfg)
require.NoError(t, err)
}
func Test_verifyAssetRun_SuccessNoTagArg(t *testing.T) {
ios, _, _, _ := iostreams.Test()
tagName := "v6"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "OWNER", "REPO", tagName, fakeSHA)
shared.StubFetchRelease(t, fakeHTTP, "OWNER", "REPO", "", `{
"tag_name": "v6",
"draft": false,
"url": "https://api.github.com/repos/OWNER/REPO/releases/23456"
}`)
baseRepo, err := ghrepo.FromFullName("OWNER/REPO")
require.NoError(t, err)
result := &verification.AttestationProcessingResult{
Attestation: &api.Attestation{
Bundle: data.GitHubReleaseBundle(t),
BundleURL: "https://example.com",
},
VerificationResult: nil,
}
releaseAssetPath := test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact.zip")
cfg := &VerifyAssetConfig{
Opts: &VerifyAssetOptions{
AssetFilePath: releaseAssetPath,
TagName: "", // No tag argument provided
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewTestClient(),
AttVerifier: shared.NewMockVerifier(result),
}
err = verifyAssetRun(cfg)
require.NoError(t, err)
}
func Test_verifyAssetRun_FailedNoAttestations(t *testing.T) {
ios, _, _, _ := iostreams.Test()
tagName := "v1"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
releaseAssetPath := test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact.zip")
cfg := &VerifyAssetConfig{
Opts: &VerifyAssetOptions{
AssetFilePath: releaseAssetPath,
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewFailTestClient(),
AttVerifier: nil,
}
err = verifyAssetRun(cfg)
require.ErrorContains(t, err, "no attestations found for tag v1")
}
func Test_verifyAssetRun_FailedTagNotInAttestation(t *testing.T) {
ios, _, _, _ := iostreams.Test()
// Tag name does not match the one present in the attestation which
// will be returned by the mock client. Simulates a scenario where
// multiple releases may point to the same commit SHA, but not all
// of them are attested.
tagName := "v1.2.3"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
releaseAssetPath := test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact.zip")
cfg := &VerifyAssetConfig{
Opts: &VerifyAssetOptions{
AssetFilePath: releaseAssetPath,
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewTestClient(),
AttVerifier: nil,
}
err = verifyAssetRun(cfg)
require.ErrorContains(t, err, "no attestations found for release v1.2.3")
}
func Test_verifyAssetRun_FailedInvalidAsset(t *testing.T) {
ios, _, _, _ := iostreams.Test()
tagName := "v6"
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
releaseAssetPath := test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact_invalid.zip")
cfg := &VerifyAssetConfig{
Opts: &VerifyAssetOptions{
AssetFilePath: releaseAssetPath,
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewTestClient(),
AttVerifier: nil,
}
err = verifyAssetRun(cfg)
require.ErrorContains(t, err, "attestation for v6 does not contain subject")
}
func Test_verifyAssetRun_NoSuchAsset(t *testing.T) {
ios, _, _, _ := iostreams.Test()
tagName := "v6"
fakeHTTP := &httpmock.Registry{}
fakeSHA := "1234567890abcdef1234567890abcdef12345678"
shared.StubFetchRefSHA(t, fakeHTTP, "owner", "repo", tagName, fakeSHA)
baseRepo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
cfg := &VerifyAssetConfig{
Opts: &VerifyAssetOptions{
AssetFilePath: "artifact.zip",
TagName: tagName,
BaseRepo: baseRepo,
Exporter: nil,
},
IO: ios,
HttpClient: &http.Client{Transport: fakeHTTP},
AttClient: api.NewTestClient(),
AttVerifier: nil,
}
err = verifyAssetRun(cfg)
require.ErrorContains(t, err, "failed to open local artifact")
}
func Test_getFileName(t *testing.T) {
tests := []struct {
input string
want string
}{
{"foo/bar/baz.txt", "baz.txt"},
{"baz.txt", "baz.txt"},
{"/tmp/foo.tar.gz", "foo.tar.gz"},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
got := getFileName(tt.input)
assert.Equal(t, tt.want, got)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/view/view.go | pkg/cmd/release/view/view.go | package view
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/markdown"
"github.com/spf13/cobra"
)
type browser interface {
Browse(string) error
}
type ViewOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Browser browser
Exporter cmdutil.Exporter
TagName string
WebMode bool
}
func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command {
opts := &ViewOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Browser: f.Browser,
}
cmd := &cobra.Command{
Use: "view [<tag>]",
Short: "View information about a release",
Long: heredoc.Doc(`
View information about a GitHub Release.
Without an explicit tag name argument, the latest release in the project
is shown.
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if len(args) > 0 {
opts.TagName = args[0]
}
if runF != nil {
return runF(opts)
}
return viewRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the release in the browser")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.ReleaseFields)
return cmd
}
func viewRun(opts *ViewOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
ctx := context.Background()
var release *shared.Release
if opts.TagName == "" {
release, err = shared.FetchLatestRelease(ctx, httpClient, baseRepo)
if err != nil {
return err
}
} else {
release, err = shared.FetchRelease(ctx, httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
}
if opts.WebMode {
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(release.URL))
}
return opts.Browser.Browse(release.URL)
}
opts.IO.DetectTerminalTheme()
if err := opts.IO.StartPager(); err != nil {
fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err)
}
defer opts.IO.StopPager()
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, release)
}
if opts.IO.IsStdoutTTY() {
if err := renderReleaseTTY(opts.IO, release); err != nil {
return err
}
} else {
if err := renderReleasePlain(opts.IO.Out, release); err != nil {
return err
}
}
return nil
}
func renderReleaseTTY(io *iostreams.IOStreams, release *shared.Release) error {
cs := io.ColorScheme()
w := io.Out
fmt.Fprintf(w, "%s\n", cs.Bold(release.TagName))
if release.IsDraft {
fmt.Fprintf(w, "%s • ", cs.Red("Draft"))
} else if release.IsPrerelease {
fmt.Fprintf(w, "%s • ", cs.Yellow("Pre-release"))
}
if release.IsDraft {
fmt.Fprintln(w, cs.Mutedf("%s created this %s", release.Author.Login, text.FuzzyAgo(time.Now(), release.CreatedAt)))
} else {
fmt.Fprintln(w, cs.Mutedf("%s released this %s", release.Author.Login, text.FuzzyAgo(time.Now(), *release.PublishedAt)))
}
renderedDescription, err := markdown.Render(release.Body,
markdown.WithTheme(io.TerminalTheme()),
markdown.WithWrap(io.TerminalWidth()))
if err != nil {
return err
}
fmt.Fprintln(w, renderedDescription)
if len(release.Assets) > 0 {
fmt.Fprintln(w, cs.Bold("Assets"))
table := tableprinter.New(io, tableprinter.WithHeader("Name", "Digest", "Size"))
for _, a := range release.Assets {
table.AddField(a.Name)
if a.Digest == nil {
table.AddField("")
} else {
table.AddField(*a.Digest)
}
table.AddField(humanFileSize(a.Size))
table.EndRow()
}
err := table.Render()
if err != nil {
return err
}
fmt.Fprint(w, "\n")
}
fmt.Fprintln(w, cs.Mutedf("View on GitHub: %s", release.URL))
return nil
}
func renderReleasePlain(w io.Writer, release *shared.Release) error {
fmt.Fprintf(w, "title:\t%s\n", release.Name)
fmt.Fprintf(w, "tag:\t%s\n", release.TagName)
fmt.Fprintf(w, "draft:\t%v\n", release.IsDraft)
fmt.Fprintf(w, "prerelease:\t%v\n", release.IsPrerelease)
fmt.Fprintf(w, "immutable:\t%v\n", release.IsImmutable)
fmt.Fprintf(w, "author:\t%s\n", release.Author.Login)
fmt.Fprintf(w, "created:\t%s\n", release.CreatedAt.Format(time.RFC3339))
if !release.IsDraft {
fmt.Fprintf(w, "published:\t%s\n", release.PublishedAt.Format(time.RFC3339))
}
fmt.Fprintf(w, "url:\t%s\n", release.URL)
for _, a := range release.Assets {
fmt.Fprintf(w, "asset:\t%s\n", a.Name)
}
fmt.Fprint(w, "--\n")
fmt.Fprint(w, release.Body)
if !strings.HasSuffix(release.Body, "\n") {
fmt.Fprintf(w, "\n")
}
return nil
}
func humanFileSize(s int64) string {
if s < 1024 {
return fmt.Sprintf("%d B", s)
}
kb := float64(s) / 1024
if kb < 1024 {
return fmt.Sprintf("%s KiB", floatToString(kb, 2))
}
mb := kb / 1024
if mb < 1024 {
return fmt.Sprintf("%s MiB", floatToString(mb, 2))
}
gb := mb / 1024
return fmt.Sprintf("%s GiB", floatToString(gb, 2))
}
// render float to fixed precision using truncation instead of rounding
func floatToString(f float64, p uint8) string {
fs := fmt.Sprintf("%#f%0*s", f, p, "")
idx := strings.IndexRune(fs, '.')
return fs[:idx+int(p)+1]
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/view/view_test.go | pkg/cmd/release/view/view_test.go | package view
import (
"bytes"
"fmt"
"io"
"net/http"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/jsonfieldstest"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestJSONFields(t *testing.T) {
jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdView, []string{
"apiUrl",
"author",
"assets",
"body",
"createdAt",
"databaseId",
"id",
"isDraft",
"isPrerelease",
"isImmutable",
"name",
"publishedAt",
"tagName",
"tarballUrl",
"targetCommitish",
"uploadUrl",
"url",
"zipballUrl",
})
}
func Test_NewCmdView(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want ViewOptions
wantErr string
}{
{
name: "version argument",
args: "v1.2.3",
isTTY: true,
want: ViewOptions{
TagName: "v1.2.3",
WebMode: false,
},
},
{
name: "no arguments",
args: "",
isTTY: true,
want: ViewOptions{
TagName: "",
WebMode: false,
},
},
{
name: "web mode",
args: "-w",
isTTY: true,
want: ViewOptions{
TagName: "",
WebMode: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *ViewOptions
cmd := NewCmdView(f, func(o *ViewOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.TagName, opts.TagName)
assert.Equal(t, tt.want.WebMode, opts.WebMode)
})
}
}
func Test_viewRun(t *testing.T) {
oneHourAgo := time.Now().Add(time.Duration(-24) * time.Hour)
frozenTime, err := time.Parse(time.RFC3339, "2020-08-31T15:44:24+02:00")
require.NoError(t, err)
tests := []struct {
name string
isTTY bool
releaseBody string
releasedAt time.Time
opts ViewOptions
wantErr string
wantStdout string
wantStderr string
}{
{
name: "view specific release",
isTTY: true,
releaseBody: `* Fixed bugs\n`,
releasedAt: oneHourAgo,
opts: ViewOptions{
TagName: "v1.2.3",
},
wantStdout: heredoc.Doc(`
v1.2.3
MonaLisa released this about 1 day ago
• Fixed bugs
Assets
NAME DIGEST SIZE
windows.zip sha256:deadc0de 12 B
linux.tgz 34 B
View on GitHub: https://github.com/OWNER/REPO/releases/tags/v1.2.3
`),
wantStderr: ``,
},
{
name: "view latest release",
isTTY: true,
releaseBody: `* Fixed bugs\n`,
releasedAt: oneHourAgo,
opts: ViewOptions{
TagName: "",
},
wantStdout: heredoc.Doc(`
v1.2.3
MonaLisa released this about 1 day ago
• Fixed bugs
Assets
NAME DIGEST SIZE
windows.zip sha256:deadc0de 12 B
linux.tgz 34 B
View on GitHub: https://github.com/OWNER/REPO/releases/tags/v1.2.3
`),
wantStderr: ``,
},
{
name: "view machine-readable",
isTTY: false,
releaseBody: `* Fixed bugs\n`,
releasedAt: frozenTime,
opts: ViewOptions{
TagName: "v1.2.3",
},
wantStdout: heredoc.Doc(`
title:
tag: v1.2.3
draft: false
prerelease: false
immutable: true
author: MonaLisa
created: 2020-08-31T15:44:24+02:00
published: 2020-08-31T15:44:24+02:00
url: https://github.com/OWNER/REPO/releases/tags/v1.2.3
asset: windows.zip
asset: linux.tgz
--
* Fixed bugs
`),
wantStderr: ``,
},
{
name: "view machine-readable but body has no ending newline",
isTTY: false,
releaseBody: `* Fixed bugs`,
releasedAt: frozenTime,
opts: ViewOptions{
TagName: "v1.2.3",
},
wantStdout: heredoc.Doc(`
title:
tag: v1.2.3
draft: false
prerelease: false
immutable: true
author: MonaLisa
created: 2020-08-31T15:44:24+02:00
published: 2020-08-31T15:44:24+02:00
url: https://github.com/OWNER/REPO/releases/tags/v1.2.3
asset: windows.zip
asset: linux.tgz
--
* Fixed bugs
`),
wantStderr: ``,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
shared.StubFetchRelease(t, fakeHTTP, "OWNER", "REPO", tt.opts.TagName, fmt.Sprintf(`{
"tag_name": "v1.2.3",
"draft": false,
"immutable": true,
"author": { "login": "MonaLisa" },
"body": "%[2]s",
"created_at": "%[1]s",
"published_at": "%[1]s",
"html_url": "https://github.com/OWNER/REPO/releases/tags/v1.2.3",
"assets": [
{ "name": "windows.zip", "size": 12, "digest": "sha256:deadc0de" },
{ "name": "linux.tgz", "size": 34, "digest": null }
]
}`, tt.releasedAt.Format(time.RFC3339), tt.releaseBody))
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: fakeHTTP}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
err := viewRun(&tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
func Test_humanFileSize(t *testing.T) {
tests := []struct {
name string
size int64
want string
}{
{
name: "min bytes",
size: 1,
want: "1 B",
},
{
name: "max bytes",
size: 1023,
want: "1023 B",
},
{
name: "min kibibytes",
size: 1024,
want: "1.00 KiB",
},
{
name: "max kibibytes",
size: 1024*1024 - 1,
want: "1023.99 KiB",
},
{
name: "min mibibytes",
size: 1024 * 1024,
want: "1.00 MiB",
},
{
name: "fractional mibibytes",
size: 1024*1024*12 + 1024*350,
want: "12.34 MiB",
},
{
name: "max mibibytes",
size: 1024*1024*1024 - 1,
want: "1023.99 MiB",
},
{
name: "min gibibytes",
size: 1024 * 1024 * 1024,
want: "1.00 GiB",
},
{
name: "fractional gibibytes",
size: 1024 * 1024 * 1024 * 1.5,
want: "1.50 GiB",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := humanFileSize(tt.size); got != tt.want {
t.Errorf("humanFileSize() = %v, want %v", got, tt.want)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/create/create.go | pkg/cmd/release/create/create.go | package create
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/surveyext"
"github.com/spf13/cobra"
)
type iprompter interface {
Select(string, string, []string) (int, error)
Input(string, string) (string, error)
Confirm(string, bool) (bool, error)
}
type CreateOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
HttpClient func() (*http.Client, error)
GitClient *git.Client
BaseRepo func() (ghrepo.Interface, error)
Edit func(string, string, string, io.Reader, io.Writer, io.Writer) (string, error)
Prompter iprompter
TagName string
Target string
Name string
Body string
BodyProvided bool
Draft bool
Prerelease bool
IsLatest *bool
Assets []*shared.AssetForUpload
// for interactive flow
SubmitAction string
// for interactive flow
ReleaseNotesAction string
// the value from the --repo flag
RepoOverride string
// maximum number of simultaneous uploads
Concurrency int
DiscussionCategory string
GenerateNotes bool
NotesStartTag string
VerifyTag bool
NotesFromTag bool
FailOnNoCommits bool
}
func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command {
opts := &CreateOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Config: f.Config,
Prompter: f.Prompter,
Edit: surveyext.Edit,
}
var notesFile string
cmd := &cobra.Command{
DisableFlagsInUseLine: true,
Use: "create [<tag>] [<filename>... | <pattern>...]",
Short: "Create a new release",
Long: heredoc.Docf(`
Create a new GitHub Release for a repository.
A list of asset files may be given to upload to the new release. To define a
display label for an asset, append text starting with %[1]s#%[1]s after the file name.
If a matching git tag does not yet exist, one will automatically get created
from the latest state of the default branch.
Use %[1]s--target%[1]s to point to a different branch or commit for the automatic tag creation.
Use %[1]s--verify-tag%[1]s to abort the release if the tag doesn't already exist.
To fetch the new tag locally after the release, do %[1]sgit fetch --tags origin%[1]s.
To create a release from an annotated git tag, first create one locally with
git, push the tag to GitHub, then run this command.
Use %[1]s--notes-from-tag%[1]s to get the release notes from the annotated git tag.
If the tag is not annotated, the commit message will be used instead.
Use %[1]s--generate-notes%[1]s to automatically generate notes using GitHub Release Notes API.
When using automatically generated release notes, a release title will also be automatically
generated unless a title was explicitly passed. Additional release notes can be prepended to
automatically generated notes by using the %[1]s--notes%[1]s flag.
By default, the release is created even if there are no new commits since the last release.
This may result in the same or duplicate release which may not be desirable in some cases.
Use %[1]s--fail-on-no-commits%[1]s to fail if no new commits are available. This flag has no
effect if there are no existing releases or this is the very first release.
## Immutable Releases
When release immutability is enabled for a repository, the following protections are enforced:
- Git tags associated with a release cannot be modified or deleted.
- Release assets cannot be modified or deleted.
Immutability is enforced only after a release is published. Draft releases can be modified
or deleted, and the associated git tags can be modified or deleted as well.
When using the %[1]screate%[1]s command to attach assets to a release, separate API calls
are made to create the release as a draft, upload the assets, and then publish the release.
Immutability protections will be enforced ONLY after the release is published.
`, "`"),
Example: heredoc.Doc(`
# Interactively create a release
$ gh release create
# Interactively create a release from specific tag
$ gh release create v1.2.3
# Non-interactively create a release
$ gh release create v1.2.3 --notes "bugfix release"
# Use automatically generated via GitHub Release Notes API release notes
$ gh release create v1.2.3 --generate-notes
# Use release notes from a file
$ gh release create v1.2.3 -F release-notes.md
# Use tag annotation or associated commit message as notes
$ gh release create v1.2.3 --notes-from-tag
# Don't mark the release as latest
$ gh release create v1.2.3 --latest=false
# Upload all tarballs in a directory as release assets
$ gh release create v1.2.3 ./dist/*.tgz
# Upload a release asset with a display label
$ gh release create v1.2.3 '/path/to/asset.zip#My display label'
# Create a release and start a discussion
$ gh release create v1.2.3 --discussion-category "General"
# Create a release only if there are new commits available since the last release
$ gh release create v1.2.3 --fail-on-no-commits
`),
Aliases: []string{"new"},
RunE: func(cmd *cobra.Command, args []string) error {
if cmd.Flags().Changed("discussion-category") && opts.Draft {
return errors.New("discussions for draft releases not supported")
}
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
opts.RepoOverride, _ = cmd.Flags().GetString("repo")
var err error
if len(args) > 0 {
opts.TagName = args[0]
opts.Assets, err = shared.AssetsFromArgs(args[1:])
if err != nil {
return err
}
}
if opts.TagName == "" && !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("tag required when not running interactively")
}
if opts.NotesFromTag && (opts.GenerateNotes || opts.NotesStartTag != "") {
return cmdutil.FlagErrorf("using `--notes-from-tag` with `--generate-notes` or `--notes-start-tag` is not supported")
}
if opts.NotesFromTag && opts.RepoOverride != "" {
return cmdutil.FlagErrorf("using `--notes-from-tag` with `--repo` is not supported")
}
opts.Concurrency = 5
opts.BodyProvided = cmd.Flags().Changed("notes") || opts.GenerateNotes || opts.NotesFromTag
if notesFile != "" {
b, err := cmdutil.ReadFile(notesFile, opts.IO.In)
if err != nil {
return err
}
opts.Body = string(b)
opts.BodyProvided = true
}
if runF != nil {
return runF(opts)
}
return createRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.Draft, "draft", "d", false, "Save the release as a draft instead of publishing it")
cmd.Flags().BoolVarP(&opts.Prerelease, "prerelease", "p", false, "Mark the release as a prerelease")
cmd.Flags().StringVar(&opts.Target, "target", "", "Target `branch` or full commit SHA (default [main branch])")
cmd.Flags().StringVarP(&opts.Name, "title", "t", "", "Release title")
cmd.Flags().StringVarP(&opts.Body, "notes", "n", "", "Release notes")
cmd.Flags().StringVarP(¬esFile, "notes-file", "F", "", "Read release notes from `file` (use \"-\" to read from standard input)")
cmd.Flags().StringVarP(&opts.DiscussionCategory, "discussion-category", "", "", "Start a discussion in the specified category")
cmd.Flags().BoolVarP(&opts.GenerateNotes, "generate-notes", "", false, "Automatically generate title and notes for the release via GitHub Release Notes API")
cmd.Flags().StringVar(&opts.NotesStartTag, "notes-start-tag", "", "Tag to use as the starting point for generating release notes")
cmdutil.NilBoolFlag(cmd, &opts.IsLatest, "latest", "", "Mark this release as \"Latest\" (default [automatic based on date and version]). --latest=false to explicitly NOT set as latest")
cmd.Flags().BoolVarP(&opts.VerifyTag, "verify-tag", "", false, "Abort in case the git tag doesn't already exist in the remote repository")
cmd.Flags().BoolVarP(&opts.NotesFromTag, "notes-from-tag", "", false, "Fetch notes from the tag annotation or message of commit associated with tag")
cmd.Flags().BoolVar(&opts.FailOnNoCommits, "fail-on-no-commits", false, "Fail if there are no commits since the last release (no impact on the first release)")
_ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "target")
return cmd
}
func createRun(opts *CreateOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
if opts.FailOnNoCommits {
isNew, err := isNewRelease(httpClient, baseRepo)
if err != nil {
return fmt.Errorf("failed to check whether there were new commits since last release: %v", err)
}
if !isNew {
return fmt.Errorf("no new commits since the last release")
}
}
var existingTag bool
if opts.TagName == "" {
tags, err := getTags(httpClient, baseRepo, 5)
if err != nil {
return err
}
if len(tags) != 0 {
options := make([]string, len(tags))
for i, tag := range tags {
options[i] = tag.Name
}
createNewTagOption := "Create a new tag"
options = append(options, createNewTagOption)
selected, err := opts.Prompter.Select("Choose a tag", options[0], options)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
tag := options[selected]
if tag != createNewTagOption {
existingTag = true
opts.TagName = tag
}
}
if opts.TagName == "" {
opts.TagName, err = opts.Prompter.Input("Tag name", "")
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
opts.TagName = strings.TrimSpace(opts.TagName)
}
}
if opts.VerifyTag && !existingTag {
remoteTagPresent, err := remoteTagExists(httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
if !remoteTagPresent {
return fmt.Errorf("tag %s doesn't exist in the repo %s, aborting due to --verify-tag flag",
opts.TagName, ghrepo.FullName(baseRepo))
}
}
var tagDescription string
if opts.RepoOverride == "" {
tagDescription, _ = gitTagInfo(opts.GitClient, opts.TagName)
if opts.NotesFromTag && tagDescription == "" {
return fmt.Errorf("cannot generate release notes from tag %s as it does not exist locally",
opts.TagName)
}
// If there is a local tag with the same name as specified
// the user may not want to create a new tag on the remote
// as the local one might be annotated or signed.
// If the user specifies the target take that as explicit instruction
// to create the tag on the remote pointing to the target regardless
// of local tag status.
// If a remote tag with the same name as specified exists already
// then a new tag will not be created so ignore local tag status.
if tagDescription != "" && !existingTag && opts.Target == "" && !opts.VerifyTag {
remoteExists, err := remoteTagExists(httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
if !remoteExists {
return fmt.Errorf("tag %s exists locally but has not been pushed to %s, please push it before continuing or specify the `--target` flag to create a new tag",
opts.TagName, ghrepo.FullName(baseRepo))
}
}
}
if !opts.BodyProvided && opts.IO.CanPrompt() {
editorCommand, err := cmdutil.DetermineEditor(opts.Config)
if err != nil {
return err
}
var generatedNotes *releaseNotes
var generatedChangelog string
generatedNotes, err = generateReleaseNotes(httpClient, baseRepo, opts.TagName, opts.Target, opts.NotesStartTag)
if err != nil && !errors.Is(err, notImplementedError) {
return err
}
if opts.RepoOverride == "" {
headRef := opts.TagName
if tagDescription == "" {
if opts.Target != "" {
// TODO: use the remote-tracking version of the branch ref
headRef = opts.Target
} else {
headRef = "HEAD"
}
}
if generatedNotes == nil {
if opts.NotesStartTag != "" {
commits, _ := changelogForRange(opts.GitClient, fmt.Sprintf("%s..%s", opts.NotesStartTag, headRef))
generatedChangelog = generateChangelog(commits)
} else if prevTag, err := detectPreviousTag(opts.GitClient, headRef); err == nil {
commits, _ := changelogForRange(opts.GitClient, fmt.Sprintf("%s..%s", prevTag, headRef))
generatedChangelog = generateChangelog(commits)
}
}
}
editorOptions := []string{"Write my own"}
if generatedNotes != nil {
editorOptions = append(editorOptions, "Write using generated notes as template")
}
if generatedChangelog != "" {
editorOptions = append(editorOptions, "Write using commit log as template")
}
if tagDescription != "" {
editorOptions = append(editorOptions, "Write using git tag message as template")
}
editorOptions = append(editorOptions, "Leave blank")
defaultName := opts.Name
if defaultName == "" && generatedNotes != nil {
defaultName = generatedNotes.Name
}
opts.Name, err = opts.Prompter.Input("Title (optional)", defaultName)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
selected, err := opts.Prompter.Select("Release notes", "", editorOptions)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
opts.ReleaseNotesAction = editorOptions[selected]
var openEditor bool
var editorContents string
switch opts.ReleaseNotesAction {
case "Write my own":
openEditor = true
case "Write using generated notes as template":
openEditor = true
editorContents = generatedNotes.Body
case "Write using commit log as template":
openEditor = true
editorContents = generatedChangelog
case "Write using git tag message as template":
openEditor = true
editorContents = tagDescription
case "Leave blank":
openEditor = false
default:
return fmt.Errorf("invalid action: %v", opts.ReleaseNotesAction)
}
if openEditor {
text, err := opts.Edit(editorCommand, "*.md", editorContents,
opts.IO.In, opts.IO.Out, opts.IO.ErrOut)
if err != nil {
return err
}
opts.Body = text
}
saveAsDraft := "Save as draft"
publishRelease := "Publish release"
defaultSubmit := publishRelease
if opts.Draft {
defaultSubmit = saveAsDraft
}
opts.Prerelease, err = opts.Prompter.Confirm("Is this a prerelease?", opts.Prerelease)
if err != nil {
return err
}
options := []string{publishRelease, saveAsDraft, "Cancel"}
selected, err = opts.Prompter.Select("Submit?", defaultSubmit, options)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
opts.SubmitAction = options[selected]
switch opts.SubmitAction {
case "Publish release":
opts.Draft = false
case "Save as draft":
opts.Draft = true
case "Cancel":
return cmdutil.CancelError
default:
return fmt.Errorf("invalid action: %v", opts.SubmitAction)
}
}
params := map[string]interface{}{
"tag_name": opts.TagName,
"draft": opts.Draft,
"prerelease": opts.Prerelease,
}
if opts.Name != "" {
params["name"] = opts.Name
}
if opts.Body != "" {
params["body"] = opts.Body
}
if opts.Target != "" {
params["target_commitish"] = opts.Target
}
if opts.IsLatest != nil {
// valid values: true/false/legacy
params["make_latest"] = fmt.Sprintf("%v", *opts.IsLatest)
}
if opts.DiscussionCategory != "" {
params["discussion_category_name"] = opts.DiscussionCategory
}
if opts.GenerateNotes {
if opts.NotesStartTag != "" {
generatedNotes, err := generateReleaseNotes(httpClient, baseRepo, opts.TagName, opts.Target, opts.NotesStartTag)
if err != nil && !errors.Is(err, notImplementedError) {
return err
}
if generatedNotes != nil {
if opts.Body == "" {
params["body"] = generatedNotes.Body
} else {
params["body"] = fmt.Sprintf("%s\n%s", opts.Body, generatedNotes.Body)
}
if opts.Name == "" {
params["name"] = generatedNotes.Name
}
}
} else {
params["generate_release_notes"] = true
}
}
if opts.NotesFromTag {
if opts.Body == "" {
params["body"] = tagDescription
} else {
params["body"] = fmt.Sprintf("%s\n%s", opts.Body, tagDescription)
}
}
hasAssets := len(opts.Assets) > 0
draftWhileUploading := false
if hasAssets && !opts.Draft {
// Check for an existing release
if opts.TagName != "" {
if ok, err := publishedReleaseExists(httpClient, baseRepo, opts.TagName); err != nil {
return fmt.Errorf("error checking for existing release: %w", err)
} else if ok {
return fmt.Errorf("a release with the same tag name already exists: %s", opts.TagName)
}
}
// Save the release initially as draft and publish it after all assets have finished uploading
draftWhileUploading = true
params["draft"] = true
}
newRelease, err := createRelease(httpClient, baseRepo, params)
var errMissingRequiredWorkflowScope *errMissingRequiredWorkflowScope
if errors.As(err, &errMissingRequiredWorkflowScope) {
host := errMissingRequiredWorkflowScope.Hostname
refreshInstructions := fmt.Sprintf("gh auth refresh -h %[1]s -s workflow", host)
cs := opts.IO.ColorScheme()
var sb strings.Builder
sb.WriteString(fmt.Sprintf("%s Failed to create release, \"workflow\" scope may be required.\n", cs.WarningIcon()))
sb.WriteString(fmt.Sprintf("To request it, run:\n%s\n", cs.Bold(refreshInstructions)))
fmt.Fprint(opts.IO.ErrOut, sb.String())
return cmdutil.SilentError
}
if err != nil {
return err
}
cleanupDraftRelease := func(err error) error {
if !draftWhileUploading {
return err
}
if cleanupErr := deleteRelease(httpClient, newRelease); cleanupErr != nil {
return fmt.Errorf("%w\ncleaning up draft failed: %v", err, cleanupErr)
}
return err
}
if hasAssets {
uploadURL := newRelease.UploadURL
if idx := strings.IndexRune(uploadURL, '{'); idx > 0 {
uploadURL = uploadURL[:idx]
}
opts.IO.StartProgressIndicator()
err = shared.ConcurrentUpload(httpClient, uploadURL, opts.Concurrency, opts.Assets)
opts.IO.StopProgressIndicator()
if err != nil {
return cleanupDraftRelease(err)
}
if draftWhileUploading {
rel, err := publishRelease(httpClient, newRelease.APIURL, opts.DiscussionCategory, opts.IsLatest)
if err != nil {
return cleanupDraftRelease(err)
}
newRelease = rel
}
}
fmt.Fprintf(opts.IO.Out, "%s\n", newRelease.URL)
return nil
}
func gitTagInfo(client *git.Client, tagName string) (string, error) {
contentCmd, err := client.Command(context.Background(), "tag", "--list", tagName, "--format=%(contents)")
if err != nil {
return "", err
}
content, err := contentCmd.Output()
if err != nil {
return "", err
}
// If there is a signature, we should strip it from the end of the content.
// Note that, we can achieve this by looking for markers like "-----BEGIN PGP
// SIGNATURE-----" and cut the remaining text from the content, but this is
// not a safe approach, because, although unlikely, the content can contain
// a signature-like section which we shouldn't leave it as is. So, we need
// to get the tag signature as a whole, if any, and remote it from the content.
signatureCmd, err := client.Command(context.Background(), "tag", "--list", tagName, "--format=%(contents:signature)")
if err != nil {
return "", err
}
signature, err := signatureCmd.Output()
if err != nil {
return "", err
}
if len(signature) == 0 {
// The tag annotation content has no trailing signature to strip out,
// so we return the entire content.
return string(content), nil
}
body, _ := strings.CutSuffix(string(content), "\n"+string(signature))
return body, nil
}
func detectPreviousTag(client *git.Client, headRef string) (string, error) {
cmd, err := client.Command(context.Background(), "describe", "--tags", "--abbrev=0", fmt.Sprintf("%s^", headRef))
if err != nil {
return "", err
}
b, err := cmd.Output()
return strings.TrimSpace(string(b)), err
}
type logEntry struct {
Subject string
Body string
}
func changelogForRange(client *git.Client, refRange string) ([]logEntry, error) {
cmd, err := client.Command(context.Background(), "-c", "log.ShowSignature=false", "log", "--first-parent", "--reverse", "--pretty=format:%B%x00", refRange)
if err != nil {
return nil, err
}
b, err := cmd.Output()
if err != nil {
return nil, err
}
var entries []logEntry
for _, cb := range bytes.Split(b, []byte{'\000'}) {
c := strings.ReplaceAll(string(cb), "\r\n", "\n")
c = strings.TrimPrefix(c, "\n")
if len(c) == 0 {
continue
}
parts := strings.SplitN(c, "\n\n", 2)
var body string
subject := strings.ReplaceAll(parts[0], "\n", " ")
if len(parts) > 1 {
body = parts[1]
}
entries = append(entries, logEntry{
Subject: subject,
Body: body,
})
}
return entries, nil
}
func generateChangelog(commits []logEntry) string {
var parts []string
for _, c := range commits {
// TODO: consider rendering "Merge pull request #123 from owner/branch" differently
parts = append(parts, fmt.Sprintf("* %s", c.Subject))
if c.Body != "" {
parts = append(parts, text.Indent(c.Body, " "))
}
}
return strings.Join(parts, "\n\n")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/create/create_test.go | pkg/cmd/release/create/create_test.go | package create
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdCreate(t *testing.T) {
tempDir := t.TempDir()
tf, err := os.CreateTemp(tempDir, "release-create")
require.NoError(t, err)
fmt.Fprint(tf, "MY NOTES")
tf.Close()
af1, err := os.Create(filepath.Join(tempDir, "windows.zip"))
require.NoError(t, err)
af1.Close()
af2, err := os.Create(filepath.Join(tempDir, "linux.tgz"))
require.NoError(t, err)
af2.Close()
tests := []struct {
name string
args string
isTTY bool
stdin string
want CreateOptions
wantErr string
}{
{
name: "no arguments tty",
args: "",
isTTY: true,
want: CreateOptions{
TagName: "",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
VerifyTag: false,
FailOnNoCommits: false,
},
},
{
name: "no arguments notty",
args: "",
isTTY: false,
wantErr: "tag required when not running interactively",
},
{
name: "only tag name",
args: "v1.2.3",
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
VerifyTag: false,
FailOnNoCommits: false,
},
},
{
name: "asset files",
args: fmt.Sprintf("v1.2.3 '%s' '%s#Linux build'", af1.Name(), af2.Name()),
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload{
{
Name: "windows.zip",
Label: "",
},
{
Name: "linux.tgz",
Label: "Linux build",
},
},
},
},
{
name: "provide title and body",
args: "v1.2.3 -t mytitle -n mynotes",
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "mytitle",
Body: "mynotes",
BodyProvided: true,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
},
},
{
name: "notes from file",
args: fmt.Sprintf(`v1.2.3 -F '%s'`, tf.Name()),
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "MY NOTES",
BodyProvided: true,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
},
},
{
name: "notes from stdin",
args: "v1.2.3 -F -",
isTTY: true,
stdin: "MY NOTES",
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "MY NOTES",
BodyProvided: true,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
},
},
{
name: "set draft and prerelease",
args: "v1.2.3 -d -p",
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: true,
Prerelease: true,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
},
},
{
name: "discussion category",
args: "v1.2.3 --discussion-category 'General'",
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
DiscussionCategory: "General",
},
},
{
name: "discussion category for draft release",
args: "v1.2.3 -d --discussion-category 'General'",
isTTY: true,
wantErr: "discussions for draft releases not supported",
},
{
name: "generate release notes",
args: "v1.2.3 --generate-notes",
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
GenerateNotes: true,
},
},
{
name: "generate release notes with notes tag",
args: "v1.2.3 --generate-notes --notes-start-tag v1.1.0",
isTTY: true,
want: CreateOptions{
TagName: "v1.2.3",
Target: "",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
GenerateNotes: true,
NotesStartTag: "v1.1.0",
},
},
{
name: "notes tag",
args: "--notes-start-tag v1.1.0",
isTTY: true,
want: CreateOptions{
TagName: "",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
GenerateNotes: false,
NotesStartTag: "v1.1.0",
},
},
{
name: "latest",
args: "--latest v1.1.0",
isTTY: false,
want: CreateOptions{
TagName: "v1.1.0",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
IsLatest: boolPtr(true),
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
GenerateNotes: false,
NotesStartTag: "",
},
},
{
name: "not latest",
args: "--latest=false v1.1.0",
isTTY: false,
want: CreateOptions{
TagName: "v1.1.0",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
IsLatest: boolPtr(false),
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
GenerateNotes: false,
NotesStartTag: "",
},
},
{
name: "with verify-tag",
args: "v1.1.0 --verify-tag",
isTTY: true,
want: CreateOptions{
TagName: "v1.1.0",
Target: "",
Name: "",
Body: "",
BodyProvided: false,
Draft: false,
Prerelease: false,
RepoOverride: "",
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
GenerateNotes: false,
VerifyTag: true,
},
},
{
name: "with --notes-from-tag",
args: "v1.2.3 --notes-from-tag",
isTTY: false,
want: CreateOptions{
TagName: "v1.2.3",
BodyProvided: true,
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
NotesFromTag: true,
},
},
{
name: "with --notes-from-tag and --generate-notes",
args: "v1.2.3 --notes-from-tag --generate-notes",
isTTY: false,
wantErr: "using `--notes-from-tag` with `--generate-notes` or `--notes-start-tag` is not supported",
},
{
name: "with --notes-from-tag and --notes-start-tag",
args: "v1.2.3 --notes-from-tag --notes-start-tag v1.2.3",
isTTY: false,
wantErr: "using `--notes-from-tag` with `--generate-notes` or `--notes-start-tag` is not supported",
},
{
name: "with --fail-on-no-commits",
args: "v1.2.3 --fail-on-no-commits",
isTTY: false,
want: CreateOptions{
TagName: "v1.2.3",
BodyProvided: false,
Concurrency: 5,
Assets: []*shared.AssetForUpload(nil),
NotesFromTag: false,
FailOnNoCommits: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
if tt.stdin == "" {
ios.SetStdinTTY(tt.isTTY)
} else {
ios.SetStdinTTY(false)
fmt.Fprint(stdin, tt.stdin)
}
ios.SetStdoutTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *CreateOptions
cmd := NewCmdCreate(f, func(o *CreateOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.TagName, opts.TagName)
assert.Equal(t, tt.want.Target, opts.Target)
assert.Equal(t, tt.want.Name, opts.Name)
assert.Equal(t, tt.want.Body, opts.Body)
assert.Equal(t, tt.want.BodyProvided, opts.BodyProvided)
assert.Equal(t, tt.want.Draft, opts.Draft)
assert.Equal(t, tt.want.Prerelease, opts.Prerelease)
assert.Equal(t, tt.want.Concurrency, opts.Concurrency)
assert.Equal(t, tt.want.RepoOverride, opts.RepoOverride)
assert.Equal(t, tt.want.DiscussionCategory, opts.DiscussionCategory)
assert.Equal(t, tt.want.GenerateNotes, opts.GenerateNotes)
assert.Equal(t, tt.want.NotesStartTag, opts.NotesStartTag)
assert.Equal(t, tt.want.IsLatest, opts.IsLatest)
assert.Equal(t, tt.want.VerifyTag, opts.VerifyTag)
assert.Equal(t, tt.want.NotesFromTag, opts.NotesFromTag)
assert.Equal(t, tt.want.FailOnNoCommits, opts.FailOnNoCommits)
require.Equal(t, len(tt.want.Assets), len(opts.Assets))
for i := range tt.want.Assets {
assert.Equal(t, tt.want.Assets[i].Name, opts.Assets[i].Name)
assert.Equal(t, tt.want.Assets[i].Label, opts.Assets[i].Label)
}
})
}
}
func Test_createRun(t *testing.T) {
const contentCmd = `git tag --list .* --format=%\(contents\)`
const signatureCmd = `git tag --list .* --format=%\(contents:signature\)`
defaultRunStubs := func(rs *run.CommandStubber) {
rs.Register(contentCmd, 0, "")
rs.Register(signatureCmd, 0, "")
}
tests := []struct {
name string
isTTY bool
opts CreateOptions
httpStubs func(t *testing.T, reg *httpmock.Registry)
runStubs func(rs *run.CommandStubber)
wantErr string
wantStdout string
wantStderr string
}{
{
name: "create a release",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "The Big 1.2",
Body: "* Fixed bugs",
BodyProvided: true,
Target: "",
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"name": "The Big 1.2",
"body": "* Fixed bugs",
"draft": false,
"prerelease": false,
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: ``,
},
{
name: "create a release if there are new commits and the last release does not exist",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "The Big 1.2",
Body: "* Fixed bugs",
BodyProvided: true,
Target: "",
FailOnNoCommits: true,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "repos/OWNER/REPO/releases/latest"), httpmock.StatusStringResponse(404, `{
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest/releases/releases#get-the-latest-release",
"status": "404"
}`))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"name": "The Big 1.2",
"body": "* Fixed bugs",
"draft": false,
"prerelease": false,
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: ``,
},
{
name: "create a release if there are new commits and the last release exists",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "The Big 1.2",
Body: "* Fixed bugs",
BodyProvided: true,
Target: "",
FailOnNoCommits: true,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "repos/OWNER/REPO/releases/latest"), httpmock.StatusStringResponse(200, `{
"tag_name": "v1.2.2"
}`))
reg.Register(httpmock.REST("GET", "repos/OWNER/REPO/compare/v1.2.2...HEAD"), httpmock.StatusStringResponse(200, `{
"status": "ahead"
}`))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"name": "The Big 1.2",
"body": "* Fixed bugs",
"draft": false,
"prerelease": false,
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: ``,
},
{
name: "create a release if there are no new commits but the last release exists",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "The Big 1.2",
Body: "* Fixed bugs",
BodyProvided: true,
Target: "",
FailOnNoCommits: true,
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "repos/OWNER/REPO/releases/latest"), httpmock.StatusStringResponse(200, `{
"tag_name": "v1.2.2"
}`))
reg.Register(httpmock.REST("GET", "repos/OWNER/REPO/compare/v1.2.2...HEAD"), httpmock.StatusStringResponse(200, `{
"status": "identical"
}`))
},
wantErr: "no new commits since the last release",
wantStdout: "",
wantStderr: ``,
},
{
name: "with discussion category",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "The Big 1.2",
Body: "* Fixed bugs",
BodyProvided: true,
Target: "",
DiscussionCategory: "General",
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"name": "The Big 1.2",
"body": "* Fixed bugs",
"draft": false,
"prerelease": false,
"discussion_category_name": "General",
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: ``,
},
{
name: "with target commitish",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Target: "main",
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": false,
"prerelease": false,
"target_commitish": "main",
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: ``,
},
{
name: "as draft",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: true,
Target: "",
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": true,
"prerelease": false,
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantStderr: ``,
},
{
name: "with latest",
isTTY: false,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
Target: "",
IsLatest: boolPtr(true),
BodyProvided: true,
GenerateNotes: false,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": false,
"prerelease": false,
"make_latest": "true",
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantErr: "",
},
{
name: "with generate notes",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
Target: "",
BodyProvided: true,
GenerateNotes: true,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": false,
"prerelease": false,
"generate_release_notes": true,
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantErr: "",
},
{
name: "with generate notes and notes tag",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
Target: "",
BodyProvided: true,
GenerateNotes: true,
NotesStartTag: "v1.1.0",
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases/generate-notes"),
httpmock.RESTPayload(200, `{
"name": "generated name",
"body": "generated body"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"previous_tag_name": "v1.1.0",
}, params)
}))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": false,
"prerelease": false,
"body": "generated body",
"name": "generated name",
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantErr: "",
},
{
name: "with generate notes and notes tag and body and name",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "name",
Body: "body",
Target: "",
BodyProvided: true,
GenerateNotes: true,
NotesStartTag: "v1.1.0",
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases/generate-notes"),
httpmock.RESTPayload(200, `{
"name": "generated name",
"body": "generated body"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"previous_tag_name": "v1.1.0",
}, params)
}))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": false,
"prerelease": false,
"body": "body\ngenerated body",
"name": "name",
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3\n",
wantErr: "",
},
{
name: "publish after uploading files",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Target: "",
Assets: []*shared.AssetForUpload{
{
Name: "ball.tgz",
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`TARBALL`)), nil
},
},
},
Concurrency: 1,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("HEAD", "repos/OWNER/REPO/releases/tags/v1.2.3"), httpmock.StatusStringResponse(404, ``))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": true,
"prerelease": false,
}, params)
}))
reg.Register(httpmock.REST("POST", "assets/upload"), func(req *http.Request) (*http.Response, error) {
q := req.URL.Query()
assert.Equal(t, "ball.tgz", q.Get("name"))
assert.Equal(t, "", q.Get("label"))
return &http.Response{
StatusCode: 201,
Request: req,
Body: io.NopCloser(bytes.NewBufferString(`{}`)),
Header: map[string][]string{
"Content-Type": {"application/json"},
},
}, nil
})
reg.Register(httpmock.REST("PATCH", "releases/123"), httpmock.RESTPayload(201, `{
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3-final"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"draft": false,
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3-final\n",
wantStderr: ``,
},
{
name: "publish after uploading files, but do not mark as latest",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
IsLatest: boolPtr(false),
Target: "",
Assets: []*shared.AssetForUpload{
{
Name: "ball.tgz",
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`TARBALL`)), nil
},
},
},
Concurrency: 1,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("HEAD", "repos/OWNER/REPO/releases/tags/v1.2.3"), httpmock.StatusStringResponse(404, ``))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"tag_name": "v1.2.3",
"draft": true,
"prerelease": false,
"make_latest": "false",
}, params)
}))
reg.Register(httpmock.REST("POST", "assets/upload"), func(req *http.Request) (*http.Response, error) {
q := req.URL.Query()
assert.Equal(t, "ball.tgz", q.Get("name"))
assert.Equal(t, "", q.Get("label"))
return &http.Response{
StatusCode: 201,
Request: req,
Body: io.NopCloser(bytes.NewBufferString(`{}`)),
Header: map[string][]string{
"Content-Type": {"application/json"},
},
}, nil
})
reg.Register(httpmock.REST("PATCH", "releases/123"), httpmock.RESTPayload(201, `{
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3-final"
}`, func(params map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"draft": false,
"make_latest": "false",
}, params)
}))
},
wantStdout: "https://github.com/OWNER/REPO/releases/tag/v1.2.3-final\n",
wantStderr: ``,
},
{
name: "upload files but release already exists",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Target: "",
Assets: []*shared.AssetForUpload{
{
Name: "ball.tgz",
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`TARBALL`)), nil
},
},
},
Concurrency: 1,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("HEAD", "repos/OWNER/REPO/releases/tags/v1.2.3"), httpmock.StatusStringResponse(200, ``))
},
wantStdout: ``,
wantStderr: ``,
wantErr: `a release with the same tag name already exists: v1.2.3`,
},
{
name: "clean up draft after uploading files fails",
isTTY: false,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Target: "",
Assets: []*shared.AssetForUpload{
{
Name: "ball.tgz",
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`TARBALL`)), nil
},
},
},
Concurrency: 1,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("HEAD", "repos/OWNER/REPO/releases/tags/v1.2.3"), httpmock.StatusStringResponse(404, ``))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.StatusStringResponse(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`))
reg.Register(httpmock.REST("POST", "assets/upload"), httpmock.StatusStringResponse(422, `{}`))
reg.Register(httpmock.REST("DELETE", "releases/123"), httpmock.StatusStringResponse(204, ``))
},
wantStdout: ``,
wantStderr: ``,
wantErr: `HTTP 422 (https://api.github.com/assets/upload?label=&name=ball.tgz)`,
},
{
name: "clean up draft after publishing fails",
isTTY: false,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Target: "",
Assets: []*shared.AssetForUpload{
{
Name: "ball.tgz",
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`TARBALL`)), nil
},
},
},
Concurrency: 1,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("HEAD", "repos/OWNER/REPO/releases/tags/v1.2.3"), httpmock.StatusStringResponse(404, ``))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.StatusStringResponse(201, `{
"url": "https://api.github.com/releases/123",
"upload_url": "https://api.github.com/assets/upload",
"html_url": "https://github.com/OWNER/REPO/releases/tag/v1.2.3"
}`))
reg.Register(httpmock.REST("POST", "assets/upload"), httpmock.StatusStringResponse(201, `{}`))
reg.Register(httpmock.REST("PATCH", "releases/123"), httpmock.StatusStringResponse(500, `{}`))
reg.Register(httpmock.REST("DELETE", "releases/123"), httpmock.StatusStringResponse(204, ``))
},
wantStdout: ``,
wantStderr: ``,
wantErr: `HTTP 500 (https://api.github.com/releases/123)`,
},
{
name: "upload files but release already exists",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Target: "",
Assets: []*shared.AssetForUpload{
{
Name: "ball.tgz",
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`TARBALL`)), nil
},
},
},
Concurrency: 1,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("HEAD", "repos/OWNER/REPO/releases/tags/v1.2.3"), httpmock.StatusStringResponse(200, ``))
},
wantStdout: ``,
wantStderr: ``,
wantErr: `a release with the same tag name already exists: v1.2.3`,
},
{
name: "upload files and create discussion",
isTTY: true,
opts: CreateOptions{
TagName: "v1.2.3",
Name: "",
Body: "",
BodyProvided: true,
Draft: false,
Target: "",
Assets: []*shared.AssetForUpload{
{
Name: "ball.tgz",
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`TARBALL`)), nil
},
},
},
DiscussionCategory: "general",
Concurrency: 1,
},
runStubs: defaultRunStubs,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(httpmock.REST("HEAD", "repos/OWNER/REPO/releases/tags/v1.2.3"), httpmock.StatusStringResponse(404, ``))
reg.Register(httpmock.REST("POST", "repos/OWNER/REPO/releases"), httpmock.RESTPayload(201, `{
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/create/http.go | pkg/cmd/release/create/http.go | package create
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/shurcooL/githubv4"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
)
type tag struct {
Name string `json:"name"`
}
type releaseNotes struct {
Name string `json:"name"`
Body string `json:"body"`
}
var notImplementedError = errors.New("not implemented")
type errMissingRequiredWorkflowScope struct {
Hostname string
}
func (e errMissingRequiredWorkflowScope) Error() string {
return "workflow scope may be required"
}
func remoteTagExists(httpClient *http.Client, repo ghrepo.Interface, tagName string) (bool, error) {
gql := api.NewClientFromHTTP(httpClient)
qualifiedTagName := fmt.Sprintf("refs/tags/%s", tagName)
var query struct {
Repository struct {
Ref struct {
ID string
} `graphql:"ref(qualifiedName: $tagName)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]interface{}{
"owner": githubv4.String(repo.RepoOwner()),
"name": githubv4.String(repo.RepoName()),
"tagName": githubv4.String(qualifiedTagName),
}
err := gql.Query(repo.RepoHost(), "RepositoryFindRef", &query, variables)
return query.Repository.Ref.ID != "", err
}
func getTags(httpClient *http.Client, repo ghrepo.Interface, limit int) ([]tag, error) {
path := fmt.Sprintf("repos/%s/%s/tags?per_page=%d", repo.RepoOwner(), repo.RepoName(), limit)
url := ghinstance.RESTPrefix(repo.RepoHost()) + path
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var tags []tag
err = json.Unmarshal(b, &tags)
return tags, err
}
func generateReleaseNotes(httpClient *http.Client, repo ghrepo.Interface, tagName, target, previousTagName string) (*releaseNotes, error) {
params := map[string]interface{}{
"tag_name": tagName,
}
if target != "" {
params["target_commitish"] = target
}
if previousTagName != "" {
params["previous_tag_name"] = previousTagName
}
bodyBytes, err := json.Marshal(params)
if err != nil {
return nil, err
}
path := fmt.Sprintf("repos/%s/%s/releases/generate-notes", repo.RepoOwner(), repo.RepoName())
url := ghinstance.RESTPrefix(repo.RepoHost()) + path
req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == 404 {
return nil, notImplementedError
}
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var rn releaseNotes
err = json.Unmarshal(b, &rn)
return &rn, err
}
func publishedReleaseExists(httpClient *http.Client, repo ghrepo.Interface, tagName string) (bool, error) {
path := fmt.Sprintf("repos/%s/%s/releases/tags/%s", repo.RepoOwner(), repo.RepoName(), url.PathEscape(tagName))
url := ghinstance.RESTPrefix(repo.RepoHost()) + path
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
return false, err
}
resp, err := httpClient.Do(req)
if err != nil {
return false, err
}
if resp.Body != nil {
defer resp.Body.Close()
}
if resp.StatusCode == 200 {
return true, nil
} else if resp.StatusCode == 404 {
return false, nil
} else {
return false, api.HandleHTTPError(resp)
}
}
func createRelease(httpClient *http.Client, repo ghrepo.Interface, params map[string]interface{}) (*shared.Release, error) {
bodyBytes, err := json.Marshal(params)
if err != nil {
return nil, err
}
path := fmt.Sprintf("repos/%s/%s/releases", repo.RepoOwner(), repo.RepoName())
url := ghinstance.RESTPrefix(repo.RepoHost()) + path
req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Check if we received a 404 while attempting to create a release without
// the workflow scope, and if so, return an error message that explains a possible
// solution to the user.
//
// If the same file (with both the same path and contents) exists
// on another branch in the repo, releases with workflow file changes can be
// created without the workflow scope. Otherwise, the workflow scope is
// required to create the release, but the API does not indicate this criteria
// beyond returning a 404.
//
// https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps#available-scopes
if resp.StatusCode == http.StatusNotFound && !tokenHasWorkflowScope(resp) {
normalizedHostname := ghauth.NormalizeHostname(resp.Request.URL.Hostname())
return nil, &errMissingRequiredWorkflowScope{
Hostname: normalizedHostname,
}
}
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var newRelease shared.Release
err = json.Unmarshal(b, &newRelease)
return &newRelease, err
}
func publishRelease(httpClient *http.Client, releaseURL string, discussionCategory string, isLatest *bool) (*shared.Release, error) {
params := map[string]interface{}{"draft": false}
if discussionCategory != "" {
params["discussion_category_name"] = discussionCategory
}
if isLatest != nil {
params["make_latest"] = fmt.Sprintf("%v", *isLatest)
}
bodyBytes, err := json.Marshal(params)
if err != nil {
return nil, err
}
req, err := http.NewRequest("PATCH", releaseURL, bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
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 release shared.Release
err = json.Unmarshal(b, &release)
return &release, err
}
func deleteRelease(httpClient *http.Client, release *shared.Release) error {
req, err := http.NewRequest("DELETE", release.APIURL, nil)
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
if resp.Body != nil {
defer resp.Body.Close()
}
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return api.HandleHTTPError(resp)
}
if resp.StatusCode != 204 {
_, _ = io.Copy(io.Discard, resp.Body)
}
return nil
}
// tokenHasWorkflowScope checks if the given http.Response's token has the workflow scope.
// Tokens that do not have OAuth scopes are assumed to have the workflow scope.
func tokenHasWorkflowScope(resp *http.Response) bool {
scopes := resp.Header.Get("X-Oauth-Scopes")
// Return true when no scopes are present - no scopes in this header
// means that the user is probably authenticating with a token type other
// than an OAuth token, and we don't know what this token's scopes actually are.
if scopes == "" {
return true
}
return slices.Contains(strings.Split(scopes, ","), "workflow")
}
// isNewRelease checks if there are new commits since the latest release.
func isNewRelease(httpClient *http.Client, repo ghrepo.Interface) (bool, error) {
ctx := context.Background()
release, err := shared.FetchLatestRelease(ctx, httpClient, repo)
if err != nil {
if errors.Is(err, shared.ErrReleaseNotFound) {
return true, nil
} else {
return false, err
}
}
tagName := release.TagName
path := fmt.Sprintf("repos/%s/%s/compare/%s...HEAD?per_page=1", repo.RepoOwner(), repo.RepoName(), tagName)
var comparisonStatus struct {
Status string `json:"status"`
}
apiClient := api.NewClientFromHTTP(httpClient)
if err := apiClient.REST(repo.RepoHost(), "GET", path, nil, &comparisonStatus); err != nil {
return false, err
}
isNew := comparisonStatus.Status == "ahead"
return isNew, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/shared/fetch_test.go | pkg/cmd/release/shared/fetch_test.go | package shared
import (
"context"
"net/http"
"testing"
"github.com/cli/go-gh/v2/pkg/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFetchRefSHA(t *testing.T) {
tests := []struct {
name string
tagName string
responseStatus int
responseBody string
responseMessage string
expectedSHA string
errorMessage string
}{
{
name: "match (200)",
tagName: "v1.2.3",
responseStatus: 200,
responseBody: `{"object": {"sha": "1234567890abcdef1234567890abcdef12345678"}}`,
expectedSHA: "1234567890abcdef1234567890abcdef12345678",
},
{
name: "non-match (404)",
tagName: "v1.2.3",
responseStatus: 404,
responseMessage: `Not found`,
errorMessage: "release not found",
},
{
name: "server error (500)",
tagName: "v1.2.3",
responseStatus: 500,
responseMessage: `arbitrary error"`,
errorMessage: "HTTP 500: arbitrary error\" (https://api.github.com/repos/owner/repo/git/ref/tags/v1.2.3)",
},
{
name: "malformed JSON with 200",
tagName: "v1.2.3",
responseStatus: 200,
responseBody: `{"object": {"sha":`,
errorMessage: "failed to parse ref response: unexpected EOF",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
repo, err := ghrepo.FromFullName("owner/repo")
require.NoError(t, err)
path := "repos/owner/repo/git/ref/tags/" + tt.tagName
if tt.responseStatus == 404 || tt.responseStatus == 500 {
fakeHTTP.Register(
httpmock.REST("GET", path),
httpmock.JSONErrorResponse(tt.responseStatus, api.HTTPError{
StatusCode: tt.responseStatus,
Message: tt.responseMessage,
}),
)
} else {
fakeHTTP.Register(
httpmock.REST("GET", path),
httpmock.StatusStringResponse(tt.responseStatus, tt.responseBody),
)
}
httpClient := &http.Client{Transport: fakeHTTP}
ctx := context.Background()
sha, err := FetchRefSHA(ctx, httpClient, repo, tt.tagName)
if tt.errorMessage != "" {
assert.Contains(t, err.Error(), tt.errorMessage)
assert.Empty(t, sha)
} else {
require.NoError(t, err)
assert.Equal(t, tt.expectedSHA, sha)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/shared/upload_test.go | pkg/cmd/release/shared/upload_test.go | package shared
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"testing"
)
func Test_typeForFilename(t *testing.T) {
tests := []struct {
name string
file string
want string
}{
{
name: "tar",
file: "ball.tar",
want: "application/x-tar",
},
{
name: "tgz",
file: "ball.tgz",
want: "application/x-gtar",
},
{
name: "tar.gz",
file: "ball.tar.gz",
want: "application/x-gtar",
},
{
name: "bz2",
file: "ball.tar.bz2",
want: "application/x-bzip2",
},
{
name: "zip",
file: "archive.zip",
want: "application/zip",
},
{
name: "js",
file: "app.js",
want: "application/javascript",
},
{
name: "dmg",
file: "apple.dmg",
want: "application/x-apple-diskimage",
},
{
name: "rpm",
file: "package.rpm",
want: "application/x-rpm",
},
{
name: "deb",
file: "package.deb",
want: "application/x-debian-package",
},
{
name: "no extension",
file: "myfile",
want: "application/octet-stream",
},
}
for _, tt := range tests {
t.Run(tt.file, func(t *testing.T) {
if got := typeForFilename(tt.file); got != tt.want {
t.Errorf("typeForFilename() = %v, want %v", got, tt.want)
}
})
}
}
func Test_uploadWithDelete_retry(t *testing.T) {
retryInterval = 0
ctx := context.Background()
tries := 0
client := funcClient(func(req *http.Request) (*http.Response, error) {
tries++
if tries == 1 {
return nil, errors.New("made up exception")
} else if tries == 2 {
return &http.Response{
Request: req,
StatusCode: 500,
Body: io.NopCloser(bytes.NewBufferString(`{}`)),
}, nil
}
return &http.Response{
Request: req,
StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(`{}`)),
}, nil
})
err := uploadWithDelete(ctx, client, "http://example.com/upload", AssetForUpload{
Name: "asset",
Label: "",
Size: 8,
Open: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewBufferString(`somebody`)), nil
},
MIMEType: "application/octet-stream",
})
if err != nil {
t.Errorf("uploadWithDelete() error: %v", err)
}
if tries != 3 {
t.Errorf("tries = %d, expected %d", tries, 3)
}
}
type funcClient func(*http.Request) (*http.Response, error)
func (f funcClient) Do(req *http.Request) (*http.Response, error) {
return f(req)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/shared/fetch.go | pkg/cmd/release/shared/fetch.go | package shared
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"testing"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/shurcooL/githubv4"
"github.com/stretchr/testify/assert"
)
var ReleaseFields = []string{
"apiUrl",
"author",
"assets",
"body",
"createdAt",
"databaseId",
"id",
"isDraft",
"isPrerelease",
"isImmutable",
"name",
"publishedAt",
"tagName",
"tarballUrl",
"targetCommitish",
"uploadUrl",
"url",
"zipballUrl",
}
type Release struct {
DatabaseID int64 `json:"id"`
ID string `json:"node_id"`
TagName string `json:"tag_name"`
Name string `json:"name"`
Body string `json:"body"`
IsDraft bool `json:"draft"`
IsPrerelease bool `json:"prerelease"`
IsImmutable bool `json:"immutable"`
CreatedAt time.Time `json:"created_at"`
PublishedAt *time.Time `json:"published_at"`
TargetCommitish string `json:"target_commitish"`
APIURL string `json:"url"`
UploadURL string `json:"upload_url"`
TarballURL string `json:"tarball_url"`
ZipballURL string `json:"zipball_url"`
URL string `json:"html_url"`
Assets []ReleaseAsset
Author struct {
ID string `json:"node_id"`
Login string `json:"login"`
}
}
type ReleaseAsset struct {
ID string `json:"node_id"`
Name string
Label string
Size int64
Digest *string
State string
APIURL string `json:"url"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DownloadCount int `json:"download_count"`
ContentType string `json:"content_type"`
BrowserDownloadURL string `json:"browser_download_url"`
}
func (rel *Release) ExportData(fields []string) map[string]interface{} {
v := reflect.ValueOf(rel).Elem()
fieldByName := func(v reflect.Value, field string) reflect.Value {
return v.FieldByNameFunc(func(s string) bool {
return strings.EqualFold(field, s)
})
}
data := map[string]interface{}{}
for _, f := range fields {
switch f {
case "author":
data[f] = map[string]interface{}{
"id": rel.Author.ID,
"login": rel.Author.Login,
}
case "assets":
assets := make([]interface{}, 0, len(rel.Assets))
for _, a := range rel.Assets {
assets = append(assets, map[string]interface{}{
"url": a.BrowserDownloadURL,
"apiUrl": a.APIURL,
"id": a.ID,
"name": a.Name,
"label": a.Label,
"size": a.Size,
"digest": a.Digest,
"state": a.State,
"createdAt": a.CreatedAt,
"updatedAt": a.UpdatedAt,
"downloadCount": a.DownloadCount,
"contentType": a.ContentType,
})
}
data[f] = assets
default:
sf := fieldByName(v, f)
data[f] = sf.Interface()
}
}
return data
}
var ErrReleaseNotFound = errors.New("release not found")
type fetchResult struct {
release *Release
error error
}
func FetchRefSHA(ctx context.Context, httpClient *http.Client, repo ghrepo.Interface, tagName string) (string, error) {
path := fmt.Sprintf("repos/%s/%s/git/ref/tags/%s", repo.RepoOwner(), repo.RepoName(), tagName)
req, err := http.NewRequestWithContext(ctx, "GET", ghinstance.RESTPrefix(repo.RepoHost())+path, nil)
if err != nil {
return "", err
}
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
_, _ = io.Copy(io.Discard, resp.Body)
return "", ErrReleaseNotFound
}
if resp.StatusCode > 299 {
return "", api.HandleHTTPError(resp)
}
var ref struct {
Object struct {
SHA string `json:"sha"`
} `json:"object"`
}
if err := json.NewDecoder(resp.Body).Decode(&ref); err != nil {
return "", fmt.Errorf("failed to parse ref response: %w", err)
}
return ref.Object.SHA, nil
}
// FetchRelease finds a published repository release by its tagName, or a draft release by its pending tag name.
func FetchRelease(ctx context.Context, httpClient *http.Client, repo ghrepo.Interface, tagName string) (*Release, error) {
cc, cancel := context.WithCancel(ctx)
results := make(chan fetchResult, 2)
// published release lookup
go func() {
path := fmt.Sprintf("repos/%s/%s/releases/tags/%s", repo.RepoOwner(), repo.RepoName(), tagName)
release, err := fetchReleasePath(cc, httpClient, repo.RepoHost(), path)
results <- fetchResult{release: release, error: err}
}()
// draft release lookup
go func() {
release, err := fetchDraftRelease(cc, httpClient, repo, tagName)
results <- fetchResult{release: release, error: err}
}()
res := <-results
if errors.Is(res.error, ErrReleaseNotFound) {
res = <-results
cancel() // satisfy the linter even though no goroutines are running anymore
} else {
cancel()
<-results // drain the channel
}
return res.release, res.error
}
// FetchLatestRelease finds the latest published release for a repository.
func FetchLatestRelease(ctx context.Context, httpClient *http.Client, repo ghrepo.Interface) (*Release, error) {
path := fmt.Sprintf("repos/%s/%s/releases/latest", repo.RepoOwner(), repo.RepoName())
return fetchReleasePath(ctx, httpClient, repo.RepoHost(), path)
}
// fetchDraftRelease returns the first draft release that has tagName as its pending tag.
func fetchDraftRelease(ctx context.Context, httpClient *http.Client, repo ghrepo.Interface, tagName string) (*Release, error) {
// First use GraphQL to find a draft release by pending tag name, since REST doesn't have this ability.
var query struct {
Repository struct {
Release *struct {
DatabaseID int64
IsDraft bool
} `graphql:"release(tagName: $tagName)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]interface{}{
"owner": githubv4.String(repo.RepoOwner()),
"name": githubv4.String(repo.RepoName()),
"tagName": githubv4.String(tagName),
}
gql := api.NewClientFromHTTP(httpClient)
if err := gql.QueryWithContext(ctx, repo.RepoHost(), "RepositoryReleaseByTag", &query, variables); err != nil {
return nil, err
}
if query.Repository.Release == nil || !query.Repository.Release.IsDraft {
return nil, ErrReleaseNotFound
}
// Then, use REST to get information about the draft release. In theory, we could have fetched
// all the necessary information via GraphQL, but REST is safer for backwards compatibility.
path := fmt.Sprintf("repos/%s/%s/releases/%d", repo.RepoOwner(), repo.RepoName(), query.Repository.Release.DatabaseID)
return fetchReleasePath(ctx, httpClient, repo.RepoHost(), path)
}
func fetchReleasePath(ctx context.Context, httpClient *http.Client, host string, p string) (*Release, error) {
req, err := http.NewRequestWithContext(ctx, "GET", ghinstance.RESTPrefix(host)+p, 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 == http.StatusNotFound {
_, _ = io.Copy(io.Discard, resp.Body)
return nil, ErrReleaseNotFound
} else if resp.StatusCode > 299 {
return nil, api.HandleHTTPError(resp)
}
var release Release
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return nil, err
}
return &release, nil
}
func StubFetchRelease(t *testing.T, reg *httpmock.Registry, owner, repoName, tagName, responseBody string) {
path := "repos/OWNER/REPO/releases/tags/v1.2.3"
if tagName == "" {
path = "repos/OWNER/REPO/releases/latest"
}
reg.Register(httpmock.REST("GET", path), httpmock.StringResponse(responseBody))
if tagName != "" {
reg.Register(
httpmock.GraphQL(`query RepositoryReleaseByTag\b`),
httpmock.GraphQLQuery(`{ "data": { "repository": { "release": null }}}`,
func(q string, vars map[string]interface{}) {
assert.Equal(t, owner, vars["owner"])
assert.Equal(t, repoName, vars["name"])
assert.Equal(t, tagName, vars["tagName"])
}),
)
}
}
func StubFetchRefSHA(t *testing.T, reg *httpmock.Registry, owner, repoName, tagName, sha string) {
path := fmt.Sprintf("repos/%s/%s/git/ref/tags/%s", owner, repoName, tagName)
reg.Register(
httpmock.REST("GET", path),
httpmock.StringResponse(fmt.Sprintf(`{"object": {"sha": "%s"}}`, sha)),
)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/shared/upload.go | pkg/cmd/release/shared/upload.go | package shared
import (
"context"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/pkg/cmdutil"
"golang.org/x/sync/errgroup"
)
type httpDoer interface {
Do(*http.Request) (*http.Response, error)
}
type errNetwork struct{ error }
type AssetForUpload struct {
Name string
Label string
Size int64
MIMEType string
Open func() (io.ReadCloser, error)
ExistingURL string
}
func AssetsFromArgs(args []string) (assets []*AssetForUpload, err error) {
labeledArgs, unlabeledArgs := cmdutil.Partition(args, func(arg string) bool {
return strings.Contains(arg, "#")
})
args, err = cmdutil.GlobPaths(unlabeledArgs)
if err != nil {
return nil, err
}
args = append(args, labeledArgs...)
for _, arg := range args {
var label string
fn := arg
if idx := strings.IndexRune(arg, '#'); idx > 0 {
fn = arg[0:idx]
label = arg[idx+1:]
}
var fi os.FileInfo
fi, err = os.Stat(fn)
if err != nil {
return
}
assets = append(assets, &AssetForUpload{
Open: func() (io.ReadCloser, error) {
return os.Open(fn)
},
Size: fi.Size(),
Name: fi.Name(),
Label: label,
MIMEType: typeForFilename(fi.Name()),
})
}
return
}
func typeForFilename(fn string) string {
ext := fileExt(fn)
switch ext {
case ".zip":
return "application/zip"
case ".js":
return "application/javascript"
case ".tar":
return "application/x-tar"
case ".tgz", ".tar.gz":
return "application/x-gtar"
case ".bz2":
return "application/x-bzip2"
case ".dmg":
return "application/x-apple-diskimage"
case ".rpm":
return "application/x-rpm"
case ".deb":
return "application/x-debian-package"
}
t := mime.TypeByExtension(ext)
if t == "" {
return "application/octet-stream"
}
return t
}
func fileExt(fn string) string {
fn = strings.ToLower(fn)
if strings.HasSuffix(fn, ".tar.gz") {
return ".tar.gz"
}
return path.Ext(fn)
}
func ConcurrentUpload(httpClient httpDoer, uploadURL string, numWorkers int, assets []*AssetForUpload) error {
if numWorkers == 0 {
return errors.New("the number of concurrent workers needs to be greater than 0")
}
ctx := context.Background()
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(numWorkers)
for _, a := range assets {
asset := *a
g.Go(func() error {
return uploadWithDelete(gctx, httpClient, uploadURL, asset)
})
}
return g.Wait()
}
func shouldRetry(err error) bool {
var networkError errNetwork
if errors.As(err, &networkError) {
return true
}
var httpError api.HTTPError
return errors.As(err, &httpError) && httpError.StatusCode >= 500
}
// Allow injecting backoff interval in tests.
var retryInterval = time.Millisecond * 200
func uploadWithDelete(ctx context.Context, httpClient httpDoer, uploadURL string, a AssetForUpload) error {
if a.ExistingURL != "" {
if err := deleteAsset(ctx, httpClient, a.ExistingURL); err != nil {
return err
}
}
bo := backoff.NewConstantBackOff(retryInterval)
return backoff.Retry(func() error {
_, err := uploadAsset(ctx, httpClient, uploadURL, a)
if err == nil || shouldRetry(err) {
return err
}
return backoff.Permanent(err)
}, backoff.WithContext(backoff.WithMaxRetries(bo, 3), ctx))
}
func uploadAsset(ctx context.Context, httpClient httpDoer, uploadURL string, asset AssetForUpload) (*ReleaseAsset, error) {
u, err := url.Parse(uploadURL)
if err != nil {
return nil, err
}
params := u.Query()
params.Set("name", asset.Name)
params.Set("label", asset.Label)
u.RawQuery = params.Encode()
f, err := asset.Open()
if err != nil {
return nil, err
}
defer f.Close()
req, err := http.NewRequestWithContext(ctx, "POST", u.String(), f)
if err != nil {
return nil, err
}
req.ContentLength = asset.Size
req.Header.Set("Content-Type", asset.MIMEType)
req.GetBody = asset.Open
resp, err := httpClient.Do(req)
if err != nil {
return nil, errNetwork{err}
}
defer resp.Body.Close()
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return nil, api.HandleHTTPError(resp)
}
var newAsset ReleaseAsset
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(&newAsset); err != nil {
return nil, err
}
return &newAsset, nil
}
func deleteAsset(ctx context.Context, httpClient httpDoer, assetURL string) error {
req, err := http.NewRequestWithContext(ctx, "DELETE", assetURL, nil)
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return api.HandleHTTPError(resp)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/shared/attestation.go | pkg/cmd/release/shared/attestation.go | package shared
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/pkg/cmd/attestation/api"
"github.com/cli/cli/v2/pkg/cmd/attestation/artifact"
att_io "github.com/cli/cli/v2/pkg/cmd/attestation/io"
"github.com/cli/cli/v2/pkg/cmd/attestation/test/data"
"github.com/cli/cli/v2/pkg/cmd/attestation/verification"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/sigstore/sigstore-go/pkg/fulcio/certificate"
"github.com/sigstore/sigstore-go/pkg/verify"
v1 "github.com/in-toto/attestation/go/v1"
"google.golang.org/protobuf/encoding/protojson"
)
type Verifier interface {
// VerifyAttestation verifies the attestation for a given artifact
VerifyAttestation(art *artifact.DigestedArtifact, att *api.Attestation) (*verification.AttestationProcessingResult, error)
}
type AttestationVerifier struct {
AttClient api.Client
HttpClient *http.Client
IO *iostreams.IOStreams
TrustedRoot string
}
func (v *AttestationVerifier) VerifyAttestation(art *artifact.DigestedArtifact, att *api.Attestation) (*verification.AttestationProcessingResult, error) {
td, err := v.AttClient.GetTrustDomain()
if err != nil {
return nil, err
}
verifier, err := verification.NewLiveSigstoreVerifier(verification.SigstoreConfig{
HttpClient: v.HttpClient,
Logger: att_io.NewHandler(v.IO),
NoPublicGood: true,
TrustDomain: td,
TrustedRoot: v.TrustedRoot,
})
if err != nil {
return nil, err
}
policy := buildVerificationPolicy(*art, td)
sigstoreVerified, err := verifier.Verify([]*api.Attestation{att}, policy)
if err != nil {
return nil, err
}
return sigstoreVerified[0], nil
}
func FilterAttestationsByTag(attestations []*api.Attestation, tagName string) ([]*api.Attestation, error) {
var filtered []*api.Attestation
for _, att := range attestations {
statement := att.Bundle.Bundle.GetDsseEnvelope().Payload
var statementData v1.Statement
err := protojson.Unmarshal([]byte(statement), &statementData)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal statement: %w", err)
}
tagValue := statementData.Predicate.GetFields()["tag"].GetStringValue()
if tagValue == tagName {
filtered = append(filtered, att)
}
}
return filtered, nil
}
func FilterAttestationsByFileDigest(attestations []*api.Attestation, fileDigest string) ([]*api.Attestation, error) {
var filtered []*api.Attestation
for _, att := range attestations {
statement := att.Bundle.Bundle.GetDsseEnvelope().Payload
var statementData v1.Statement
err := protojson.Unmarshal([]byte(statement), &statementData)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal statement: %w", err)
}
subjects := statementData.Subject
for _, subject := range subjects {
digestMap := subject.GetDigest()
alg := "sha256"
digest := digestMap[alg]
if digest == fileDigest {
filtered = append(filtered, att)
}
}
}
return filtered, nil
}
// buildVerificationPolicy constructs a verification policy for GitHub releases
func buildVerificationPolicy(a artifact.DigestedArtifact, trustDomain string) verify.PolicyBuilder {
// If no trust domain is specified, default to "dotcom"
if trustDomain == "" {
trustDomain = "dotcom"
}
// SAN must match the GitHub releases domain. No issuer extension (match anything)
sanMatcher, _ := verify.NewSANMatcher("", fmt.Sprintf("^https://%s\\.releases\\.github\\.com$", trustDomain))
issuerMatcher, _ := verify.NewIssuerMatcher("", ".*")
certId, _ := verify.NewCertificateIdentity(sanMatcher, issuerMatcher, certificate.Extensions{})
artifactDigestPolicyOption, _ := verification.BuildDigestPolicyOption(a)
return verify.NewPolicy(artifactDigestPolicyOption, verify.WithCertificateIdentity(certId))
}
type MockVerifier struct {
mockResult *verification.AttestationProcessingResult
}
func NewMockVerifier(mockResult *verification.AttestationProcessingResult) *MockVerifier {
return &MockVerifier{mockResult: mockResult}
}
func (v *MockVerifier) VerifyAttestation(art *artifact.DigestedArtifact, att *api.Attestation) (*verification.AttestationProcessingResult, error) {
return &verification.AttestationProcessingResult{
Attestation: &api.Attestation{
Bundle: data.GitHubReleaseBundle(nil),
BundleURL: "https://example.com",
},
VerificationResult: nil,
}, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/download/download_test.go | pkg/cmd/release/download/download_test.go | package download
import (
"bytes"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func Test_NewCmdDownload(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want DownloadOptions
wantErr string
}{
{
name: "version argument",
args: "v1.2.3",
isTTY: true,
want: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string(nil),
Destination: ".",
Concurrency: 5,
},
},
{
name: "version and file pattern",
args: "v1.2.3 -p *.tgz",
isTTY: true,
want: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string{"*.tgz"},
Destination: ".",
Concurrency: 5,
},
},
{
name: "multiple file patterns",
args: "v1.2.3 -p 1 -p 2,3",
isTTY: true,
want: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string{"1", "2,3"},
Destination: ".",
Concurrency: 5,
},
},
{
name: "version and destination",
args: "v1.2.3 -D tmp/assets",
isTTY: true,
want: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string(nil),
Destination: "tmp/assets",
Concurrency: 5,
},
},
{
name: "download latest",
args: "-p *",
isTTY: true,
want: DownloadOptions{
TagName: "",
FilePatterns: []string{"*"},
Destination: ".",
Concurrency: 5,
},
},
{
name: "download archive with valid option",
args: "v1.2.3 -A zip",
isTTY: true,
want: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string(nil),
Destination: ".",
ArchiveType: "zip",
Concurrency: 5,
},
},
{
name: "download to output with valid option",
args: "v1.2.3 -A zip -O ./sample.zip",
isTTY: true,
want: DownloadOptions{
OutputFile: "./sample.zip",
TagName: "v1.2.3",
FilePatterns: []string(nil),
Destination: ".",
ArchiveType: "zip",
Concurrency: 5,
},
},
{
name: "no arguments",
args: "",
isTTY: true,
wantErr: "`--pattern` or `--archive` is required when downloading the latest release",
},
{
name: "simultaneous pattern and archive arguments",
args: "-p * -A zip",
isTTY: true,
wantErr: "specify only one of '--pattern' or '--archive'",
},
{
name: "invalid archive argument",
args: "v1.2.3 -A abc",
isTTY: true,
wantErr: "the value for `--archive` must be one of \"zip\" or \"tar.gz\"",
},
{
name: "simultaneous output and destination flags",
args: "v1.2.3 -O ./file.xyz -D ./destination",
isTTY: true,
wantErr: "specify only one of `--dir` or `--output`",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *DownloadOptions
cmd := NewCmdDownload(f, func(o *DownloadOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
assert.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want.TagName, opts.TagName)
assert.Equal(t, tt.want.FilePatterns, opts.FilePatterns)
assert.Equal(t, tt.want.Destination, opts.Destination)
assert.Equal(t, tt.want.Concurrency, opts.Concurrency)
assert.Equal(t, tt.want.OutputFile, opts.OutputFile)
})
}
}
func Test_downloadRun(t *testing.T) {
tests := []struct {
name string
isTTY bool
opts DownloadOptions
httpStubs func(*httpmock.Registry)
wantErr string
wantStdout string
wantStderr string
wantFiles []string
}{
{
name: "download all assets",
isTTY: true,
opts: DownloadOptions{
TagName: "v1.2.3",
Destination: ".",
Concurrency: 2,
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
reg.Register(httpmock.REST("GET", "assets/1234"), httpmock.StringResponse(`1234`))
reg.Register(httpmock.REST("GET", "assets/3456"), httpmock.StringResponse(`3456`))
reg.Register(httpmock.REST("GET", "assets/5678"), httpmock.StringResponse(`5678`))
},
wantStdout: ``,
wantStderr: ``,
wantFiles: []string{
"linux.tgz",
"windows-32bit.zip",
"windows-64bit.zip",
},
},
{
name: "download assets matching pattern into destination directory",
isTTY: true,
opts: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string{"windows-*.zip"},
Destination: "tmp/assets",
Concurrency: 2,
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
reg.Register(httpmock.REST("GET", "assets/1234"), httpmock.StringResponse(`1234`))
reg.Register(httpmock.REST("GET", "assets/3456"), httpmock.StringResponse(`3456`))
},
wantStdout: ``,
wantStderr: ``,
wantFiles: []string{
"tmp/assets/windows-32bit.zip",
"tmp/assets/windows-64bit.zip",
},
},
{
name: "no match for pattern",
isTTY: true,
opts: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string{"linux*.zip"},
Destination: ".",
Concurrency: 2,
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
},
wantStdout: ``,
wantStderr: ``,
wantErr: "no assets match the file pattern",
},
{
name: "download archive in zip format into destination directory",
isTTY: true,
opts: DownloadOptions{
TagName: "v1.2.3",
ArchiveType: "zip",
Destination: "tmp/packages",
Concurrency: 2,
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
reg.Register(
httpmock.REST(
"GET",
"repos/OWNER/REPO/zipball/v1.2.3",
),
httpmock.WithHeader(
httpmock.StringResponse("somedata"), "content-disposition", "attachment; filename=zipball.zip",
),
)
},
wantStdout: ``,
wantStderr: ``,
wantFiles: []string{
"tmp/packages/zipball.zip",
},
},
{
name: "download archive in `tar.gz` format into destination directory",
isTTY: true,
opts: DownloadOptions{
TagName: "v1.2.3",
ArchiveType: "tar.gz",
Destination: "tmp/packages",
Concurrency: 2,
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
reg.Register(
httpmock.REST(
"GET",
"repos/OWNER/REPO/tarball/v1.2.3",
),
httpmock.WithHeader(
httpmock.StringResponse("somedata"), "content-disposition", "attachment; filename=tarball.tgz",
),
)
},
wantStdout: ``,
wantStderr: ``,
wantFiles: []string{
"tmp/packages/tarball.tgz",
},
},
{
name: "download archive in `tar.gz` format into output option",
isTTY: true,
opts: DownloadOptions{
OutputFile: "./tmp/my-tarball.tgz",
TagName: "v1.2.3",
Destination: "",
Concurrency: 2,
ArchiveType: "tar.gz",
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
reg.Register(
httpmock.REST(
"GET",
"repos/OWNER/REPO/tarball/v1.2.3",
),
httpmock.WithHeader(
httpmock.StringResponse("somedata"), "content-disposition", "attachment; filename=tarball.tgz",
),
)
},
wantStdout: ``,
wantStderr: ``,
wantFiles: []string{
"tmp/my-tarball.tgz",
},
},
{
name: "download single asset from matching pattern into output option",
isTTY: true,
opts: DownloadOptions{
OutputFile: "./tmp/my-tarball.tgz",
TagName: "v1.2.3",
Destination: "",
Concurrency: 2,
FilePatterns: []string{"*windows-32bit.zip"},
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
reg.Register(httpmock.REST("GET", "assets/1234"), httpmock.StringResponse(`1234`))
},
wantStdout: ``,
wantStderr: ``,
wantFiles: []string{
"tmp/my-tarball.tgz",
},
},
{
name: "download single asset from matching pattern into output 'stdout´",
isTTY: true,
opts: DownloadOptions{
OutputFile: "-",
TagName: "v1.2.3",
Destination: "",
Concurrency: 2,
FilePatterns: []string{"*windows-32bit.zip"},
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
reg.Register(httpmock.REST("GET", "assets/1234"), httpmock.StringResponse(`1234`))
},
wantStdout: `1234`,
wantStderr: ``,
},
{
name: "draft release with null tarball_url and zipball_url",
isTTY: true,
opts: DownloadOptions{
TagName: "v1.2.3",
ArchiveType: "tar.gz",
Destination: "tmp/packages",
Concurrency: 2,
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"tag_name": "v1.2.3",
"name": "patch-36",
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": null,
"zipball_url": null,
"draft": true
}`)
},
wantStdout: ``,
wantStderr: ``,
wantErr: "release \"patch-36\" with tag \"v1.2.3\", does not have a \"tar.gz\" archive asset. Most likely, this is because it is a draft.",
},
{
name: "non-draft release with null tarball_url and zipball_url",
isTTY: true,
opts: DownloadOptions{
TagName: "v1.2.3",
ArchiveType: "tar.gz",
Destination: "tmp/packages",
Concurrency: 2,
},
httpStubs: func(reg *httpmock.Registry) {
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"tag_name": "v1.2.3",
"name": "patch-36",
"assets": [
{ "name": "windows-32bit.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "linux.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": null,
"zipball_url": null,
"draft": false
}`)
},
wantStdout: ``,
wantStderr: ``,
wantErr: "release \"patch-36\" with tag \"v1.2.3\", does not have a \"tar.gz\" archive asset.",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempDir := t.TempDir()
t.Chdir(tempDir)
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
fakeHTTP := &httpmock.Registry{}
defer fakeHTTP.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(fakeHTTP)
}
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: fakeHTTP}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
err := downloadRun(&tt.opts)
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
var expectedAcceptHeader = "application/octet-stream"
if len(tt.opts.ArchiveType) > 0 {
expectedAcceptHeader = "application/octet-stream, application/json"
}
for _, req := range fakeHTTP.Requests {
if req.Method != "GET" || req.URL.Path != "repos/OWNER/REPO/releases/tags/v1.2.3" {
// skip non-asset download requests
continue
}
assert.Equal(t, expectedAcceptHeader, req.Header.Get("Accept"), "for request %s", req.URL)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
downloadedFiles, err := listFiles(".")
assert.NoError(t, err)
assert.Equal(t, tt.wantFiles, downloadedFiles)
})
}
}
func Test_downloadRun_cloberAndSkip(t *testing.T) {
oldAssetContents := "older copy to be clobbered"
oldZipballContents := "older zipball to be clobbered"
// this should be shorter than oldAssetContents and oldZipballContents
newContents := "somedata"
tests := []struct {
name string
opts DownloadOptions
httpStubs func(*httpmock.Registry)
wantErr string
wantFileSize int64
wantArchiveSize int64
}{
{
name: "no clobber or skip",
opts: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string{"windows-64bit.zip"},
Destination: "tmp/packages",
Concurrency: 2,
},
wantErr: "already exists (use `--clobber` to overwrite file or `--skip-existing` to skip file)",
wantFileSize: int64(len(oldAssetContents)),
wantArchiveSize: int64(len(oldZipballContents)),
},
{
name: "clobber",
opts: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string{"windows-64bit.zip"},
Destination: "tmp/packages",
Concurrency: 2,
OverwriteExisting: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "assets/3456"), httpmock.StringResponse(newContents))
},
wantFileSize: int64(len(newContents)),
wantArchiveSize: int64(len(oldZipballContents)),
},
{
name: "clobber archive",
opts: DownloadOptions{
TagName: "v1.2.3",
ArchiveType: "zip",
Destination: "tmp/packages",
Concurrency: 2,
OverwriteExisting: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/zipball/v1.2.3"),
httpmock.WithHeader(
httpmock.StringResponse(newContents), "content-disposition", "attachment; filename=zipball.zip",
),
)
},
wantFileSize: int64(len(oldAssetContents)),
wantArchiveSize: int64(len(newContents)),
},
{
name: "skip",
opts: DownloadOptions{
TagName: "v1.2.3",
FilePatterns: []string{"windows-64bit.zip"},
Destination: "tmp/packages",
Concurrency: 2,
SkipExisting: true,
},
wantFileSize: int64(len(oldAssetContents)),
wantArchiveSize: int64(len(oldZipballContents)),
},
{
name: "skip archive",
opts: DownloadOptions{
TagName: "v1.2.3",
ArchiveType: "zip",
Destination: "tmp/packages",
Concurrency: 2,
SkipExisting: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/zipball/v1.2.3"),
httpmock.WithHeader(
httpmock.StringResponse(newContents), "content-disposition", "attachment; filename=zipball.zip",
),
)
},
wantFileSize: int64(len(oldAssetContents)),
wantArchiveSize: int64(len(oldZipballContents)),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempDir := t.TempDir()
dest := filepath.Join(tempDir, tt.opts.Destination)
err := os.MkdirAll(dest, 0755)
assert.NoError(t, err)
file := filepath.Join(dest, "windows-64bit.zip")
archive := filepath.Join(dest, "zipball.zip")
f1, err := os.Create(file)
assert.NoError(t, err)
_, err = f1.WriteString(oldAssetContents)
assert.NoError(t, err)
f1.Close()
f2, err := os.Create(archive)
assert.NoError(t, err)
_, err = f2.WriteString(oldZipballContents)
assert.NoError(t, err)
f2.Close()
tt.opts.Destination = dest
ios, _, _, _ := iostreams.Test()
tt.opts.IO = ios
reg := &httpmock.Registry{}
defer reg.Verify(t)
shared.StubFetchRelease(t, reg, "OWNER", "REPO", "v1.2.3", `{
"assets": [
{ "name": "windows-64bit.zip", "size": 34,
"url": "https://api.github.com/assets/3456" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
err = downloadRun(&tt.opts)
if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
} else {
assert.NoError(t, err)
}
fs, err := os.Stat(file)
assert.NoError(t, err)
as, err := os.Stat(archive)
assert.NoError(t, err)
assert.Equal(t, tt.wantFileSize, fs.Size())
assert.Equal(t, tt.wantArchiveSize, as.Size())
})
}
}
func Test_downloadRun_windowsReservedFilename(t *testing.T) {
if runtime.GOOS != "windows" {
t.SkipNow()
}
tagName := "v1.2.3"
ios, _, _, _ := iostreams.Test()
reg := &httpmock.Registry{}
defer reg.Verify(t)
shared.StubFetchRelease(t, reg, "OWNER", "REPO", tagName, `{
"assets": [
{ "name": "valid-asset.zip", "size": 12,
"url": "https://api.github.com/assets/1234" },
{ "name": "valid-asset-2.zip", "size": 34,
"url": "https://api.github.com/assets/3456" },
{ "name": "CON.tgz", "size": 56,
"url": "https://api.github.com/assets/5678" }
],
"tarball_url": "https://api.github.com/repos/OWNER/REPO/tarball/v1.2.3",
"zipball_url": "https://api.github.com/repos/OWNER/REPO/zipball/v1.2.3"
}`)
opts := &DownloadOptions{
IO: ios,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
},
TagName: tagName,
}
err := downloadRun(opts)
assert.EqualError(t, err, `unable to download release due to asset with reserved filename "CON.tgz"`)
}
func TestIsWindowsReservedFilename(t *testing.T) {
tests := []struct {
name string
filename string
want bool
}{
{
name: "non-reserved filename",
filename: "test",
want: false,
},
{
name: "non-reserved filename with file type extension",
filename: "test.tar.gz",
want: false,
},
{
name: "reserved filename",
filename: "NUL",
want: true,
},
{
name: "reserved filename with file type extension",
filename: "NUL.tar.gz",
want: true,
},
{
name: "reserved filename with mixed type case",
filename: "NuL",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, isWindowsReservedFilename(tt.filename))
})
}
}
func listFiles(dir string) ([]string, error) {
var files []string
err := filepath.Walk(dir, func(p string, f os.FileInfo, err error) error {
if !f.IsDir() {
rp, err := filepath.Rel(dir, p)
if err != nil {
return err
}
files = append(files, filepath.ToSlash(rp))
}
return err
})
return files, err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/release/download/download.go | pkg/cmd/release/download/download.go | package download
import (
"context"
"errors"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/release/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type DownloadOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
OverwriteExisting bool
SkipExisting bool
TagName string
FilePatterns []string
Destination string
OutputFile string
// maximum number of simultaneous downloads
Concurrency int
ArchiveType string
}
func NewCmdDownload(f *cmdutil.Factory, runF func(*DownloadOptions) error) *cobra.Command {
opts := &DownloadOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "download [<tag>]",
Short: "Download release assets",
Long: heredoc.Docf(`
Download assets from a GitHub release.
Without an explicit tag name argument, assets are downloaded from the
latest release in the project. In this case, %[1]s--pattern%[1]s or %[1]s--archive%[1]s
is required.
`, "`"),
Example: heredoc.Doc(`
# Download all assets from a specific release
$ gh release download v1.2.3
# Download only Debian packages for the latest release
$ gh release download --pattern '*.deb'
# Specify multiple file patterns
$ gh release download -p '*.deb' -p '*.rpm'
# Download the archive of the source code for a release
$ gh release download v1.2.3 --archive=zip
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if len(args) == 0 {
if len(opts.FilePatterns) == 0 && opts.ArchiveType == "" {
return cmdutil.FlagErrorf("`--pattern` or `--archive` is required when downloading the latest release")
}
} else {
opts.TagName = args[0]
}
if err := cmdutil.MutuallyExclusive("specify only one of `--clobber` or `--skip-existing`", opts.OverwriteExisting, opts.SkipExisting); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("specify only one of `--dir` or `--output`", opts.Destination != ".", opts.OutputFile != ""); err != nil {
return err
}
// check archive type option validity
if err := checkArchiveTypeOption(opts); err != nil {
return err
}
opts.Concurrency = 5
if runF != nil {
return runF(opts)
}
return downloadRun(opts)
},
}
cmd.Flags().StringVarP(&opts.OutputFile, "output", "O", "", "The `file` to write a single asset to (use \"-\" to write to standard output)")
cmd.Flags().StringVarP(&opts.Destination, "dir", "D", ".", "The `directory` to download files into")
cmd.Flags().StringArrayVarP(&opts.FilePatterns, "pattern", "p", nil, "Download only assets that match a glob pattern")
cmd.Flags().StringVarP(&opts.ArchiveType, "archive", "A", "", "Download the source code archive in the specified `format` (zip or tar.gz)")
cmd.Flags().BoolVar(&opts.OverwriteExisting, "clobber", false, "Overwrite existing files of the same name")
cmd.Flags().BoolVar(&opts.SkipExisting, "skip-existing", false, "Skip downloading when files of the same name exist")
return cmd
}
func checkArchiveTypeOption(opts *DownloadOptions) error {
if len(opts.ArchiveType) == 0 {
return nil
}
if err := cmdutil.MutuallyExclusive(
"specify only one of '--pattern' or '--archive'",
true, // ArchiveType len > 0
len(opts.FilePatterns) > 0,
); err != nil {
return err
}
if opts.ArchiveType != "zip" && opts.ArchiveType != "tar.gz" {
return cmdutil.FlagErrorf("the value for `--archive` must be one of \"zip\" or \"tar.gz\"")
}
return nil
}
func downloadRun(opts *DownloadOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
opts.IO.StartProgressIndicatorWithLabel("Finding assets to download")
defer opts.IO.StopProgressIndicator()
ctx := context.Background()
var release *shared.Release
if opts.TagName == "" {
release, err = shared.FetchLatestRelease(ctx, httpClient, baseRepo)
if err != nil {
return err
}
} else {
release, err = shared.FetchRelease(ctx, httpClient, baseRepo, opts.TagName)
if err != nil {
return err
}
}
var toDownload []shared.ReleaseAsset
isArchive := false
if opts.ArchiveType != "" {
var archiveURL string
if opts.ArchiveType == "tar.gz" {
archiveURL = release.TarballURL
} else {
archiveURL = release.ZipballURL
}
if archiveURL == "" {
errMessage := fmt.Sprintf(
"release %q with tag %q, does not have a %q archive asset.",
release.Name, release.TagName, opts.ArchiveType,
)
if release.IsDraft {
errMessage += " Most likely, this is because it is a draft."
}
return errors.New(errMessage)
}
// create pseudo-Asset with no name and pointing to ZipBallURL or TarBallURL
toDownload = append(toDownload, shared.ReleaseAsset{APIURL: archiveURL})
isArchive = true
} else {
for _, a := range release.Assets {
if len(opts.FilePatterns) > 0 && !matchAny(opts.FilePatterns, a.Name) {
continue
}
// Note that if we need to start checking for reserved filenames on
// more operating systems we should move to using a build constraints
// pattern rather than checking the operating system at runtime.
if runtime.GOOS == "windows" && isWindowsReservedFilename(a.Name) {
return fmt.Errorf("unable to download release due to asset with reserved filename %q", a.Name)
}
toDownload = append(toDownload, a)
}
}
if len(toDownload) == 0 {
if len(release.Assets) > 0 {
return errors.New("no assets match the file pattern")
}
return errors.New("no assets to download")
}
if len(toDownload) > 1 && opts.OutputFile != "" {
return fmt.Errorf("unable to write more than one asset with `--output`, got %d assets", len(toDownload))
}
dest := destinationWriter{
file: opts.OutputFile,
dir: opts.Destination,
skipExisting: opts.SkipExisting,
overwrite: opts.OverwriteExisting,
stdout: opts.IO.Out,
}
return downloadAssets(&dest, httpClient, toDownload, opts.Concurrency, isArchive, opts.IO)
}
func matchAny(patterns []string, name string) bool {
for _, p := range patterns {
if isMatch, err := filepath.Match(p, name); err == nil && isMatch {
return true
}
}
return false
}
func downloadAssets(dest *destinationWriter, httpClient *http.Client, toDownload []shared.ReleaseAsset, numWorkers int, isArchive bool, io *iostreams.IOStreams) error {
if numWorkers == 0 {
return errors.New("the number of concurrent workers needs to be greater than 0")
}
jobs := make(chan shared.ReleaseAsset, len(toDownload))
results := make(chan error, len(toDownload))
if len(toDownload) < numWorkers {
numWorkers = len(toDownload)
}
for w := 1; w <= numWorkers; w++ {
go func() {
for a := range jobs {
io.StartProgressIndicatorWithLabel(fmt.Sprintf("Downloading %s", a.Name))
results <- downloadAsset(dest, httpClient, a.APIURL, a.Name, isArchive)
}
}()
}
for _, a := range toDownload {
jobs <- a
}
close(jobs)
var downloadError error
for i := 0; i < len(toDownload); i++ {
if err := <-results; err != nil && !errors.Is(err, errSkipped) {
downloadError = err
}
}
io.StopProgressIndicator()
return downloadError
}
func downloadAsset(dest *destinationWriter, httpClient *http.Client, assetURL, fileName string, isArchive bool) error {
if err := dest.Check(fileName); err != nil {
return err
}
req, err := http.NewRequest("GET", assetURL, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/octet-stream")
if isArchive {
// adding application/json to Accept header due to a bug in the zipball/tarball API endpoint that makes it mandatory
req.Header.Set("Accept", "application/octet-stream, application/json")
// override HTTP redirect logic to avoid "legacy" Codeload resources
oldClient := *httpClient
httpClient = &oldClient
httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) == 1 {
req.URL.Path = removeLegacyFromCodeloadPath(req.URL.Path)
}
return nil
}
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
if len(fileName) == 0 {
contentDisposition := resp.Header.Get("Content-Disposition")
_, params, err := mime.ParseMediaType(contentDisposition)
if err != nil {
return fmt.Errorf("unable to parse file name of archive: %w", err)
}
if serverFileName, ok := params["filename"]; ok {
fileName = filepath.Base(serverFileName)
} else {
return errors.New("unable to determine file name of archive")
}
}
return dest.Copy(fileName, resp.Body)
}
var codeloadLegacyRE = regexp.MustCompile(`^(/[^/]+/[^/]+/)legacy\.`)
// removeLegacyFromCodeloadPath converts URLs for "legacy" Codeload archives into ones that match the format
// when you choose to download "Source code (zip/tar.gz)" from a tagged release on the web. The legacy URLs
// look like this:
//
// https://codeload.github.com/OWNER/REPO/legacy.zip/refs/tags/TAGNAME
//
// Removing the "legacy." part results in a valid Codeload URL for our desired archive format.
func removeLegacyFromCodeloadPath(p string) string {
return codeloadLegacyRE.ReplaceAllString(p, "$1")
}
var errSkipped = errors.New("skipped")
// destinationWriter handles writing content into destination files
type destinationWriter struct {
file string
dir string
skipExisting bool
overwrite bool
stdout io.Writer
}
func (w destinationWriter) makePath(name string) string {
if w.file == "" {
return filepath.Join(w.dir, name)
}
return w.file
}
// Check returns an error if a file already exists at destination
func (w destinationWriter) Check(name string) error {
if name == "" {
// skip check as file name will only be known after the API request
return nil
}
fp := w.makePath(name)
if fp == "-" {
// writing to stdout should always proceed
return nil
}
return w.check(fp)
}
func (w destinationWriter) check(fp string) error {
if _, err := os.Stat(fp); err == nil {
if w.skipExisting {
return errSkipped
}
if !w.overwrite {
return fmt.Errorf(
"%s already exists (use `--clobber` to overwrite file or `--skip-existing` to skip file)",
fp,
)
}
}
return nil
}
// Copy writes the data from r into a file specified by name.
func (w destinationWriter) Copy(name string, r io.Reader) (copyErr error) {
fp := w.makePath(name)
if fp == "-" {
_, copyErr = io.Copy(w.stdout, r)
return
}
if copyErr = w.check(fp); copyErr != nil {
return
}
if dir := filepath.Dir(fp); dir != "." {
if copyErr = os.MkdirAll(dir, 0755); copyErr != nil {
return
}
}
var f *os.File
if f, copyErr = os.OpenFile(fp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); copyErr != nil {
return
}
defer func() {
if err := f.Close(); copyErr == nil && err != nil {
copyErr = err
}
}()
_, copyErr = io.Copy(f, r)
return
}
func isWindowsReservedFilename(filename string) bool {
// Windows terminals should prevent the creation of these files
// but that behavior is not enforced across terminals. Prevent
// the user from downloading files with these reserved names as
// they represent an exploit vector for bad actors.
// Reserved filenames defined at:
// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#win32-file-namespaces
reservedFilenames := []string{"CON", "PRN", "AUX", "NUL", "COM0",
"COM1", "COM2", "COM3", "COM4", "COM5",
"COM6", "COM7", "COM8", "COM9", "COM¹",
"COM²", "COM³", "LPT0", "LPT1", "LPT2",
"LPT3", "LPT4", "LPT5", "LPT6", "LPT7",
"LPT8", "LPT9", "LPT¹", "LPT²", "LPT³"}
// Normalize type case and remove file type extension from filename.
filename = strings.ToUpper(strings.Split(filename, ".")[0])
return slices.Contains(reservedFilenames, filename)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/accessibility/accessibility.go | pkg/cmd/accessibility/accessibility.go | package accessibility
import (
"fmt"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
const (
webURL = "https://accessibility.github.com/conformance/cli/"
)
type AccessibilityOptions struct {
IO *iostreams.IOStreams
Browser browser.Browser
Web bool
}
func NewCmdAccessibility(f *cmdutil.Factory) *cobra.Command {
opts := AccessibilityOptions{
IO: f.IOStreams,
Browser: f.Browser,
}
cmd := &cobra.Command{
Use: "accessibility",
Aliases: []string{"a11y"},
Short: "Learn about GitHub CLI's accessibility experiences",
Long: longDescription(opts.IO),
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
if opts.Web {
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(webURL))
}
return opts.Browser.Browse(webURL)
}
return cmd.Help()
},
Example: heredoc.Doc(`
# Open the GitHub Accessibility site in your browser
$ gh accessibility --web
# Display color using customizable, 4-bit accessible colors
$ gh config set accessible_colors enabled
# Use input prompts without redrawing the screen
$ gh config set accessible_prompter enabled
# Disable motion-based spinners for progress indicators in favor of text
$ gh config set spinner disabled
`),
}
cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open the GitHub Accessibility site in your browser")
cmdutil.DisableAuthCheck(cmd)
return cmd
}
func longDescription(io *iostreams.IOStreams) string {
cs := io.ColorScheme()
title := cs.Bold("Learn about GitHub CLI's accessibility experiences")
color := cs.Bold("Customizable and contrasting colors")
prompter := cs.Bold("Non-interactive user input prompting")
spinner := cs.Bold("Text-based spinners")
feedback := cs.Bold("Join the conversation")
return heredoc.Docf(`
%[2]s
As the home for all developers, we want every developer to feel welcome in our
community and be empowered to contribute to the future of global software
development with everything GitHub has to offer including the GitHub CLI.
%[3]s
Text interfaces often use color for various purposes, but insufficient contrast
or customizability can leave some users unable to benefit.
For a more accessible experience, the GitHub CLI can use color palettes
based on terminal background appearance and limit colors to 4-bit ANSI color
palettes, which users can customize within terminal preferences.
With this new experience, the GitHub CLI provides multiple options to address
color usage:
1. The GitHub CLI will use 4-bit color palette for increased color contrast based
on dark and light backgrounds including rendering Markdown based on the
GitHub Primer design system.
To enable this experience, use one of the following methods:
- Run %[1]sgh config set accessible_colors enabled%[1]s
- Set %[1]sGH_ACCESSIBLE_COLORS=enabled%[1]s environment variable
2. The GitHub CLI will display issue and pull request labels' custom RGB colors
in terminals with true color support.
To enable this experience, use one of the following methods:
- Run %[1]sgh config set color_labels enabled%[1]s
- Set %[1]sGH_COLOR_LABELS=enabled%[1]s environment variable
%[4]s
Interactive text user interfaces manipulate the terminal cursor to redraw parts
of the screen, which can be difficult for speech synthesizers or braille displays
to accurately detect and read.
For a more accessible experience, the GitHub CLI can provide a similar experience using
non-interactive prompts for user input.
To enable this experience, use one of the following methods:
- Run %[1]sgh config set accessible_prompter enabled%[1]s
- Set %[1]sGH_ACCESSIBLE_PROMPTER=enabled%[1]s environment variable
%[5]s
Motion-based spinners communicate in-progress activity by manipulating the
terminal cursor to create a spinning effect, which may cause discomfort to users
with motion sensitivity or miscommunicate information to speech synthesizers.
For a more accessible experience, this interactivity can be disabled in favor
of text-based progress indicators.
To enable this experience, use one of the following methods:
- Run %[1]sgh config set spinner disabled%[1]s
- Set %[1]sGH_SPINNER_DISABLED=yes%[1]s environment variable
%[6]s
We invite you to join us in improving GitHub CLI accessibility by sharing your
feedback and ideas through GitHub Accessibility feedback channels:
%[7]s
`, "`", title, color, prompter, spinner, feedback, webURL)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/git.go | pkg/cmd/extension/git.go | package extension
import (
"context"
"github.com/cli/cli/v2/git"
)
type gitClient interface {
CheckoutBranch(branch string) error
Clone(cloneURL string, args []string) (string, error)
CommandOutput(args []string) ([]byte, error)
Config(name string) (string, error)
Fetch(remote string, refspec string) error
ForRepo(repoDir string) gitClient
Pull(remote, branch string) error
Remotes() (git.RemoteSet, error)
}
type gitExecuter struct {
client *git.Client
}
func (g *gitExecuter) CheckoutBranch(branch string) error {
return g.client.CheckoutBranch(context.Background(), branch)
}
func (g *gitExecuter) Clone(cloneURL string, cloneArgs []string) (string, error) {
return g.client.Clone(context.Background(), cloneURL, cloneArgs)
}
func (g *gitExecuter) CommandOutput(args []string) ([]byte, error) {
cmd, err := g.client.Command(context.Background(), args...)
if err != nil {
return nil, err
}
return cmd.Output()
}
func (g *gitExecuter) Config(name string) (string, error) {
return g.client.Config(context.Background(), name)
}
func (g *gitExecuter) Fetch(remote string, refspec string) error {
return g.client.Fetch(context.Background(), remote, refspec)
}
func (g *gitExecuter) ForRepo(repoDir string) gitClient {
gc := g.client.Copy()
gc.RepoDir = repoDir
return &gitExecuter{client: gc}
}
func (g *gitExecuter) Pull(remote, branch string) error {
return g.client.Pull(context.Background(), remote, branch)
}
func (g *gitExecuter) Remotes() (git.RemoteSet, error) {
return g.client.Remotes(context.Background())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/manager_test.go | pkg/cmd/extension/manager_test.go | package extension
import (
"bytes"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)
func TestHelperProcess(t *testing.T) {
if os.Getenv("GH_WANT_HELPER_PROCESS") != "1" {
return
}
if err := func(args []string) error {
fmt.Fprintf(os.Stdout, "%v\n", args)
return nil
}(os.Args[3:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Exit(0)
}
func newTestManager(dataDir, updateDir string, client *http.Client, gitClient gitClient, ios *iostreams.IOStreams) *Manager {
return &Manager{
dataDir: func() string { return dataDir },
updateDir: func() string { return updateDir },
lookPath: func(exe string) (string, error) { return exe, nil },
findSh: func() (string, error) { return "sh", nil },
newCommand: func(exe string, args ...string) *exec.Cmd {
args = append([]string{os.Args[0], "-test.run=TestHelperProcess", "--", exe}, args...)
cmd := exec.Command(args[0], args[1:]...)
if ios != nil {
cmd.Stdout = ios.Out
cmd.Stderr = ios.ErrOut
}
cmd.Env = []string{"GH_WANT_HELPER_PROCESS=1"}
return cmd
},
config: config.NewBlankConfig(),
io: ios,
client: client,
gitClient: gitClient,
platform: func() (string, string) {
return "windows-amd64", ".exe"
},
}
}
func TestManager_List(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-hello", "gh-hello")))
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-two", "gh-two")))
assert.NoError(t, stubBinaryExtension(
filepath.Join(dataDir, "extensions", "gh-bin-ext"),
binManifest{
Owner: "owner",
Name: "gh-bin-ext",
Host: "example.com",
Tag: "v1.0.1",
}))
dirOne := filepath.Join(dataDir, "extensions", "gh-hello")
dirTwo := filepath.Join(dataDir, "extensions", "gh-two")
gc, gcOne, gcTwo := &mockGitClient{}, &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", dirOne).Return(gcOne).Once()
gc.On("ForRepo", dirTwo).Return(gcTwo).Once()
m := newTestManager(dataDir, updateDir, nil, gc, nil)
exts := m.List()
assert.Equal(t, 3, len(exts))
assert.Equal(t, "bin-ext", exts[0].Name())
assert.Equal(t, "hello", exts[1].Name())
assert.Equal(t, "two", exts[2].Name())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
gcTwo.AssertExpectations(t)
}
func TestManager_list_includeMetadata(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
assert.NoError(t, stubBinaryExtension(
filepath.Join(dataDir, "extensions", "gh-bin-ext"),
binManifest{
Owner: "owner",
Name: "gh-bin-ext",
Host: "example.com",
Tag: "v1.0.1",
}))
reg := httpmock.Registry{}
defer reg.Verify(t)
client := http.Client{Transport: ®}
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Tag: "v1.0.2",
Assets: []releaseAsset{
{
Name: "gh-bin-ext-windows-amd64",
APIURL: "https://example.com/release/cool2",
},
},
}))
m := newTestManager(dataDir, updateDir, &client, nil, nil)
exts, err := m.list(true)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
assert.Equal(t, "bin-ext", exts[0].Name())
assert.True(t, exts[0].UpdateAvailable())
assert.Equal(t, "https://example.com/owner/gh-bin-ext", exts[0].URL())
}
func TestManager_Dispatch(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
extDir := filepath.Join(dataDir, "extensions", "gh-hello")
extPath := filepath.Join(dataDir, "extensions", "gh-hello", "gh-hello")
assert.NoError(t, stubExtension(extPath))
gc, gcOne := &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", extDir).Return(gcOne).Once()
m := newTestManager(dataDir, updateDir, nil, gc, nil)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
found, err := m.Dispatch([]string{"hello", "one", "two"}, nil, stdout, stderr)
assert.NoError(t, err)
assert.True(t, found)
if runtime.GOOS == "windows" {
assert.Equal(t, fmt.Sprintf("[sh -c command \"$@\" -- %s one two]\n", extPath), stdout.String())
} else {
assert.Equal(t, fmt.Sprintf("[%s one two]\n", extPath), stdout.String())
}
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
}
func TestManager_Dispatch_binary(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
extPath := filepath.Join(dataDir, "extensions", "gh-hello")
exePath := filepath.Join(extPath, "gh-hello")
bm := binManifest{
Owner: "owner",
Name: "gh-hello",
Host: "github.com",
Tag: "v1.0.0",
}
assert.NoError(t, stubBinaryExtension(extPath, bm))
m := newTestManager(dataDir, updateDir, nil, nil, nil)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
found, err := m.Dispatch([]string{"hello", "one", "two"}, nil, stdout, stderr)
assert.NoError(t, err)
assert.True(t, found)
assert.Equal(t, fmt.Sprintf("[%s one two]\n", exePath), stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_Remove(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-hello", "gh-hello")))
assert.NoError(t, stubExtensionUpdate(filepath.Join(updateDir, "gh-hello")))
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-two", "gh-two")))
m := newTestManager(dataDir, updateDir, nil, nil, nil)
err := m.Remove("hello")
assert.NoError(t, err)
items, err := os.ReadDir(filepath.Join(dataDir, "extensions"))
assert.NoError(t, err)
assert.Equal(t, 1, len(items))
assert.Equal(t, "gh-two", items[0].Name())
assert.NoDirExistsf(t, filepath.Join(updateDir, "gh-hello"), "update directory should be removed")
}
func TestManager_Upgrade_NoExtensions(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, nil, nil, ios)
err := m.Upgrade("", false)
assert.EqualError(t, err, "no extensions installed")
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_Upgrade_NoMatchingExtension(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
extDir := filepath.Join(dataDir, "extensions", "gh-hello")
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-hello", "gh-hello")))
ios, _, stdout, stderr := iostreams.Test()
gc, gcOne := &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", extDir).Return(gcOne).Once()
m := newTestManager(dataDir, updateDir, nil, gc, ios)
err := m.Upgrade("invalid", false)
assert.EqualError(t, err, `no extension matched "invalid"`)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
}
func TestManager_UpgradeExtensions(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
dirOne := filepath.Join(dataDir, "extensions", "gh-hello")
dirTwo := filepath.Join(dataDir, "extensions", "gh-two")
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-hello", "gh-hello")))
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-two", "gh-two")))
assert.NoError(t, stubLocalExtension(dataDir, filepath.Join(dataDir, "extensions", "gh-local", "gh-local")))
ios, _, stdout, stderr := iostreams.Test()
gc, gcOne, gcTwo := &mockGitClient{}, &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", dirOne).Return(gcOne).Times(3)
gc.On("ForRepo", dirTwo).Return(gcTwo).Times(3)
gcOne.On("Remotes").Return(nil, nil).Once()
gcTwo.On("Remotes").Return(nil, nil).Once()
gcOne.On("Pull", "", "").Return(nil).Once()
gcTwo.On("Pull", "", "").Return(nil).Once()
m := newTestManager(dataDir, updateDir, nil, gc, ios)
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 3, len(exts))
for i := 0; i < 3; i++ {
exts[i].currentVersion = "old version"
exts[i].latestVersion = "new version"
}
err = m.upgradeExtensions(exts, false)
assert.NoError(t, err)
assert.Equal(t, heredoc.Doc(
`
[hello]: upgraded from old vers to new vers
[local]: local extensions can not be upgraded
[ two]: upgraded from old vers to new vers
`,
), stdout.String())
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
gcTwo.AssertExpectations(t)
}
func TestManager_UpgradeExtensions_DryRun(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
dirOne := filepath.Join(dataDir, "extensions", "gh-hello")
dirTwo := filepath.Join(dataDir, "extensions", "gh-two")
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-hello", "gh-hello")))
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-two", "gh-two")))
assert.NoError(t, stubLocalExtension(dataDir, filepath.Join(dataDir, "extensions", "gh-local", "gh-local")))
ios, _, stdout, stderr := iostreams.Test()
gc, gcOne, gcTwo := &mockGitClient{}, &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", dirOne).Return(gcOne).Twice()
gc.On("ForRepo", dirTwo).Return(gcTwo).Twice()
gcOne.On("Remotes").Return(nil, nil).Once()
gcTwo.On("Remotes").Return(nil, nil).Once()
m := newTestManager(dataDir, updateDir, nil, gc, ios)
m.EnableDryRunMode()
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 3, len(exts))
for i := 0; i < 3; i++ {
exts[i].currentVersion = fmt.Sprintf("%d", i)
exts[i].latestVersion = fmt.Sprintf("%d", i+1)
}
err = m.upgradeExtensions(exts, false)
assert.NoError(t, err)
assert.Equal(t, heredoc.Doc(
`
[hello]: would have upgraded from 0 to 1
[local]: local extensions can not be upgraded
[ two]: would have upgraded from 2 to 3
`,
), stdout.String())
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
gcTwo.AssertExpectations(t)
}
func TestManager_UpgradeExtension_LocalExtension(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
assert.NoError(t, stubLocalExtension(dataDir, filepath.Join(dataDir, "extensions", "gh-local", "gh-local")))
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, nil, nil, ios)
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
err = m.upgradeExtension(exts[0], false)
assert.EqualError(t, err, "local extensions can not be upgraded")
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_UpgradeExtension_LocalExtension_DryRun(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
assert.NoError(t, stubLocalExtension(dataDir, filepath.Join(dataDir, "extensions", "gh-local", "gh-local")))
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, nil, nil, ios)
m.EnableDryRunMode()
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
err = m.upgradeExtension(exts[0], false)
assert.EqualError(t, err, "local extensions can not be upgraded")
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_UpgradeExtension_GitExtension(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
extensionDir := filepath.Join(dataDir, "extensions", "gh-remote")
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-remote", "gh-remote")))
ios, _, stdout, stderr := iostreams.Test()
gc, gcOne := &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", extensionDir).Return(gcOne).Times(3)
gcOne.On("Remotes").Return(nil, nil).Once()
gcOne.On("Pull", "", "").Return(nil).Once()
m := newTestManager(dataDir, updateDir, nil, gc, ios)
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
ext.currentVersion = "old version"
ext.latestVersion = "new version"
err = m.upgradeExtension(ext, false)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
}
func TestManager_UpgradeExtension_GitExtension_DryRun(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
extDir := filepath.Join(dataDir, "extensions", "gh-remote")
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-remote", "gh-remote")))
ios, _, stdout, stderr := iostreams.Test()
gc, gcOne := &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", extDir).Return(gcOne).Twice()
gcOne.On("Remotes").Return(nil, nil).Once()
m := newTestManager(dataDir, updateDir, nil, gc, ios)
m.EnableDryRunMode()
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
ext.currentVersion = "old version"
ext.latestVersion = "new version"
err = m.upgradeExtension(ext, false)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
}
func TestManager_UpgradeExtension_GitExtension_Force(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
extensionDir := filepath.Join(dataDir, "extensions", "gh-remote")
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-remote", "gh-remote")))
ios, _, stdout, stderr := iostreams.Test()
gc, gcOne := &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", extensionDir).Return(gcOne).Times(3)
gcOne.On("Remotes").Return(nil, nil).Once()
gcOne.On("Fetch", "origin", "HEAD").Return(nil).Once()
gcOne.On("CommandOutput", []string{"reset", "--hard", "origin/HEAD"}).Return("", nil).Once()
m := newTestManager(dataDir, updateDir, nil, gc, ios)
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
ext.currentVersion = "old version"
ext.latestVersion = "new version"
err = m.upgradeExtension(ext, true)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
}
func TestManager_MigrateToBinaryExtension(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
assert.NoError(t, stubExtension(filepath.Join(dataDir, "extensions", "gh-remote", "gh-remote")))
ios, _, stdout, stderr := iostreams.Test()
reg := httpmock.Registry{}
defer reg.Verify(t)
client := http.Client{Transport: ®}
gc := &gitExecuter{client: &git.Client{}}
m := newTestManager(dataDir, updateDir, &client, gc, ios)
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
ext.currentVersion = "old version"
ext.latestVersion = "new version"
rs, restoreRun := run.Stub()
defer restoreRun(t)
rs.Register(`git -C.*?gh-remote remote -v`, 0, "origin git@github.com:owner/gh-remote.git (fetch)\norigin git@github.com:owner/gh-remote.git (push)")
rs.Register(`git -C.*?gh-remote config --get-regexp \^.*`, 0, "remote.origin.gh-resolve base")
reg.Register(
httpmock.REST("GET", "repos/owner/gh-remote/releases/latest"),
httpmock.JSONResponse(
release{
Tag: "v1.0.2",
Assets: []releaseAsset{
{
Name: "gh-remote-windows-amd64.exe",
APIURL: "/release/cool",
},
},
}))
reg.Register(
httpmock.REST("GET", "repos/owner/gh-remote/releases/latest"),
httpmock.JSONResponse(
release{
Tag: "v1.0.2",
Assets: []releaseAsset{
{
Name: "gh-remote-windows-amd64.exe",
APIURL: "/release/cool",
},
},
}))
reg.Register(
httpmock.REST("GET", "release/cool"),
httpmock.StringResponse("FAKE UPGRADED BINARY"))
err = m.upgradeExtension(ext, false)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
manifest, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-remote", manifestName))
assert.NoError(t, err)
var bm binManifest
err = yaml.Unmarshal(manifest, &bm)
assert.NoError(t, err)
assert.Equal(t, binManifest{
Name: "gh-remote",
Owner: "owner",
Host: "github.com",
Tag: "v1.0.2",
Path: filepath.Join(dataDir, "extensions/gh-remote/gh-remote.exe"),
}, bm)
fakeBin, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-remote/gh-remote.exe"))
assert.NoError(t, err)
assert.Equal(t, "FAKE UPGRADED BINARY", string(fakeBin))
}
func TestManager_UpgradeExtension_BinaryExtension(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
reg := httpmock.Registry{}
defer reg.Verify(t)
assert.NoError(t, stubBinaryExtension(
filepath.Join(dataDir, "extensions", "gh-bin-ext"),
binManifest{
Owner: "owner",
Name: "gh-bin-ext",
Host: "example.com",
Tag: "v1.0.1",
}))
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, &http.Client{Transport: ®}, nil, ios)
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Tag: "v1.0.2",
Assets: []releaseAsset{
{
Name: "gh-bin-ext-windows-amd64.exe",
APIURL: "https://example.com/release/cool2",
},
},
}))
reg.Register(
httpmock.REST("GET", "release/cool2"),
httpmock.StringResponse("FAKE UPGRADED BINARY"))
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
ext.latestVersion = "v1.0.2"
err = m.upgradeExtension(ext, false)
assert.NoError(t, err)
manifest, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-bin-ext", manifestName))
assert.NoError(t, err)
var bm binManifest
err = yaml.Unmarshal(manifest, &bm)
assert.NoError(t, err)
assert.Equal(t, binManifest{
Name: "gh-bin-ext",
Owner: "owner",
Host: "example.com",
Tag: "v1.0.2",
Path: filepath.Join(dataDir, "extensions/gh-bin-ext/gh-bin-ext.exe"),
}, bm)
fakeBin, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-bin-ext/gh-bin-ext.exe"))
assert.NoError(t, err)
assert.Equal(t, "FAKE UPGRADED BINARY", string(fakeBin))
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_UpgradeExtension_BinaryExtension_Pinned_Force(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
reg := httpmock.Registry{}
defer reg.Verify(t)
assert.NoError(t, stubBinaryExtension(
filepath.Join(dataDir, "extensions", "gh-bin-ext"),
binManifest{
Owner: "owner",
Name: "gh-bin-ext",
Host: "example.com",
Tag: "v1.0.1",
IsPinned: true,
}))
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, &http.Client{Transport: ®}, nil, ios)
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Tag: "v1.0.2",
Assets: []releaseAsset{
{
Name: "gh-bin-ext-windows-amd64.exe",
APIURL: "https://example.com/release/cool2",
},
},
}))
reg.Register(
httpmock.REST("GET", "release/cool2"),
httpmock.StringResponse("FAKE UPGRADED BINARY"))
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
ext.latestVersion = "v1.0.2"
err = m.upgradeExtension(ext, true)
assert.NoError(t, err)
manifest, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-bin-ext", manifestName))
assert.NoError(t, err)
var bm binManifest
err = yaml.Unmarshal(manifest, &bm)
assert.NoError(t, err)
assert.Equal(t, binManifest{
Name: "gh-bin-ext",
Owner: "owner",
Host: "example.com",
Tag: "v1.0.2",
Path: filepath.Join(dataDir, "extensions/gh-bin-ext/gh-bin-ext.exe"),
}, bm)
fakeBin, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-bin-ext/gh-bin-ext.exe"))
assert.NoError(t, err)
assert.Equal(t, "FAKE UPGRADED BINARY", string(fakeBin))
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_UpgradeExtension_BinaryExtension_DryRun(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
reg := httpmock.Registry{}
defer reg.Verify(t)
assert.NoError(t, stubBinaryExtension(
filepath.Join(dataDir, "extensions", "gh-bin-ext"),
binManifest{
Owner: "owner",
Name: "gh-bin-ext",
Host: "example.com",
Tag: "v1.0.1",
}))
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, &http.Client{Transport: ®}, nil, ios)
m.EnableDryRunMode()
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Tag: "v1.0.2",
Assets: []releaseAsset{
{
Name: "gh-bin-ext-windows-amd64.exe",
APIURL: "https://example.com/release/cool2",
},
},
}))
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
ext.latestVersion = "v1.0.2"
err = m.upgradeExtension(ext, false)
assert.NoError(t, err)
manifest, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-bin-ext", manifestName))
assert.NoError(t, err)
var bm binManifest
err = yaml.Unmarshal(manifest, &bm)
assert.NoError(t, err)
assert.Equal(t, binManifest{
Name: "gh-bin-ext",
Owner: "owner",
Host: "example.com",
Tag: "v1.0.1",
}, bm)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_UpgradeExtension_BinaryExtension_Pinned(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
assert.NoError(t, stubBinaryExtension(
filepath.Join(dataDir, "extensions", "gh-bin-ext"),
binManifest{
Owner: "owner",
Name: "gh-bin-ext",
Host: "example.com",
Tag: "v1.6.3",
IsPinned: true,
}))
ios, _, _, _ := iostreams.Test()
m := newTestManager(dataDir, updateDir, nil, nil, ios)
exts, err := m.list(false)
assert.Nil(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
err = m.upgradeExtension(ext, false)
assert.NotNil(t, err)
assert.Equal(t, err, pinnedExtensionUpgradeError)
}
func TestManager_UpgradeExtension_GitExtension_Pinned(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
extDir := filepath.Join(dataDir, "extensions", "gh-remote")
assert.NoError(t, stubPinnedExtension(filepath.Join(extDir, "gh-remote"), "abcd1234"))
ios, _, _, _ := iostreams.Test()
gc, gcOne := &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", extDir).Return(gcOne).Once()
m := newTestManager(dataDir, updateDir, nil, gc, ios)
exts, err := m.list(false)
assert.NoError(t, err)
assert.Equal(t, 1, len(exts))
ext := exts[0]
pinnedTrue := true
ext.isPinned = &pinnedTrue
ext.latestVersion = "new version"
err = m.upgradeExtension(ext, false)
assert.NotNil(t, err)
assert.Equal(t, err, pinnedExtensionUpgradeError)
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
}
func TestManager_Install_local(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, nil, nil, ios)
fakeExtensionName := "gh-local-ext"
// Create a temporary directory to simulate the local extension repo
extensionLocalPath := filepath.Join(dataDir, fakeExtensionName)
require.NoError(t, os.MkdirAll(extensionLocalPath, 0755))
// Create a fake executable in the local extension directory
fakeExtensionExecutablePath := filepath.Join(extensionLocalPath, fakeExtensionName)
require.NoError(t, stubExtension(fakeExtensionExecutablePath))
// Create a temporary directory to simulate the local extension update state
extensionUpdatePath := filepath.Join(updateDir, fakeExtensionName)
require.NoError(t, stubExtensionUpdate(extensionUpdatePath))
err := m.InstallLocal(extensionLocalPath)
require.NoError(t, err)
// This is the path to a file:
// on windows this is a file whose contents is a string describing the path to the local extension dir.
// on other platforms this file is a real symlink to the local extension dir.
extensionLinkFile := filepath.Join(dataDir, "extensions", fakeExtensionName)
if runtime.GOOS == "windows" {
// We don't create true symlinks on Windows, so check if we made a
// file with the correct contents to produce the symlink-like behavior
b, err := os.ReadFile(extensionLinkFile)
require.NoError(t, err)
assert.Equal(t, extensionLocalPath, string(b))
} else {
// Verify the created symlink points to the correct directory
linkTarget, err := os.Readlink(extensionLinkFile)
require.NoError(t, err)
assert.Equal(t, extensionLocalPath, linkTarget)
}
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
require.NoDirExistsf(t, extensionUpdatePath, "update directory should be removed")
}
func TestManager_Install_local_no_executable_found(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
ios, _, stdout, stderr := iostreams.Test()
m := newTestManager(dataDir, updateDir, nil, nil, ios)
fakeExtensionName := "gh-local-ext"
// Create a temporary directory to simulate the local extension repo
localDir := filepath.Join(dataDir, fakeExtensionName)
require.NoError(t, os.MkdirAll(localDir, 0755))
// Create a temporary directory to simulate the local extension update state
extensionUpdatePath := filepath.Join(updateDir, fakeExtensionName)
require.NoError(t, stubExtensionUpdate(extensionUpdatePath))
// Intentionally not creating an executable in the local extension repo
// to simulate an attempt to install a local extension without an executable
err := m.InstallLocal(localDir)
require.ErrorAs(t, err, new(*ErrExtensionExecutableNotFound))
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
require.NoDirExistsf(t, extensionUpdatePath, "update directory should be removed")
}
func TestManager_Install_git(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
reg := httpmock.Registry{}
defer reg.Verify(t)
client := http.Client{Transport: ®}
ios, _, stdout, stderr := iostreams.Test()
fakeExtensionName := "gh-some-ext"
extensionDir := filepath.Join(dataDir, "extensions", fakeExtensionName)
gc := &mockGitClient{}
gc.On("Clone", "https://github.com/owner/gh-some-ext.git", []string{extensionDir}).Return("", nil).Once()
// Create a temporary directory to simulate the local extension update state
extensionUpdatePath := filepath.Join(updateDir, fakeExtensionName)
require.NoError(t, stubExtensionUpdate(extensionUpdatePath))
m := newTestManager(dataDir, updateDir, &client, gc, ios)
reg.Register(
httpmock.REST("GET", "repos/owner/gh-some-ext/releases/latest"),
httpmock.JSONResponse(
release{
Assets: []releaseAsset{
{
Name: "not-a-binary",
APIURL: "https://example.com/release/cool",
},
},
}))
reg.Register(
httpmock.REST("GET", "repos/owner/gh-some-ext/contents/gh-some-ext"),
httpmock.StringResponse("script"))
repo := ghrepo.New("owner", fakeExtensionName)
err := m.Install(repo, "")
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
gc.AssertExpectations(t)
assert.NoDirExistsf(t, extensionUpdatePath, "update directory should be removed")
}
func TestManager_Install_git_pinned(t *testing.T) {
dataDir := t.TempDir()
updateDir := t.TempDir()
reg := httpmock.Registry{}
defer reg.Verify(t)
client := http.Client{Transport: ®}
ios, _, stdout, stderr := iostreams.Test()
extensionDir := filepath.Join(dataDir, "extensions", "gh-cool-ext")
gc, gcOne := &mockGitClient{}, &mockGitClient{}
gc.On("ForRepo", extensionDir).Return(gcOne).Once()
gc.On("Clone", "https://github.com/owner/gh-cool-ext.git", []string{extensionDir}).Return("", nil).Once()
gcOne.On("CheckoutBranch", "abcd1234").Return(nil).Once()
m := newTestManager(dataDir, updateDir, &client, gc, ios)
reg.Register(
httpmock.REST("GET", "repos/owner/gh-cool-ext/releases/latest"),
httpmock.JSONResponse(
release{
Assets: []releaseAsset{
{
Name: "not-a-binary",
APIURL: "https://example.com/release/cool",
},
},
}))
reg.Register(
httpmock.REST("GET", "repos/owner/gh-cool-ext/commits/some-ref"),
httpmock.StringResponse("abcd1234"))
reg.Register(
httpmock.REST("GET", "repos/owner/gh-cool-ext/contents/gh-cool-ext"),
httpmock.StringResponse("script"))
_ = os.MkdirAll(filepath.Join(m.installDir(), "gh-cool-ext"), 0700)
repo := ghrepo.New("owner", "gh-cool-ext")
err := m.Install(repo, "some-ref")
assert.NoError(t, err)
assert.Equal(t, "", stderr.String())
assert.Equal(t, "", stdout.String())
gc.AssertExpectations(t)
gcOne.AssertExpectations(t)
}
func TestManager_Install_binary_pinned(t *testing.T) {
repo := ghrepo.NewWithHost("owner", "gh-bin-ext", "example.com")
reg := httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Assets: []releaseAsset{
{
Name: "gh-bin-ext-windows-amd64.exe",
APIURL: "https://example.com/release/cool",
},
},
}))
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/tags/v1.6.3-pre"),
httpmock.JSONResponse(
release{
Tag: "v1.6.3-pre",
Assets: []releaseAsset{
{
Name: "gh-bin-ext-windows-amd64.exe",
APIURL: "https://example.com/release/cool",
},
},
}))
reg.Register(
httpmock.REST("GET", "release/cool"),
httpmock.StringResponse("FAKE BINARY"))
ios, _, stdout, stderr := iostreams.Test()
dataDir := t.TempDir()
updateDir := t.TempDir()
m := newTestManager(dataDir, updateDir, &http.Client{Transport: ®}, nil, ios)
err := m.Install(repo, "v1.6.3-pre")
assert.NoError(t, err)
manifest, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-bin-ext", manifestName))
assert.NoError(t, err)
var bm binManifest
err = yaml.Unmarshal(manifest, &bm)
assert.NoError(t, err)
assert.Equal(t, binManifest{
Name: "gh-bin-ext",
Owner: "owner",
Host: "example.com",
Tag: "v1.6.3-pre",
IsPinned: true,
Path: filepath.Join(dataDir, "extensions/gh-bin-ext/gh-bin-ext.exe"),
}, bm)
fakeBin, err := os.ReadFile(filepath.Join(dataDir, "extensions/gh-bin-ext/gh-bin-ext.exe"))
assert.NoError(t, err)
assert.Equal(t, "FAKE BINARY", string(fakeBin))
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_Install_binary_unsupported(t *testing.T) {
repo := ghrepo.NewWithHost("owner", "gh-bin-ext", "example.com")
reg := httpmock.Registry{}
defer reg.Verify(t)
client := http.Client{Transport: ®}
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Assets: []releaseAsset{
{
Name: "gh-bin-ext-linux-amd64",
APIURL: "https://example.com/release/cool",
},
},
}))
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Tag: "v1.0.1",
Assets: []releaseAsset{
{
Name: "gh-bin-ext-linux-amd64",
APIURL: "https://example.com/release/cool",
},
},
}))
ios, _, stdout, stderr := iostreams.Test()
dataDir := t.TempDir()
updateDir := t.TempDir()
m := newTestManager(dataDir, updateDir, &client, nil, ios)
err := m.Install(repo, "")
assert.EqualError(t, err, "gh-bin-ext unsupported for windows-amd64.\n\nTo request support for windows-amd64, open an issue on the extension's repo by running the following command:\n\n\t`gh issue create -R owner/gh-bin-ext --title \"Add support for the windows-amd64 architecture\" --body \"This extension does not support the windows-amd64 architecture. I tried to install it on a windows-amd64 machine, and it failed due to the lack of an available binary. Would you be able to update the extension's build and release process to include the relevant binary? For more details, see <https://docs.github.com/en/github-cli/github-cli/creating-github-cli-extensions>.\"`")
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
}
func TestManager_Install_rosetta_fallback_not_found(t *testing.T) {
repo := ghrepo.NewWithHost("owner", "gh-bin-ext", "example.com")
reg := httpmock.Registry{}
defer reg.Verify(t)
client := http.Client{Transport: ®}
reg.Register(
httpmock.REST("GET", "api/v3/repos/owner/gh-bin-ext/releases/latest"),
httpmock.JSONResponse(
release{
Assets: []releaseAsset{
{
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/mocks.go | pkg/cmd/extension/mocks.go | package extension
import (
"github.com/cli/cli/v2/git"
"github.com/stretchr/testify/mock"
)
type mockGitClient struct {
mock.Mock
}
func (g *mockGitClient) CheckoutBranch(branch string) error {
args := g.Called(branch)
return args.Error(0)
}
func (g *mockGitClient) Clone(cloneURL string, cloneArgs []string) (string, error) {
args := g.Called(cloneURL, cloneArgs)
return args.String(0), args.Error(1)
}
func (g *mockGitClient) CommandOutput(commandArgs []string) ([]byte, error) {
args := g.Called(commandArgs)
return []byte(args.String(0)), args.Error(1)
}
func (g *mockGitClient) Config(name string) (string, error) {
args := g.Called(name)
return args.String(0), args.Error(1)
}
func (g *mockGitClient) Fetch(remote string, refspec string) error {
args := g.Called(remote, refspec)
return args.Error(0)
}
func (g *mockGitClient) ForRepo(repoDir string) gitClient {
args := g.Called(repoDir)
if v, ok := args.Get(0).(*mockGitClient); ok {
return v
}
return nil
}
func (g *mockGitClient) Pull(remote, branch string) error {
args := g.Called(remote, branch)
return args.Error(0)
}
func (g *mockGitClient) Remotes() (git.RemoteSet, error) {
args := g.Called()
return nil, args.Error(1)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/command_test.go | pkg/cmd/extension/command_test.go | package extension
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdExtension(t *testing.T) {
tempDir := t.TempDir()
localExtensionTempDir := filepath.Join(tempDir, "gh-hello")
require.NoError(t, os.MkdirAll(localExtensionTempDir, 0755))
t.Chdir(localExtensionTempDir)
tests := []struct {
name string
args []string
managerStubs func(em *extensions.ExtensionManagerMock) func(*testing.T)
prompterStubs func(pm *prompter.PrompterMock)
httpStubs func(reg *httpmock.Registry)
browseStubs func(*browser.Stub) func(*testing.T)
isTTY bool
wantErr bool
errMsg string
wantStdout string
wantStderr string
}{
{
name: "search for extensions",
args: []string{"search"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/vilmibm/gh-screensaver"
},
},
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/github/gh-gei"
},
},
}
}
return func(t *testing.T) {
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
}
},
httpStubs: func(reg *httpmock.Registry) {
values := url.Values{
"page": []string{"1"},
"per_page": []string{"30"},
"q": []string{"topic:gh-extension"},
}
reg.Register(
httpmock.QueryMatcher("GET", "search/repositories", values),
httpmock.JSONResponse(searchResults(4)),
)
},
isTTY: true,
wantStdout: "Showing 4 of 4 extensions\n\n REPO DESCRIPTION\n✓ vilmibm/gh-screensaver terminal animations\n cli/gh-cool it's just cool ok\n samcoe/gh-triage helps with triage\n✓ github/gh-gei something something enterprise\n",
},
{
name: "search for extensions non-tty",
args: []string{"search"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/vilmibm/gh-screensaver"
},
},
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/github/gh-gei"
},
},
}
}
return func(t *testing.T) {
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
}
},
httpStubs: func(reg *httpmock.Registry) {
values := url.Values{
"page": []string{"1"},
"per_page": []string{"30"},
"q": []string{"topic:gh-extension"},
}
reg.Register(
httpmock.QueryMatcher("GET", "search/repositories", values),
httpmock.JSONResponse(searchResults(4)),
)
},
wantStdout: "installed\tvilmibm/gh-screensaver\tterminal animations\n\tcli/gh-cool\tit's just cool ok\n\tsamcoe/gh-triage\thelps with triage\ninstalled\tgithub/gh-gei\tsomething something enterprise\n",
},
{
name: "search for extensions with keywords",
args: []string{"search", "screen"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/vilmibm/gh-screensaver"
},
},
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/github/gh-gei"
},
},
}
}
return func(t *testing.T) {
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
}
},
httpStubs: func(reg *httpmock.Registry) {
values := url.Values{
"page": []string{"1"},
"per_page": []string{"30"},
"q": []string{"screen topic:gh-extension"},
}
results := searchResults(1)
reg.Register(
httpmock.QueryMatcher("GET", "search/repositories", values),
httpmock.JSONResponse(results),
)
},
wantStdout: "installed\tvilmibm/gh-screensaver\tterminal animations\n",
},
{
name: "search for extensions with parameter flags",
args: []string{"search", "--limit", "1", "--order", "asc", "--sort", "stars"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
return func(t *testing.T) {
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
}
},
httpStubs: func(reg *httpmock.Registry) {
values := url.Values{
"page": []string{"1"},
"order": []string{"asc"},
"sort": []string{"stars"},
"per_page": []string{"1"},
"q": []string{"topic:gh-extension"},
}
results := searchResults(1)
reg.Register(
httpmock.QueryMatcher("GET", "search/repositories", values),
httpmock.JSONResponse(results),
)
},
wantStdout: "\tvilmibm/gh-screensaver\tterminal animations\n",
},
{
name: "search for extensions with qualifier flags",
args: []string{"search", "--license", "GPLv3", "--owner", "jillvalentine"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
return func(t *testing.T) {
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
}
},
httpStubs: func(reg *httpmock.Registry) {
values := url.Values{
"page": []string{"1"},
"per_page": []string{"30"},
"q": []string{"license:GPLv3 topic:gh-extension user:jillvalentine"},
}
results := searchResults(1)
reg.Register(
httpmock.QueryMatcher("GET", "search/repositories", values),
httpmock.JSONResponse(results),
)
},
wantStdout: "\tvilmibm/gh-screensaver\tterminal animations\n",
},
{
name: "search for extensions with web mode",
args: []string{"search", "--web"},
browseStubs: func(b *browser.Stub) func(*testing.T) {
return func(t *testing.T) {
b.Verify(t, "https://github.com/search?q=topic%3Agh-extension&type=repositories")
}
},
},
{
name: "install an extension",
args: []string{"install", "owner/gh-some-ext"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
em.InstallFunc = func(_ ghrepo.Interface, _ string) error {
return nil
}
return func(t *testing.T) {
installCalls := em.InstallCalls()
assert.Equal(t, 1, len(installCalls))
assert.Equal(t, "gh-some-ext", installCalls[0].InterfaceMoqParam.RepoName())
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
}
},
},
{
name: "install an extension with same name as existing extension",
args: []string{"install", "owner/gh-existing-ext"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
e := &Extension{path: "owner2/gh-existing-ext", owner: "owner2"}
return []extensions.Extension{e}
}
return func(t *testing.T) {
calls := em.ListCalls()
assert.Equal(t, 1, len(calls))
}
},
wantErr: true,
errMsg: "there is already an installed extension that provides the \"existing-ext\" command",
},
{
name: "install an already installed extension",
args: []string{"install", "owner/gh-existing-ext"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
e := &Extension{path: "owner/gh-existing-ext", owner: "owner"}
return []extensions.Extension{e}
}
return func(t *testing.T) {
calls := em.ListCalls()
assert.Equal(t, 1, len(calls))
}
},
wantStderr: "! Extension owner/gh-existing-ext is already installed\n",
},
{
name: "install local extension",
args: []string{"install", "."},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
em.InstallLocalFunc = func(dir string) error {
return nil
}
return func(t *testing.T) {
calls := em.InstallLocalCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, localExtensionTempDir, normalizeDir(calls[0].Dir))
}
},
},
{
name: "installing local extension without executable with TTY shows warning",
args: []string{"install", "."},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.InstallLocalFunc = func(dir string) error {
return &ErrExtensionExecutableNotFound{
Dir: tempDir,
Name: "gh-test",
}
}
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
return nil
},
wantStderr: fmt.Sprintf("! an extension has been installed but there is no executable: executable file named \"%s\" in %s is required to run the extension after install. Perhaps you need to build it?\n", "gh-test", tempDir),
wantErr: false,
isTTY: true,
},
{
name: "install local extension without executable with no TTY shows no warning",
args: []string{"install", "."},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.InstallLocalFunc = func(dir string) error {
return &ErrExtensionExecutableNotFound{
Dir: tempDir,
Name: "gh-test",
}
}
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
return nil
},
wantStderr: "",
wantErr: false,
isTTY: false,
},
{
name: "error extension not found",
args: []string{"install", "owner/gh-some-ext"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
em.InstallFunc = func(_ ghrepo.Interface, _ string) error {
return repositoryNotFoundErr
}
return func(t *testing.T) {
installCalls := em.InstallCalls()
assert.Equal(t, 1, len(installCalls))
assert.Equal(t, "gh-some-ext", installCalls[0].InterfaceMoqParam.RepoName())
}
},
wantErr: true,
errMsg: "X Could not find extension 'owner/gh-some-ext' on host github.com",
},
{
name: "install local extension with pin",
args: []string{"install", ".", "--pin", "v1.0.0"},
wantErr: true,
errMsg: "local extensions cannot be pinned",
isTTY: true,
},
{
name: "upgrade argument error",
args: []string{"upgrade"},
wantErr: true,
errMsg: "specify an extension to upgrade or `--all`",
},
{
name: "upgrade --all with extension name error",
args: []string{"upgrade", "test", "--all"},
wantErr: true,
errMsg: "cannot use `--all` with extension name",
},
{
name: "upgrade an extension",
args: []string{"upgrade", "hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
{
name: "upgrade an extension dry run",
args: []string{"upgrade", "hello", "--dry-run"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.EnableDryRunModeFunc = func() {}
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
dryRunCalls := em.EnableDryRunModeCalls()
assert.Equal(t, 1, len(dryRunCalls))
upgradeCalls := em.UpgradeCalls()
assert.Equal(t, 1, len(upgradeCalls))
assert.Equal(t, "hello", upgradeCalls[0].Name)
assert.False(t, upgradeCalls[0].Force)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
{
name: "upgrade an extension notty",
args: []string{"upgrade", "hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: false,
},
{
name: "upgrade an up-to-date extension",
args: []string{"upgrade", "hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
// An already up to date extension returns the same response
// as an one that has been upgraded.
return nil
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
{
name: "upgrade extension error",
args: []string{"upgrade", "hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return errors.New("oh no")
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: false,
wantErr: true,
errMsg: "SilentError",
wantStdout: "",
wantStderr: "X Failed upgrading extension hello: oh no\n",
},
{
name: "upgrade an extension gh-prefix",
args: []string{"upgrade", "gh-hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
{
name: "upgrade an extension full name",
args: []string{"upgrade", "monalisa/gh-hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
{
name: "upgrade all",
args: []string{"upgrade", "--all"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "", calls[0].Name)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
{
name: "upgrade all dry run",
args: []string{"upgrade", "--all", "--dry-run"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.EnableDryRunModeFunc = func() {}
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
dryRunCalls := em.EnableDryRunModeCalls()
assert.Equal(t, 1, len(dryRunCalls))
upgradeCalls := em.UpgradeCalls()
assert.Equal(t, 1, len(upgradeCalls))
assert.Equal(t, "", upgradeCalls[0].Name)
assert.False(t, upgradeCalls[0].Force)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
{
name: "upgrade all none installed",
args: []string{"upgrade", "--all"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return noExtensionsInstalledError
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "", calls[0].Name)
}
},
isTTY: true,
wantErr: true,
errMsg: "no installed extensions found",
},
{
name: "upgrade all notty",
args: []string{"upgrade", "--all"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
calls := em.UpgradeCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "", calls[0].Name)
}
},
isTTY: false,
},
{
name: "remove extension tty",
args: []string{"remove", "hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.RemoveFunc = func(name string) error {
return nil
}
return func(t *testing.T) {
calls := em.RemoveCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: true,
wantStdout: "✓ Removed extension hello\n",
},
{
name: "remove extension nontty",
args: []string{"remove", "hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.RemoveFunc = func(name string) error {
return nil
}
return func(t *testing.T) {
calls := em.RemoveCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: false,
wantStdout: "",
},
{
name: "remove extension gh-prefix",
args: []string{"remove", "gh-hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.RemoveFunc = func(name string) error {
return nil
}
return func(t *testing.T) {
calls := em.RemoveCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: false,
wantStdout: "",
},
{
name: "remove extension full name",
args: []string{"remove", "monalisa/gh-hello"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.RemoveFunc = func(name string) error {
return nil
}
return func(t *testing.T) {
calls := em.RemoveCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "hello", calls[0].Name)
}
},
isTTY: false,
wantStdout: "",
},
{
name: "list extensions",
args: []string{"list"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
ex1 := &Extension{path: "cli/gh-test", url: "https://github.com/cli/gh-test", currentVersion: "1"}
ex2 := &Extension{path: "cli/gh-test2", url: "https://github.com/cli/gh-test2", currentVersion: "1"}
return []extensions.Extension{ex1, ex2}
}
return func(t *testing.T) {
calls := em.ListCalls()
assert.Equal(t, 1, len(calls))
}
},
wantStdout: "gh test\tcli/gh-test\t1\ngh test2\tcli/gh-test2\t1\n",
},
{
name: "create extension interactive",
args: []string{"create"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.CreateFunc = func(name string, tmplType extensions.ExtTemplateType) error {
return nil
}
return func(t *testing.T) {
calls := em.CreateCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "gh-test", calls[0].Name)
}
},
isTTY: true,
prompterStubs: func(pm *prompter.PrompterMock) {
pm.InputFunc = func(prompt, defVal string) (string, error) {
if prompt == "Extension name:" {
return "test", nil
}
return "", nil
}
pm.SelectFunc = func(prompt, defVal string, opts []string) (int, error) {
return prompter.IndexFor(opts, "Script (Bash, Ruby, Python, etc)")
}
},
wantStdout: heredoc.Doc(`
✓ Created directory gh-test
✓ Initialized git repository
✓ Made initial commit
✓ Set up extension scaffolding
gh-test is ready for development!
Next Steps
- run 'cd gh-test; gh extension install .; gh test' to see your new extension in action
- run 'gh repo create' to share your extension with others
For more information on writing extensions:
https://docs.github.com/github-cli/github-cli/creating-github-cli-extensions
`),
},
{
name: "create extension with arg, --precompiled=go",
args: []string{"create", "test", "--precompiled", "go"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.CreateFunc = func(name string, tmplType extensions.ExtTemplateType) error {
return nil
}
return func(t *testing.T) {
calls := em.CreateCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "gh-test", calls[0].Name)
}
},
isTTY: true,
wantStdout: heredoc.Doc(`
✓ Created directory gh-test
✓ Initialized git repository
✓ Made initial commit
✓ Set up extension scaffolding
✓ Downloaded Go dependencies
✓ Built gh-test binary
gh-test is ready for development!
Next Steps
- run 'cd gh-test; gh extension install .; gh test' to see your new extension in action
- run 'go build && gh test' to see changes in your code as you develop
- run 'gh repo create' to share your extension with others
For more information on writing extensions:
https://docs.github.com/github-cli/github-cli/creating-github-cli-extensions
`),
},
{
name: "create extension with arg, --precompiled=other",
args: []string{"create", "test", "--precompiled", "other"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.CreateFunc = func(name string, tmplType extensions.ExtTemplateType) error {
return nil
}
return func(t *testing.T) {
calls := em.CreateCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "gh-test", calls[0].Name)
}
},
isTTY: true,
wantStdout: heredoc.Doc(`
✓ Created directory gh-test
✓ Initialized git repository
✓ Made initial commit
✓ Set up extension scaffolding
gh-test is ready for development!
Next Steps
- run 'cd gh-test; gh extension install .' to install your extension locally
- fill in script/build.sh with your compilation script for automated builds
- compile a gh-test binary locally and run 'gh test' to see changes
- run 'gh repo create' to share your extension with others
For more information on writing extensions:
https://docs.github.com/github-cli/github-cli/creating-github-cli-extensions
`),
},
{
name: "create extension tty with argument",
args: []string{"create", "test"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.CreateFunc = func(name string, tmplType extensions.ExtTemplateType) error {
return nil
}
return func(t *testing.T) {
calls := em.CreateCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "gh-test", calls[0].Name)
}
},
isTTY: true,
wantStdout: heredoc.Doc(`
✓ Created directory gh-test
✓ Initialized git repository
✓ Made initial commit
✓ Set up extension scaffolding
gh-test is ready for development!
Next Steps
- run 'cd gh-test; gh extension install .; gh test' to see your new extension in action
- run 'gh repo create' to share your extension with others
For more information on writing extensions:
https://docs.github.com/github-cli/github-cli/creating-github-cli-extensions
`),
},
{
name: "create extension tty with argument commit fails",
args: []string{"create", "test"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.CreateFunc = func(name string, tmplType extensions.ExtTemplateType) error {
return ErrInitialCommitFailed
}
return func(t *testing.T) {
calls := em.CreateCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "gh-test", calls[0].Name)
}
},
isTTY: true,
wantStdout: heredoc.Doc(`
✓ Created directory gh-test
✓ Initialized git repository
X Made initial commit
✓ Set up extension scaffolding
gh-test is ready for development!
Next Steps
- run 'cd gh-test; gh extension install .; gh test' to see your new extension in action
- run 'gh repo create' to share your extension with others
For more information on writing extensions:
https://docs.github.com/github-cli/github-cli/creating-github-cli-extensions
`),
},
{
name: "create extension notty",
args: []string{"create", "gh-test"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.CreateFunc = func(name string, tmplType extensions.ExtTemplateType) error {
return nil
}
return func(t *testing.T) {
calls := em.CreateCalls()
assert.Equal(t, 1, len(calls))
assert.Equal(t, "gh-test", calls[0].Name)
}
},
isTTY: false,
wantStdout: "",
},
{
name: "exec extension missing",
args: []string{"exec", "invalid"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.DispatchFunc = func(args []string, stdin io.Reader, stdout, stderr io.Writer) (bool, error) {
return false, nil
}
return func(t *testing.T) {
calls := em.DispatchCalls()
assert.Equal(t, 1, len(calls))
assert.EqualValues(t, []string{"invalid"}, calls[0].Args)
}
},
wantErr: true,
errMsg: `extension "invalid" not found`,
},
{
name: "exec extension with arguments",
args: []string{"exec", "test", "arg1", "arg2", "--flag1"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.DispatchFunc = func(args []string, stdin io.Reader, stdout, stderr io.Writer) (bool, error) {
fmt.Fprintf(stdout, "test output")
return true, nil
}
return func(t *testing.T) {
calls := em.DispatchCalls()
assert.Equal(t, 1, len(calls))
assert.EqualValues(t, []string{"test", "arg1", "arg2", "--flag1"}, calls[0].Args)
}
},
wantStdout: "test output",
},
{
name: "browse",
args: []string{"browse"},
wantErr: true,
errMsg: "this command runs an interactive UI and needs to be run in a terminal",
},
{
name: "force install when absent",
args: []string{"install", "owner/gh-hello", "--force"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{}
}
em.InstallFunc = func(_ ghrepo.Interface, _ string) error {
return nil
}
return func(t *testing.T) {
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
installCalls := em.InstallCalls()
assert.Equal(t, 1, len(installCalls))
assert.Equal(t, "gh-hello", installCalls[0].InterfaceMoqParam.RepoName())
}
},
isTTY: true,
wantStdout: "✓ Installed extension owner/gh-hello\n",
},
{
name: "force install when present",
args: []string{"install", "owner/gh-hello", "--force"},
managerStubs: func(em *extensions.ExtensionManagerMock) func(*testing.T) {
em.ListFunc = func() []extensions.Extension {
return []extensions.Extension{
&Extension{path: "owner/gh-hello", owner: "owner"},
}
}
em.InstallFunc = func(_ ghrepo.Interface, _ string) error {
return nil
}
em.UpgradeFunc = func(name string, force bool) error {
return nil
}
return func(t *testing.T) {
listCalls := em.ListCalls()
assert.Equal(t, 1, len(listCalls))
installCalls := em.InstallCalls()
assert.Equal(t, 0, len(installCalls))
upgradeCalls := em.UpgradeCalls()
assert.Equal(t, 1, len(upgradeCalls))
assert.Equal(t, "hello", upgradeCalls[0].Name)
}
},
isTTY: true,
wantStdout: "✓ Successfully checked extension upgrades\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
var assertFunc func(*testing.T)
em := &extensions.ExtensionManagerMock{}
if tt.managerStubs != nil {
assertFunc = tt.managerStubs(em)
}
pm := &prompter.PrompterMock{}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
reg := httpmock.Registry{}
defer reg.Verify(t)
client := http.Client{Transport: ®}
if tt.httpStubs != nil {
tt.httpStubs(®)
}
var assertBrowserFunc func(*testing.T)
browseStub := &browser.Stub{}
if tt.browseStubs != nil {
assertBrowserFunc = tt.browseStubs(browseStub)
}
f := cmdutil.Factory{
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
IOStreams: ios,
ExtensionManager: em,
Prompter: pm,
Browser: browseStub,
HttpClient: func() (*http.Client, error) {
return &client, nil
},
}
cmd := NewCmdExtension(&f)
cmd.SetArgs(tt.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err := cmd.ExecuteC()
if tt.wantErr {
assert.EqualError(t, err, tt.errMsg)
} else {
assert.NoError(t, err)
}
if assertFunc != nil {
assertFunc(t)
}
if assertBrowserFunc != nil {
assertBrowserFunc(t)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
func normalizeDir(d string) string {
return strings.TrimPrefix(d, "/private")
}
func Test_checkValidExtension(t *testing.T) {
rootCmd := &cobra.Command{}
rootCmd.AddCommand(&cobra.Command{Use: "help"})
rootCmd.AddCommand(&cobra.Command{Use: "auth"})
m := &extensions.ExtensionManagerMock{
ListFunc: func() []extensions.Extension {
return []extensions.Extension{
&extensions.ExtensionMock{
OwnerFunc: func() string { return "monalisa" },
NameFunc: func() string { return "screensaver" },
},
&extensions.ExtensionMock{
OwnerFunc: func() string { return "monalisa" },
NameFunc: func() string { return "triage" },
},
}
},
}
type args struct {
rootCmd *cobra.Command
manager extensions.ExtensionManager
extName string
extOwner string
}
tests := []struct {
name string
args args
wantError string
}{
{
name: "valid extension",
args: args{
rootCmd: rootCmd,
manager: m,
extOwner: "monalisa",
extName: "gh-hello",
},
},
{
name: "invalid extension name",
args: args{
rootCmd: rootCmd,
manager: m,
extOwner: "monalisa",
extName: "gherkins",
},
wantError: "extension name must start with `gh-`",
},
{
name: "clashes with built-in command",
args: args{
rootCmd: rootCmd,
manager: m,
extOwner: "monalisa",
extName: "gh-auth",
},
wantError: "\"auth\" matches the name of a built-in command or alias",
},
{
name: "clashes with an installed extension",
args: args{
rootCmd: rootCmd,
manager: m,
extOwner: "cli",
extName: "gh-triage",
},
wantError: "there is already an installed extension that provides the \"triage\" command",
},
{
name: "clashes with same extension",
args: args{
rootCmd: rootCmd,
manager: m,
extOwner: "monalisa",
extName: "gh-triage",
},
wantError: "alreadyInstalledError",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := checkValidExtension(tt.args.rootCmd, tt.args.manager, tt.args.extName, tt.args.extOwner)
if tt.wantError == "" {
assert.NoError(t, err)
} else {
assert.EqualError(t, err, tt.wantError)
}
})
}
}
func Test_checkValidExtensionWithLocalExtension(t *testing.T) {
fakeRootCmd := &cobra.Command{}
fakeRootCmd.AddCommand(&cobra.Command{Use: "help"})
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/symlink_windows.go | pkg/cmd/extension/symlink_windows.go | package extension
import "os"
func makeSymlink(oldname, newname string) error {
// Create a regular file that contains the location of the directory where to find this extension. We
// avoid relying on symlinks because creating them on Windows requires administrator privileges.
f, err := os.OpenFile(newname, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(oldname)
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/extension_test.go | pkg/cmd/extension/extension_test.go | package extension
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUpdateAvailable_IsLocal(t *testing.T) {
e := &Extension{
kind: LocalKind,
}
assert.False(t, e.UpdateAvailable())
}
func TestUpdateAvailable_NoCurrentVersion(t *testing.T) {
e := &Extension{
kind: LocalKind,
}
assert.False(t, e.UpdateAvailable())
}
func TestUpdateAvailable_NoLatestVersion(t *testing.T) {
e := &Extension{
kind: BinaryKind,
currentVersion: "1.0.0",
}
assert.False(t, e.UpdateAvailable())
}
func TestUpdateAvailable_CurrentVersionIsLatestVersion(t *testing.T) {
e := &Extension{
kind: BinaryKind,
currentVersion: "1.0.0",
latestVersion: "1.0.0",
}
assert.False(t, e.UpdateAvailable())
}
func TestUpdateAvailable(t *testing.T) {
e := &Extension{
kind: BinaryKind,
currentVersion: "1.0.0",
latestVersion: "1.1.0",
}
assert.True(t, e.UpdateAvailable())
}
func TestOwnerLocalExtension(t *testing.T) {
tempDir := t.TempDir()
extPath := filepath.Join(tempDir, "extensions", "gh-local", "gh-local")
assert.NoError(t, stubLocalExtension(tempDir, extPath))
e := &Extension{
kind: LocalKind,
path: extPath,
}
assert.Equal(t, "", e.Owner())
}
func TestOwnerBinaryExtension(t *testing.T) {
tempDir := t.TempDir()
extName := "gh-bin-ext"
extDir := filepath.Join(tempDir, "extensions", extName)
extPath := filepath.Join(extDir, extName)
bm := binManifest{
Owner: "owner",
Name: "gh-bin-ext",
Host: "example.com",
Tag: "v1.0.1",
}
assert.NoError(t, stubBinaryExtension(extDir, bm))
e := &Extension{
kind: BinaryKind,
path: extPath,
}
assert.Equal(t, "owner", e.Owner())
}
func TestOwnerGitExtension(t *testing.T) {
gc := &mockGitClient{}
gc.On("Config", "remote.origin.url").Return("git@github.com:owner/repo.git", nil).Once()
e := &Extension{
kind: GitKind,
gitClient: gc,
}
assert.Equal(t, "owner", e.Owner())
}
func TestOwnerCached(t *testing.T) {
e := &Extension{
owner: "cli",
}
assert.Equal(t, "cli", e.Owner())
}
func TestIsPinnedBinaryExtensionUnpinned(t *testing.T) {
tempDir := t.TempDir()
extName := "gh-bin-ext"
extDir := filepath.Join(tempDir, "extensions", extName)
extPath := filepath.Join(extDir, extName)
bm := binManifest{
Name: "gh-bin-ext",
}
assert.NoError(t, stubBinaryExtension(extDir, bm))
e := &Extension{
kind: BinaryKind,
path: extPath,
}
assert.False(t, e.IsPinned())
}
func TestIsPinnedBinaryExtensionPinned(t *testing.T) {
tempDir := t.TempDir()
extName := "gh-bin-ext"
extDir := filepath.Join(tempDir, "extensions", extName)
extPath := filepath.Join(extDir, extName)
bm := binManifest{
Name: "gh-bin-ext",
IsPinned: true,
}
assert.NoError(t, stubBinaryExtension(extDir, bm))
e := &Extension{
kind: BinaryKind,
path: extPath,
}
assert.True(t, e.IsPinned())
}
func TestIsPinnedGitExtensionUnpinned(t *testing.T) {
tempDir := t.TempDir()
extPath := filepath.Join(tempDir, "extensions", "gh-local", "gh-local")
assert.NoError(t, stubExtension(extPath))
gc := &mockGitClient{}
gc.On("CommandOutput", []string{"rev-parse", "HEAD"}).Return("abcd1234", nil)
e := &Extension{
kind: GitKind,
gitClient: gc,
path: extPath,
}
assert.False(t, e.IsPinned())
gc.AssertExpectations(t)
}
func TestIsPinnedGitExtensionPinned(t *testing.T) {
tempDir := t.TempDir()
extPath := filepath.Join(tempDir, "extensions", "gh-local", "gh-local")
assert.NoError(t, stubPinnedExtension(extPath, "abcd1234"))
gc := &mockGitClient{}
gc.On("CommandOutput", []string{"rev-parse", "HEAD"}).Return("abcd1234", nil)
e := &Extension{
kind: GitKind,
gitClient: gc,
path: extPath,
}
assert.True(t, e.IsPinned())
gc.AssertExpectations(t)
}
func TestIsPinnedLocalExtension(t *testing.T) {
tempDir := t.TempDir()
extPath := filepath.Join(tempDir, "extensions", "gh-local", "gh-local")
assert.NoError(t, stubLocalExtension(tempDir, extPath))
e := &Extension{
kind: LocalKind,
path: extPath,
}
assert.False(t, e.IsPinned())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/symlink_other.go | pkg/cmd/extension/symlink_other.go | //go:build !windows
package extension
import "os"
func makeSymlink(oldname, newname string) error {
return os.Symlink(oldname, newname)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/http.go | pkg/cmd/extension/http.go | package extension
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
)
func repoExists(httpClient *http.Client, repo ghrepo.Interface) (bool, error) {
url := fmt.Sprintf("%srepos/%s/%s", ghinstance.RESTPrefix(repo.RepoHost()), repo.RepoOwner(), repo.RepoName())
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
resp, err := httpClient.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case 200:
return true, nil
case 404:
return false, nil
default:
return false, api.HandleHTTPError(resp)
}
}
func hasScript(httpClient *http.Client, repo ghrepo.Interface) (bool, error) {
path := fmt.Sprintf("repos/%s/%s/contents/%s",
repo.RepoOwner(), repo.RepoName(), repo.RepoName())
url := ghinstance.RESTPrefix(repo.RepoHost()) + path
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
resp, err := httpClient.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode == 404 {
return false, nil
}
if resp.StatusCode > 299 {
err = api.HandleHTTPError(resp)
return false, err
}
return true, nil
}
type releaseAsset struct {
Name string
APIURL string `json:"url"`
}
type release struct {
Tag string `json:"tag_name"`
Assets []releaseAsset
}
// downloadAsset downloads a single asset to the given file path.
func downloadAsset(httpClient *http.Client, asset releaseAsset, destPath string) (downloadErr error) {
var req *http.Request
if req, downloadErr = http.NewRequest("GET", asset.APIURL, nil); downloadErr != nil {
return
}
req.Header.Set("Accept", "application/octet-stream")
var resp *http.Response
if resp, downloadErr = httpClient.Do(req); downloadErr != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
downloadErr = api.HandleHTTPError(resp)
return
}
var f *os.File
if f, downloadErr = os.OpenFile(destPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755); downloadErr != nil {
return
}
defer func() {
if err := f.Close(); downloadErr == nil && err != nil {
downloadErr = err
}
}()
_, downloadErr = io.Copy(f, resp.Body)
return
}
var commitNotFoundErr = errors.New("commit not found")
var releaseNotFoundErr = errors.New("release not found")
var repositoryNotFoundErr = errors.New("repository not found")
// fetchLatestRelease finds the latest published release for a repository.
func fetchLatestRelease(httpClient *http.Client, baseRepo ghrepo.Interface) (*release, error) {
path := fmt.Sprintf("repos/%s/%s/releases/latest", baseRepo.RepoOwner(), baseRepo.RepoName())
url := ghinstance.RESTPrefix(baseRepo.RepoHost()) + path
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 == 404 {
return nil, releaseNotFoundErr
}
if resp.StatusCode > 299 {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var r release
err = json.Unmarshal(b, &r)
if err != nil {
return nil, err
}
return &r, nil
}
// fetchReleaseFromTag finds release by tag name for a repository
func fetchReleaseFromTag(httpClient *http.Client, baseRepo ghrepo.Interface, tagName string) (*release, error) {
fullRepoName := fmt.Sprintf("%s/%s", baseRepo.RepoOwner(), baseRepo.RepoName())
path := fmt.Sprintf("repos/%s/releases/tags/%s", fullRepoName, tagName)
url := ghinstance.RESTPrefix(baseRepo.RepoHost()) + path
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 == 404 {
return nil, releaseNotFoundErr
}
if resp.StatusCode > 299 {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var r release
err = json.Unmarshal(b, &r)
if err != nil {
return nil, err
}
return &r, nil
}
// fetchCommitSHA finds full commit SHA from a target ref in a repo
func fetchCommitSHA(httpClient *http.Client, baseRepo ghrepo.Interface, targetRef string) (string, error) {
path := fmt.Sprintf("repos/%s/%s/commits/%s", baseRepo.RepoOwner(), baseRepo.RepoName(), targetRef)
url := ghinstance.RESTPrefix(baseRepo.RepoHost()) + path
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/vnd.github.v3.sha")
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == 422 {
return "", commitNotFoundErr
}
if resp.StatusCode > 299 {
return "", api.HandleHTTPError(resp)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/extension.go | pkg/cmd/extension/extension.go | package extension
import (
"bytes"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
"gopkg.in/yaml.v3"
)
const manifestName = "manifest.yml"
type ExtensionKind int
const (
GitKind ExtensionKind = iota
BinaryKind
LocalKind
)
type Extension struct {
path string
kind ExtensionKind
gitClient gitClient
httpClient *http.Client
mu sync.RWMutex
// These fields get resolved dynamically:
url string
isPinned *bool
currentVersion string
latestVersion string
owner string
}
func (e *Extension) Name() string {
return strings.TrimPrefix(filepath.Base(e.path), "gh-")
}
func (e *Extension) Path() string {
return e.path
}
func (e *Extension) IsLocal() bool {
return e.kind == LocalKind
}
func (e *Extension) IsBinary() bool {
return e.kind == BinaryKind
}
func (e *Extension) URL() string {
e.mu.RLock()
if e.url != "" {
defer e.mu.RUnlock()
return e.url
}
e.mu.RUnlock()
var url string
switch e.kind {
case LocalKind:
case BinaryKind:
if manifest, err := e.loadManifest(); err == nil {
repo := ghrepo.NewWithHost(manifest.Owner, manifest.Name, manifest.Host)
url = ghrepo.GenerateRepoURL(repo, "")
}
case GitKind:
if remoteURL, err := e.gitClient.Config("remote.origin.url"); err == nil {
url = strings.TrimSpace(string(remoteURL))
}
}
e.mu.Lock()
e.url = url
e.mu.Unlock()
return e.url
}
func (e *Extension) CurrentVersion() string {
e.mu.RLock()
if e.currentVersion != "" {
defer e.mu.RUnlock()
return e.currentVersion
}
e.mu.RUnlock()
var currentVersion string
switch e.kind {
case LocalKind:
case BinaryKind:
if manifest, err := e.loadManifest(); err == nil {
currentVersion = manifest.Tag
}
case GitKind:
if sha, err := e.gitClient.CommandOutput([]string{"rev-parse", "HEAD"}); err == nil {
currentVersion = string(bytes.TrimSpace(sha))
}
}
e.mu.Lock()
e.currentVersion = currentVersion
e.mu.Unlock()
return e.currentVersion
}
func (e *Extension) LatestVersion() string {
e.mu.RLock()
if e.latestVersion != "" {
defer e.mu.RUnlock()
return e.latestVersion
}
e.mu.RUnlock()
var latestVersion string
switch e.kind {
case LocalKind:
case BinaryKind:
repo, err := ghrepo.FromFullName(e.URL())
if err != nil {
return ""
}
release, err := fetchLatestRelease(e.httpClient, repo)
if err != nil {
return ""
}
latestVersion = release.Tag
case GitKind:
if lsRemote, err := e.gitClient.CommandOutput([]string{"ls-remote", "origin", "HEAD"}); err == nil {
latestVersion = string(bytes.SplitN(lsRemote, []byte("\t"), 2)[0])
}
}
e.mu.Lock()
e.latestVersion = latestVersion
e.mu.Unlock()
return e.latestVersion
}
func (e *Extension) IsPinned() bool {
e.mu.RLock()
if e.isPinned != nil {
defer e.mu.RUnlock()
return *e.isPinned
}
e.mu.RUnlock()
var isPinned bool
switch e.kind {
case LocalKind:
case BinaryKind:
if manifest, err := e.loadManifest(); err == nil {
isPinned = manifest.IsPinned
}
case GitKind:
extDir := filepath.Dir(e.path)
pinPath := filepath.Join(extDir, fmt.Sprintf(".pin-%s", e.CurrentVersion()))
if _, err := os.Stat(pinPath); err == nil {
isPinned = true
} else {
isPinned = false
}
}
e.mu.Lock()
e.isPinned = &isPinned
e.mu.Unlock()
return *e.isPinned
}
func (e *Extension) Owner() string {
e.mu.RLock()
if e.owner != "" {
defer e.mu.RUnlock()
return e.owner
}
e.mu.RUnlock()
var owner string
switch e.kind {
case LocalKind:
case BinaryKind:
if manifest, err := e.loadManifest(); err == nil {
owner = manifest.Owner
}
case GitKind:
if remoteURL, err := e.gitClient.Config("remote.origin.url"); err == nil {
if url, err := git.ParseURL(strings.TrimSpace(string(remoteURL))); err == nil {
if repo, err := ghrepo.FromURL(url); err == nil {
owner = repo.RepoOwner()
}
}
}
}
e.mu.Lock()
e.owner = owner
e.mu.Unlock()
return e.owner
}
func (e *Extension) UpdateAvailable() bool {
if e.IsLocal() ||
e.CurrentVersion() == "" ||
e.LatestVersion() == "" ||
e.CurrentVersion() == e.LatestVersion() {
return false
}
return true
}
func (e *Extension) loadManifest() (binManifest, error) {
var bm binManifest
dir, _ := filepath.Split(e.Path())
manifestPath := filepath.Join(dir, manifestName)
manifest, err := os.ReadFile(manifestPath)
if err != nil {
return bm, fmt.Errorf("could not open %s for reading: %w", manifestPath, err)
}
err = yaml.Unmarshal(manifest, &bm)
if err != nil {
return bm, fmt.Errorf("could not parse %s: %w", manifestPath, err)
}
return bm, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/command.go | pkg/cmd/extension/command.go | package extension
import (
"errors"
"fmt"
gio "io"
"os"
"path/filepath"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/extension/browse"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/search"
"github.com/spf13/cobra"
)
var alreadyInstalledError = errors.New("alreadyInstalledError")
func NewCmdExtension(f *cmdutil.Factory) *cobra.Command {
m := f.ExtensionManager
io := f.IOStreams
gc := f.GitClient
prompter := f.Prompter
config := f.Config
browser := f.Browser
httpClient := f.HttpClient
extCmd := cobra.Command{
Use: "extension",
Short: "Manage gh extensions",
Long: heredoc.Docf(`
GitHub CLI extensions are repositories that provide additional gh commands.
The name of the extension repository must start with %[1]sgh-%[1]s and it must contain an
executable of the same name. All arguments passed to the %[1]sgh <extname>%[1]s invocation
will be forwarded to the %[1]sgh-<extname>%[1]s executable of the extension.
An extension cannot override any of the core gh commands. If an extension name conflicts
with a core gh command, you can use %[1]sgh extension exec <extname>%[1]s.
When an extension is executed, gh will check for new versions once every 24 hours and display
an upgrade notice. See %[1]sgh help environment%[1]s for information on disabling extension notices.
For the list of available extensions, see <https://github.com/topics/gh-extension>.
`, "`"),
Aliases: []string{"extensions", "ext"},
}
upgradeFunc := func(name string, flagForce bool) error {
cs := io.ColorScheme()
err := m.Upgrade(name, flagForce)
if err != nil {
if name != "" {
fmt.Fprintf(io.ErrOut, "%s Failed upgrading extension %s: %s\n", cs.FailureIcon(), name, err)
} else if errors.Is(err, noExtensionsInstalledError) {
return cmdutil.NewNoResultsError("no installed extensions found")
} else {
fmt.Fprintf(io.ErrOut, "%s Failed upgrading extensions\n", cs.FailureIcon())
}
return cmdutil.SilentError
}
if io.IsStdoutTTY() {
fmt.Fprintf(io.Out, "%s Successfully checked extension upgrades\n", cs.SuccessIcon())
}
return nil
}
extCmd.AddCommand(
func() *cobra.Command {
query := search.Query{
Kind: search.KindRepositories,
}
qualifiers := search.Qualifiers{
Topic: []string{"gh-extension"},
}
var order string
var sort string
var webMode bool
var exporter cmdutil.Exporter
cmd := &cobra.Command{
Use: "search [<query>]",
Short: "Search extensions to the GitHub CLI",
Long: heredoc.Docf(`
Search for gh extensions.
With no arguments, this command prints out the first 30 extensions
available to install sorted by number of stars. More extensions can
be fetched by specifying a higher limit with the %[1]s--limit%[1]s flag.
When connected to a terminal, this command prints out three columns.
The first has a ✓ if the extension is already installed locally. The
second is the full name of the extension repository in %[1]sOWNER/REPO%[1]s
format. The third is the extension's description.
When not connected to a terminal, the ✓ character is rendered as the
word "installed" but otherwise the order and content of the columns
are the same.
This command behaves similarly to %[1]sgh search repos%[1]s but does not
support as many search qualifiers. For a finer grained search of
extensions, try using:
gh search repos --topic "gh-extension"
and adding qualifiers as needed. See %[1]sgh help search repos%[1]s to learn
more about repository search.
For listing just the extensions that are already installed locally,
see:
gh ext list
`, "`"),
Example: heredoc.Doc(`
# List the first 30 extensions sorted by star count, descending
$ gh ext search
# List more extensions
$ gh ext search --limit 300
# List extensions matching the term "branch"
$ gh ext search branch
# List extensions owned by organization "github"
$ gh ext search --owner github
# List extensions, sorting by recently updated, ascending
$ gh ext search --sort updated --order asc
# List extensions, filtering by license
$ gh ext search --license MIT
# Open search results in the browser
$ gh ext search -w
`),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config()
if err != nil {
return err
}
client, err := httpClient()
if err != nil {
return err
}
if cmd.Flags().Changed("order") {
query.Order = order
}
if cmd.Flags().Changed("sort") {
query.Sort = sort
}
query.Keywords = args
query.Qualifiers = qualifiers
host, _ := cfg.Authentication().DefaultHost()
detector := featuredetection.NewDetector(client, host)
searcher := search.NewSearcher(client, host, detector)
if webMode {
url := searcher.URL(query)
if io.IsStdoutTTY() {
fmt.Fprintf(io.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(url))
}
return browser.Browse(url)
}
io.StartProgressIndicator()
result, err := searcher.Repositories(query)
io.StopProgressIndicator()
if err != nil {
return err
}
if exporter != nil {
return exporter.Write(io, result.Items)
}
if io.IsStdoutTTY() {
if len(result.Items) == 0 {
return errors.New("no extensions found")
}
fmt.Fprintf(io.Out, "Showing %d of %d extensions\n", len(result.Items), result.Total)
fmt.Fprintln(io.Out)
}
cs := io.ColorScheme()
installedExts := m.List()
isInstalled := func(repo search.Repository) bool {
searchRepo, err := ghrepo.FromFullName(repo.FullName)
if err != nil {
return false
}
for _, e := range installedExts {
// TODO consider a Repo() on Extension interface
if u, err := git.ParseURL(e.URL()); err == nil {
if r, err := ghrepo.FromURL(u); err == nil {
if ghrepo.IsSame(searchRepo, r) {
return true
}
}
}
}
return false
}
tp := tableprinter.New(io, tableprinter.WithHeader("", "REPO", "DESCRIPTION"))
for _, repo := range result.Items {
if !strings.HasPrefix(repo.Name, "gh-") {
continue
}
installed := ""
if isInstalled(repo) {
if io.IsStdoutTTY() {
installed = "✓"
} else {
installed = "installed"
}
}
tp.AddField(installed, tableprinter.WithColor(cs.Green))
tp.AddField(repo.FullName, tableprinter.WithColor(cs.Bold))
tp.AddField(repo.Description)
tp.EndRow()
}
return tp.Render()
},
}
// Output flags
cmd.Flags().BoolVarP(&webMode, "web", "w", false, "Open the search query in the web browser")
cmdutil.AddJSONFlags(cmd, &exporter, search.RepositoryFields)
// Query parameter flags
cmd.Flags().IntVarP(&query.Limit, "limit", "L", 30, "Maximum number of extensions to fetch")
cmdutil.StringEnumFlag(cmd, &order, "order", "", "desc", []string{"asc", "desc"}, "Order of repositories returned, ignored unless '--sort' flag is specified")
cmdutil.StringEnumFlag(cmd, &sort, "sort", "", "best-match", []string{"forks", "help-wanted-issues", "stars", "updated"}, "Sort fetched repositories")
// Qualifier flags
cmd.Flags().StringSliceVar(&qualifiers.License, "license", nil, "Filter based on license type")
cmd.Flags().StringSliceVar(&qualifiers.User, "owner", nil, "Filter on owner")
return cmd
}(),
&cobra.Command{
Use: "list",
Short: "List installed extension commands",
Aliases: []string{"ls"},
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cmds := m.List()
if len(cmds) == 0 {
return cmdutil.NewNoResultsError("no installed extensions found")
}
cs := io.ColorScheme()
t := tableprinter.New(io, tableprinter.WithHeader("NAME", "REPO", "VERSION"))
for _, c := range cmds {
// TODO consider a Repo() on Extension interface
var repo string
if u, err := git.ParseURL(c.URL()); err == nil {
if r, err := ghrepo.FromURL(u); err == nil {
repo = ghrepo.FullName(r)
}
}
t.AddField(fmt.Sprintf("gh %s", c.Name()))
t.AddField(repo)
version := displayExtensionVersion(c, c.CurrentVersion())
if c.IsPinned() {
t.AddField(version, tableprinter.WithColor(cs.Cyan))
} else {
t.AddField(version)
}
t.EndRow()
}
return t.Render()
},
},
func() *cobra.Command {
var forceFlag bool
var pinFlag string
cmd := &cobra.Command{
Use: "install <repository>",
Short: "Install a gh extension from a repository",
Long: heredoc.Docf(`
Install a GitHub CLI extension from a GitHub or local repository.
For GitHub repositories, the repository argument can be specified in
%[1]sOWNER/REPO%[1]s format or as a full repository URL.
The URL format is useful when the repository is not hosted on %[1]sgithub.com%[1]s.
For remote repositories, the GitHub CLI first looks for the release artifacts assuming
that it's a binary extension i.e. prebuilt binaries provided as part of the release.
In the absence of a release, the repository itself is cloned assuming that it's a
script extension i.e. prebuilt executable or script exists on its root.
The %[1]s--pin%[1]s flag may be used to specify a tag or commit for binary and script
extensions respectively, the latest version is used otherwise.
For local repositories, often used while developing extensions, use %[1]s.%[1]s as the
value of the repository argument. Note the following:
- After installing an extension from a locally cloned repository, the GitHub CLI will
manage this extension as a symbolic link (or equivalent mechanism on Windows) pointing
to an executable file with the same name as the repository in the repository's root.
For example, if the repository is named %[1]sgh-foobar%[1]s, the symbolic link will point
to %[1]sgh-foobar%[1]s in the extension repository's root.
- When executing the extension, the GitHub CLI will run the executable file found
by following the symbolic link. If no executable file is found, the extension
will fail to execute.
- If the extension is precompiled, the executable file must be built manually and placed
in the repository's root.
For the list of available extensions, see <https://github.com/topics/gh-extension>.
`, "`"),
Example: heredoc.Doc(`
# Install an extension from a remote repository hosted on GitHub
$ gh extension install owner/gh-extension
# Install an extension from a remote repository via full URL
$ gh extension install https://my.ghes.com/owner/gh-extension
# Install an extension from a local repository in the current working directory
$ gh extension install .
`),
Args: cmdutil.MinimumArgs(1, "must specify a repository to install from"),
RunE: func(cmd *cobra.Command, args []string) error {
if args[0] == "." {
if pinFlag != "" {
return fmt.Errorf("local extensions cannot be pinned")
}
wd, err := os.Getwd()
if err != nil {
return err
}
_, err = checkValidExtension(cmd.Root(), m, filepath.Base(wd), "")
if err != nil {
return err
}
err = m.InstallLocal(wd)
var ErrExtensionExecutableNotFound *ErrExtensionExecutableNotFound
if errors.As(err, &ErrExtensionExecutableNotFound) {
cs := io.ColorScheme()
if io.IsStdoutTTY() {
fmt.Fprintf(io.ErrOut, "%s %s", cs.WarningIcon(), ErrExtensionExecutableNotFound.Error())
}
return nil
}
return err
}
repo, err := ghrepo.FromFullName(args[0])
if err != nil {
return err
}
cs := io.ColorScheme()
if ext, err := checkValidExtension(cmd.Root(), m, repo.RepoName(), repo.RepoOwner()); err != nil {
// If an existing extension was found and --force was specified, attempt to upgrade.
if forceFlag && ext != nil {
return upgradeFunc(ext.Name(), forceFlag)
}
if errors.Is(err, alreadyInstalledError) {
fmt.Fprintf(io.ErrOut, "%s Extension %s is already installed\n", cs.WarningIcon(), ghrepo.FullName(repo))
return nil
}
return err
}
io.StartProgressIndicator()
err = m.Install(repo, pinFlag)
io.StopProgressIndicator()
if err != nil {
if errors.Is(err, releaseNotFoundErr) {
return fmt.Errorf("%s Could not find a release of %s for %s",
cs.FailureIcon(), args[0], cs.Cyan(pinFlag))
} else if errors.Is(err, commitNotFoundErr) {
return fmt.Errorf("%s %s does not exist in %s",
cs.FailureIcon(), cs.Cyan(pinFlag), args[0])
} else if errors.Is(err, repositoryNotFoundErr) {
return fmt.Errorf("%s Could not find extension '%s' on host %s",
cs.FailureIcon(), args[0], repo.RepoHost())
}
return err
}
if io.IsStdoutTTY() {
fmt.Fprintf(io.Out, "%s Installed extension %s\n", cs.SuccessIcon(), args[0])
if pinFlag != "" {
fmt.Fprintf(io.Out, "%s Pinned extension at %s\n", cs.SuccessIcon(), cs.Cyan(pinFlag))
}
}
return nil
},
}
cmd.Flags().BoolVar(&forceFlag, "force", false, "Force upgrade extension, or ignore if latest already installed")
cmd.Flags().StringVar(&pinFlag, "pin", "", "Pin extension to a release tag or commit ref")
return cmd
}(),
func() *cobra.Command {
var flagAll bool
var flagForce bool
var flagDryRun bool
cmd := &cobra.Command{
Use: "upgrade {<name> | --all}",
Short: "Upgrade installed extensions",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 && !flagAll {
return cmdutil.FlagErrorf("specify an extension to upgrade or `--all`")
}
if len(args) > 0 && flagAll {
return cmdutil.FlagErrorf("cannot use `--all` with extension name")
}
if len(args) > 1 {
return cmdutil.FlagErrorf("too many arguments")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var name string
if len(args) > 0 {
name = normalizeExtensionSelector(args[0])
}
if flagDryRun {
m.EnableDryRunMode()
}
return upgradeFunc(name, flagForce)
},
}
cmd.Flags().BoolVar(&flagAll, "all", false, "Upgrade all extensions")
cmd.Flags().BoolVar(&flagForce, "force", false, "Force upgrade extension")
cmd.Flags().BoolVar(&flagDryRun, "dry-run", false, "Only display upgrades")
return cmd
}(),
&cobra.Command{
Use: "remove <name>",
Short: "Remove an installed extension",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
extName := normalizeExtensionSelector(args[0])
if err := m.Remove(extName); err != nil {
return err
}
if io.IsStdoutTTY() {
cs := io.ColorScheme()
fmt.Fprintf(io.Out, "%s Removed extension %s\n", cs.SuccessIcon(), extName)
}
return nil
},
},
func() *cobra.Command {
var debug bool
var singleColumn bool
cmd := &cobra.Command{
Use: "browse",
Short: "Enter a UI for browsing, adding, and removing extensions",
Long: heredoc.Docf(`
This command will take over your terminal and run a fully interactive
interface for browsing, adding, and removing gh extensions. A terminal
width greater than 100 columns is recommended.
To learn how to control this interface, press %[1]s?%[1]s after running to see
the help text.
Press %[1]sq%[1]s to quit.
Running this command with %[1]s--single-column%[1]s should make this command
more intelligible for users who rely on assistive technology like screen
readers or high zoom.
For a more traditional way to discover extensions, see:
gh ext search
along with %[1]sgh ext install%[1]s, %[1]sgh ext remove%[1]s, and %[1]sgh repo view%[1]s.
`, "`"),
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if !io.CanPrompt() {
return errors.New("this command runs an interactive UI and needs to be run in a terminal")
}
cfg, err := config()
if err != nil {
return err
}
host, _ := cfg.Authentication().DefaultHost()
client, err := f.HttpClient()
if err != nil {
return err
}
detector := featuredetection.NewDetector(client, host)
searcher := search.NewSearcher(api.NewCachedHTTPClient(client, time.Hour*24), host, detector)
gc.Stderr = gio.Discard
opts := browse.ExtBrowseOpts{
Cmd: cmd,
IO: io,
Browser: browser,
Searcher: searcher,
Em: m,
Client: client,
Cfg: cfg,
Debug: debug,
SingleColumn: singleColumn,
}
return browse.ExtBrowse(opts)
},
}
cmd.Flags().BoolVar(&debug, "debug", false, "Log to /tmp/extBrowse-*")
cmd.Flags().BoolVarP(&singleColumn, "single-column", "s", false, "Render TUI with only one column of text")
return cmd
}(),
&cobra.Command{
Use: "exec <name> [args]",
Short: "Execute an installed extension",
Long: heredoc.Docf(`
Execute an extension using the short name. For example, if the extension repository is
%[1]sowner/gh-extension%[1]s, you should pass %[1]sextension%[1]s. You can use this command when
the short name conflicts with a core gh command.
All arguments after the extension name will be forwarded to the executable
of the extension.
`, "`"),
Example: heredoc.Doc(`
# Execute a label extension instead of the core gh label command
$ gh extension exec label
`),
Args: cobra.MinimumNArgs(1),
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
if found, err := m.Dispatch(args, io.In, io.Out, io.ErrOut); !found {
return fmt.Errorf("extension %q not found", args[0])
} else {
return err
}
},
},
func() *cobra.Command {
promptCreate := func() (string, extensions.ExtTemplateType, error) {
extName, err := prompter.Input("Extension name:", "")
if err != nil {
return extName, -1, err
}
options := []string{"Script (Bash, Ruby, Python, etc)", "Go", "Other Precompiled (C++, Rust, etc)"}
extTmplType, err := prompter.Select("What kind of extension?",
options[0],
options)
return extName, extensions.ExtTemplateType(extTmplType), err
}
var flagType string
cmd := &cobra.Command{
Use: "create [<name>]",
Short: "Create a new extension",
Example: heredoc.Doc(`
# Use interactively
$ gh extension create
# Create a script-based extension
$ gh extension create foobar
# Create a Go extension
$ gh extension create --precompiled=go foobar
# Create a non-Go precompiled extension
$ gh extension create --precompiled=other foobar
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if cmd.Flags().Changed("precompiled") {
if flagType != "go" && flagType != "other" {
return cmdutil.FlagErrorf("value for --precompiled must be 'go' or 'other'. Got '%s'", flagType)
}
}
var extName string
var err error
tmplType := extensions.GitTemplateType
if len(args) == 0 {
if io.IsStdoutTTY() {
extName, tmplType, err = promptCreate()
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
}
} else {
extName = args[0]
if flagType == "go" {
tmplType = extensions.GoBinTemplateType
} else if flagType == "other" {
tmplType = extensions.OtherBinTemplateType
}
}
var fullName string
if strings.HasPrefix(extName, "gh-") {
fullName = extName
extName = extName[3:]
} else {
fullName = "gh-" + extName
}
cs := io.ColorScheme()
commitIcon := cs.SuccessIcon()
if err := m.Create(fullName, tmplType); err != nil {
if errors.Is(err, ErrInitialCommitFailed) {
commitIcon = cs.FailureIcon()
} else {
return err
}
}
if !io.IsStdoutTTY() {
return nil
}
var goBinChecks string
steps := fmt.Sprintf(
"- run 'cd %[1]s; gh extension install .; gh %[2]s' to see your new extension in action",
fullName, extName)
if tmplType == extensions.GoBinTemplateType {
goBinChecks = heredoc.Docf(`
%[1]s Downloaded Go dependencies
%[1]s Built %[2]s binary
`, cs.SuccessIcon(), fullName)
steps = heredoc.Docf(`
- run 'cd %[1]s; gh extension install .; gh %[2]s' to see your new extension in action
- run 'go build && gh %[2]s' to see changes in your code as you develop`, fullName, extName)
} else if tmplType == extensions.OtherBinTemplateType {
steps = heredoc.Docf(`
- run 'cd %[1]s; gh extension install .' to install your extension locally
- fill in script/build.sh with your compilation script for automated builds
- compile a %[1]s binary locally and run 'gh %[2]s' to see changes`, fullName, extName)
}
link := "https://docs.github.com/github-cli/github-cli/creating-github-cli-extensions"
out := heredoc.Docf(`
%[1]s Created directory %[2]s
%[1]s Initialized git repository
%[7]s Made initial commit
%[1]s Set up extension scaffolding
%[6]s
%[2]s is ready for development!
%[4]s
%[5]s
- run 'gh repo create' to share your extension with others
For more information on writing extensions:
%[3]s
`, cs.SuccessIcon(), fullName, link, cs.Bold("Next Steps"), steps, goBinChecks, commitIcon)
fmt.Fprint(io.Out, out)
return nil
},
}
cmd.Flags().StringVar(&flagType, "precompiled", "", "Create a precompiled extension. Possible values: go, other")
return cmd
}(),
)
return &extCmd
}
func checkValidExtension(rootCmd *cobra.Command, m extensions.ExtensionManager, extName, extOwner string) (extensions.Extension, error) {
if !strings.HasPrefix(extName, "gh-") {
return nil, errors.New("extension name must start with `gh-`")
}
commandName := strings.TrimPrefix(extName, "gh-")
if c, _, _ := rootCmd.Find([]string{commandName}); c != rootCmd && c.GroupID != "extension" {
return nil, fmt.Errorf("%q matches the name of a built-in command or alias", commandName)
}
for _, ext := range m.List() {
if ext.Name() == commandName {
if extOwner != "" && ext.Owner() == extOwner {
return ext, alreadyInstalledError
}
return ext, fmt.Errorf("there is already an installed extension that provides the %q command", commandName)
}
}
return nil, nil
}
func normalizeExtensionSelector(n string) string {
if idx := strings.IndexRune(n, '/'); idx >= 0 {
n = n[idx+1:]
}
return strings.TrimPrefix(n, "gh-")
}
func displayExtensionVersion(ext extensions.Extension, version string) string {
if !ext.IsBinary() && len(version) > 8 {
return version[:8]
}
return version
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/manager.go | pkg/cmd/extension/manager.go | package extension
import (
_ "embed"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/findsh"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/safeexec"
"gopkg.in/yaml.v3"
)
// ErrInitialCommitFailed indicates the initial commit when making a new extension failed.
var ErrInitialCommitFailed = errors.New("initial commit failed")
type ErrExtensionExecutableNotFound struct {
Dir string
Name string
}
func (e *ErrExtensionExecutableNotFound) Error() string {
return fmt.Sprintf("an extension has been installed but there is no executable: executable file named \"%s\" in %s is required to run the extension after install. Perhaps you need to build it?\n", e.Name, e.Dir)
}
const darwinAmd64 = "darwin-amd64"
type Manager struct {
dataDir func() string
updateDir func() string
lookPath func(string) (string, error)
findSh func() (string, error)
newCommand func(string, ...string) *exec.Cmd
platform func() (string, string)
client *http.Client
gitClient gitClient
config gh.Config
io *iostreams.IOStreams
dryRunMode bool
}
func NewManager(ios *iostreams.IOStreams, gc *git.Client) *Manager {
return &Manager{
dataDir: config.DataDir,
updateDir: func() string {
return filepath.Join(config.StateDir(), "extensions")
},
lookPath: safeexec.LookPath,
findSh: findsh.Find,
newCommand: exec.Command,
platform: func() (string, string) {
ext := ""
if runtime.GOOS == "windows" {
ext = ".exe"
}
return fmt.Sprintf("%s-%s", runtime.GOOS, runtime.GOARCH), ext
},
io: ios,
gitClient: &gitExecuter{client: gc},
}
}
func (m *Manager) SetConfig(cfg gh.Config) {
m.config = cfg
}
func (m *Manager) SetClient(client *http.Client) {
m.client = client
}
func (m *Manager) EnableDryRunMode() {
m.dryRunMode = true
}
func (m *Manager) Dispatch(args []string, stdin io.Reader, stdout, stderr io.Writer) (bool, error) {
if len(args) == 0 {
return false, errors.New("too few arguments in list")
}
var exe string
extName := args[0]
forwardArgs := args[1:]
exts, _ := m.list(false)
var ext *Extension
for _, e := range exts {
if e.Name() == extName {
ext = e
exe = ext.Path()
break
}
}
if exe == "" {
return false, nil
}
var externalCmd *exec.Cmd
if ext.IsBinary() || runtime.GOOS != "windows" {
externalCmd = m.newCommand(exe, forwardArgs...)
} else if runtime.GOOS == "windows" {
// Dispatch all extension calls through the `sh` interpreter to support executable files with a
// shebang line on Windows.
shExe, err := m.findSh()
if err != nil {
if errors.Is(err, exec.ErrNotFound) {
return true, errors.New("the `sh.exe` interpreter is required. Please install Git for Windows and try again")
}
return true, err
}
forwardArgs = append([]string{"-c", `command "$@"`, "--", exe}, forwardArgs...)
externalCmd = m.newCommand(shExe, forwardArgs...)
}
externalCmd.Stdin = stdin
externalCmd.Stdout = stdout
externalCmd.Stderr = stderr
return true, externalCmd.Run()
}
func (m *Manager) List() []extensions.Extension {
exts, _ := m.list(false)
r := make([]extensions.Extension, len(exts))
for i, ext := range exts {
r[i] = ext
}
return r
}
func (m *Manager) list(includeMetadata bool) ([]*Extension, error) {
dir := m.installDir()
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
results := make([]*Extension, 0, len(entries))
for _, f := range entries {
if !strings.HasPrefix(f.Name(), "gh-") {
continue
}
if f.IsDir() {
if _, err := os.Stat(filepath.Join(dir, f.Name(), manifestName)); err == nil {
results = append(results, &Extension{
path: filepath.Join(dir, f.Name(), f.Name()),
kind: BinaryKind,
httpClient: m.client,
})
} else {
results = append(results, &Extension{
path: filepath.Join(dir, f.Name(), f.Name()),
kind: GitKind,
gitClient: m.gitClient.ForRepo(filepath.Join(dir, f.Name())),
})
}
} else if isSymlink(f.Type()) {
results = append(results, &Extension{
path: filepath.Join(dir, f.Name(), f.Name()),
kind: LocalKind,
})
} else {
// the contents of a regular file point to a local extension on disk
p, err := readPathFromFile(filepath.Join(dir, f.Name()))
if err != nil {
return nil, err
}
results = append(results, &Extension{
path: filepath.Join(p, f.Name()),
kind: LocalKind,
})
}
}
if includeMetadata {
m.populateLatestVersions(results)
}
return results, nil
}
func (m *Manager) populateLatestVersions(exts []*Extension) {
var wg sync.WaitGroup
for _, ext := range exts {
wg.Add(1)
go func(e *Extension) {
defer wg.Done()
e.LatestVersion()
}(ext)
}
wg.Wait()
}
func (m *Manager) InstallLocal(dir string) error {
name := filepath.Base(dir)
if err := m.cleanExtensionUpdateDir(name); err != nil {
return err
}
targetLink := filepath.Join(m.installDir(), name)
if err := os.MkdirAll(filepath.Dir(targetLink), 0755); err != nil {
return err
}
if err := makeSymlink(dir, targetLink); err != nil {
return err
}
// Check if an executable of the same name exists in the target directory.
// An error here doesn't indicate a failed extension installation, but
// it does indicate that the user will not be able to run the extension until
// the executable file is built or created manually somehow.
if _, err := os.Stat(filepath.Join(dir, name)); err != nil {
if os.IsNotExist(err) {
return &ErrExtensionExecutableNotFound{
Dir: dir,
Name: name,
}
}
return err
}
return nil
}
type binManifest struct {
Owner string
Name string
Host string
Tag string
IsPinned bool
// TODO I may end up not using this; just thinking ahead to local installs
Path string
}
// Install installs an extension from repo, and pins to commitish if provided
func (m *Manager) Install(repo ghrepo.Interface, target string) error {
isBin, err := isBinExtension(m.client, repo)
if err != nil {
if errors.Is(err, releaseNotFoundErr) {
if ok, err := repoExists(m.client, repo); err != nil {
return err
} else if !ok {
return repositoryNotFoundErr
}
} else {
return fmt.Errorf("could not check for binary extension: %w", err)
}
}
if isBin {
return m.installBin(repo, target)
}
hs, err := hasScript(m.client, repo)
if err != nil {
return err
}
if !hs {
return fmt.Errorf("extension is not installable: no usable release artifact or script found in %s", repo)
}
return m.installGit(repo, target)
}
func (m *Manager) installBin(repo ghrepo.Interface, target string) error {
var r *release
var err error
isPinned := target != ""
if isPinned {
r, err = fetchReleaseFromTag(m.client, repo, target)
} else {
r, err = fetchLatestRelease(m.client, repo)
}
if err != nil {
return err
}
platform, ext := m.platform()
isMacARM := platform == "darwin-arm64"
trueARMBinary := false
var asset *releaseAsset
for _, a := range r.Assets {
if strings.HasSuffix(a.Name, platform+ext) {
asset = &a
trueARMBinary = isMacARM
break
}
}
// if using an ARM-based Mac and an arm64 binary is unavailable, fall back to amd64 if a relevant binary is available and Rosetta 2 is installed
if asset == nil && isMacARM {
for _, a := range r.Assets {
if strings.HasSuffix(a.Name, darwinAmd64) {
if !hasRosetta() {
return fmt.Errorf(
"%[1]s unsupported for %[2]s. Install Rosetta with `softwareupdate --install-rosetta` to use the available %[3]s binary, or open an issue: `gh issue create -R %[4]s/%[1]s -t'Support %[2]s'`",
repo.RepoName(), platform, darwinAmd64, repo.RepoOwner())
}
fallbackMessage := fmt.Sprintf("%[1]s not available for %[2]s. Falling back to compatible %[3]s binary", repo.RepoName(), platform, darwinAmd64)
fmt.Fprintln(m.io.Out, fallbackMessage)
asset = &a
break
}
}
}
if asset == nil {
cs := m.io.ColorScheme()
errorMessageInRed := fmt.Sprintf(cs.Red("%[1]s unsupported for %[2]s."), repo.RepoName(), platform)
issueCreateCommand := generateMissingBinaryIssueCreateCommand(repo.RepoOwner(), repo.RepoName(), platform)
return fmt.Errorf(
"%[1]s\n\nTo request support for %[2]s, open an issue on the extension's repo by running the following command:\n\n `%[3]s`",
errorMessageInRed, platform, issueCreateCommand)
}
if m.dryRunMode {
return nil
}
name := repo.RepoName()
if err := m.cleanExtensionUpdateDir(name); err != nil {
return err
}
targetDir := filepath.Join(m.installDir(), name)
if err = os.MkdirAll(targetDir, 0755); err != nil {
return fmt.Errorf("failed to create installation directory: %w", err)
}
binPath := filepath.Join(targetDir, name)
binPath += ext
err = downloadAsset(m.client, *asset, binPath)
if err != nil {
return fmt.Errorf("failed to download asset %s: %w", asset.Name, err)
}
if trueARMBinary {
if err := codesignBinary(binPath); err != nil {
return fmt.Errorf("failed to codesign downloaded binary: %w", err)
}
}
manifest := binManifest{
Name: name,
Owner: repo.RepoOwner(),
Host: repo.RepoHost(),
Path: binPath,
Tag: r.Tag,
IsPinned: isPinned,
}
bs, err := yaml.Marshal(manifest)
if err != nil {
return fmt.Errorf("failed to serialize manifest: %w", err)
}
if err := writeManifest(targetDir, manifestName, bs); err != nil {
return err
}
return nil
}
func generateMissingBinaryIssueCreateCommand(repoOwner string, repoName string, currentPlatform string) string {
issueBody := generateMissingBinaryIssueBody(currentPlatform)
return fmt.Sprintf("gh issue create -R %[1]s/%[2]s --title \"Add support for the %[3]s architecture\" --body \"%[4]s\"", repoOwner, repoName, currentPlatform, issueBody)
}
func generateMissingBinaryIssueBody(currentPlatform string) string {
return fmt.Sprintf("This extension does not support the %[1]s architecture. I tried to install it on a %[1]s machine, and it failed due to the lack of an available binary. Would you be able to update the extension's build and release process to include the relevant binary? For more details, see <https://docs.github.com/en/github-cli/github-cli/creating-github-cli-extensions>.", currentPlatform)
}
func writeManifest(dir, name string, data []byte) (writeErr error) {
path := filepath.Join(dir, name)
var f *os.File
if f, writeErr = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600); writeErr != nil {
writeErr = fmt.Errorf("failed to open manifest for writing: %w", writeErr)
return
}
defer func() {
if err := f.Close(); writeErr == nil && err != nil {
writeErr = err
}
}()
if _, writeErr = f.Write(data); writeErr != nil {
writeErr = fmt.Errorf("failed write manifest file: %w", writeErr)
}
return
}
func (m *Manager) installGit(repo ghrepo.Interface, target string) error {
protocol := m.config.GitProtocol(repo.RepoHost()).Value
cloneURL := ghrepo.FormatRemoteURL(repo, protocol)
var commitSHA string
if target != "" {
var err error
commitSHA, err = fetchCommitSHA(m.client, repo, target)
if err != nil {
return err
}
}
name := strings.TrimSuffix(path.Base(cloneURL), ".git")
targetDir := filepath.Join(m.installDir(), name)
if err := m.cleanExtensionUpdateDir(name); err != nil {
return err
}
_, err := m.gitClient.Clone(cloneURL, []string{targetDir})
if err != nil {
return err
}
if commitSHA == "" {
return nil
}
scopedClient := m.gitClient.ForRepo(targetDir)
err = scopedClient.CheckoutBranch(commitSHA)
if err != nil {
return err
}
pinPath := filepath.Join(targetDir, fmt.Sprintf(".pin-%s", commitSHA))
f, err := os.OpenFile(pinPath, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return fmt.Errorf("failed to create pin file in directory: %w", err)
}
return f.Close()
}
var pinnedExtensionUpgradeError = errors.New("pinned extensions can not be upgraded")
var localExtensionUpgradeError = errors.New("local extensions can not be upgraded")
var upToDateError = errors.New("already up to date")
var noExtensionsInstalledError = errors.New("no extensions installed")
func (m *Manager) Upgrade(name string, force bool) error {
// Fetch metadata during list only when upgrading all extensions.
// This is a performance improvement so that we don't make a
// bunch of unnecessary network requests when trying to upgrade a single extension.
fetchMetadata := name == ""
exts, _ := m.list(fetchMetadata)
if len(exts) == 0 {
return noExtensionsInstalledError
}
if name == "" {
return m.upgradeExtensions(exts, force)
}
for _, f := range exts {
if f.Name() != name {
continue
}
if f.IsLocal() {
return localExtensionUpgradeError
}
// For single extensions manually retrieve latest version since we forgo doing it during list.
if latestVersion := f.LatestVersion(); latestVersion == "" {
return fmt.Errorf("unable to retrieve latest version for extension %q", name)
}
return m.upgradeExtensions([]*Extension{f}, force)
}
return fmt.Errorf("no extension matched %q", name)
}
func (m *Manager) upgradeExtensions(exts []*Extension, force bool) error {
var longestExt = slices.MaxFunc(exts, func(a, b *Extension) int {
return len(a.Name()) - len(b.Name())
})
var longestExtName = len(longestExt.Name())
var failed bool
for _, f := range exts {
fmt.Fprintf(m.io.Out, "[%*s]: ", longestExtName, f.Name())
currentVersion := displayExtensionVersion(f, f.CurrentVersion())
err := m.upgradeExtension(f, force)
if err != nil {
if !errors.Is(err, localExtensionUpgradeError) &&
!errors.Is(err, upToDateError) &&
!errors.Is(err, pinnedExtensionUpgradeError) {
failed = true
}
fmt.Fprintf(m.io.Out, "%s\n", err)
continue
}
latestVersion := displayExtensionVersion(f, f.LatestVersion())
if m.dryRunMode {
fmt.Fprintf(m.io.Out, "would have upgraded from %s to %s\n", currentVersion, latestVersion)
} else {
fmt.Fprintf(m.io.Out, "upgraded from %s to %s\n", currentVersion, latestVersion)
}
}
if failed {
return errors.New("some extensions failed to upgrade")
}
return nil
}
func (m *Manager) upgradeExtension(ext *Extension, force bool) error {
if ext.IsLocal() {
return localExtensionUpgradeError
}
if !force && ext.IsPinned() {
return pinnedExtensionUpgradeError
}
if !ext.UpdateAvailable() {
return upToDateError
}
var err error
if ext.IsBinary() {
err = m.upgradeBinExtension(ext)
} else {
// Check if git extension has changed to a binary extension
var isBin bool
repo, repoErr := repoFromPath(m.gitClient, filepath.Join(ext.Path(), ".."))
if repoErr == nil {
isBin, _ = isBinExtension(m.client, repo)
}
if isBin {
if err := m.Remove(ext.Name()); err != nil {
return fmt.Errorf("failed to migrate to new precompiled extension format: %w", err)
}
return m.installBin(repo, "")
}
err = m.upgradeGitExtension(ext, force)
}
return err
}
func (m *Manager) upgradeGitExtension(ext *Extension, force bool) error {
if m.dryRunMode {
return nil
}
dir := filepath.Dir(ext.path)
scopedClient := m.gitClient.ForRepo(dir)
if force {
err := scopedClient.Fetch("origin", "HEAD")
if err != nil {
return err
}
_, err = scopedClient.CommandOutput([]string{"reset", "--hard", "origin/HEAD"})
return err
}
return scopedClient.Pull("", "")
}
func (m *Manager) upgradeBinExtension(ext *Extension) error {
repo, err := ghrepo.FromFullName(ext.URL())
if err != nil {
return fmt.Errorf("failed to parse URL %s: %w", ext.URL(), err)
}
return m.installBin(repo, "")
}
func (m *Manager) Remove(name string) error {
name = normalizeExtension(name)
targetDir := filepath.Join(m.installDir(), name)
if _, err := os.Lstat(targetDir); os.IsNotExist(err) {
return fmt.Errorf("no extension found: %q", targetDir)
}
if m.dryRunMode {
return nil
}
if err := m.cleanExtensionUpdateDir(name); err != nil {
return err
}
return os.RemoveAll(targetDir)
}
func (m *Manager) installDir() string {
return filepath.Join(m.dataDir(), "extensions")
}
// UpdateDir returns the extension-specific directory where updates are stored.
func (m *Manager) UpdateDir(name string) string {
return filepath.Join(m.updateDir(), normalizeExtension(name))
}
//go:embed ext_tmpls/goBinMain.go.txt
var mainGoTmpl string
//go:embed ext_tmpls/goBinWorkflow.yml
var goBinWorkflow []byte
//go:embed ext_tmpls/otherBinWorkflow.yml
var otherBinWorkflow []byte
//go:embed ext_tmpls/script.sh
var scriptTmpl string
//go:embed ext_tmpls/buildScript.sh
var buildScript []byte
func (m *Manager) Create(name string, tmplType extensions.ExtTemplateType) error {
if _, err := m.gitClient.CommandOutput([]string{"init", "--quiet", name}); err != nil {
return err
}
if tmplType == extensions.GoBinTemplateType {
return m.goBinScaffolding(name)
} else if tmplType == extensions.OtherBinTemplateType {
return m.otherBinScaffolding(name)
}
script := fmt.Sprintf(scriptTmpl, name)
if err := writeFile(filepath.Join(name, name), []byte(script), 0755); err != nil {
return err
}
scopedClient := m.gitClient.ForRepo(name)
if _, err := scopedClient.CommandOutput([]string{"add", name, "--chmod=+x"}); err != nil {
return err
}
if _, err := scopedClient.CommandOutput([]string{"commit", "-m", "initial commit"}); err != nil {
return ErrInitialCommitFailed
}
return nil
}
func (m *Manager) otherBinScaffolding(name string) error {
if err := writeFile(filepath.Join(name, ".github", "workflows", "release.yml"), otherBinWorkflow, 0644); err != nil {
return err
}
buildScriptPath := filepath.Join("script", "build.sh")
if err := writeFile(filepath.Join(name, buildScriptPath), buildScript, 0755); err != nil {
return err
}
scopedClient := m.gitClient.ForRepo(name)
if _, err := scopedClient.CommandOutput([]string{"add", buildScriptPath, "--chmod=+x"}); err != nil {
return err
}
if _, err := scopedClient.CommandOutput([]string{"add", "."}); err != nil {
return err
}
if _, err := scopedClient.CommandOutput([]string{"commit", "-m", "initial commit"}); err != nil {
return ErrInitialCommitFailed
}
return nil
}
func (m *Manager) goBinScaffolding(name string) error {
goExe, err := m.lookPath("go")
if err != nil {
return fmt.Errorf("go is required for creating Go extensions: %w", err)
}
if err := writeFile(filepath.Join(name, ".github", "workflows", "release.yml"), goBinWorkflow, 0644); err != nil {
return err
}
mainGo := fmt.Sprintf(mainGoTmpl, name)
if err := writeFile(filepath.Join(name, "main.go"), []byte(mainGo), 0644); err != nil {
return err
}
host, _ := m.config.Authentication().DefaultHost()
currentUser, err := api.CurrentLoginName(api.NewClientFromHTTP(m.client), host)
if err != nil {
return err
}
goCmds := [][]string{
{"mod", "init", fmt.Sprintf("%s/%s/%s", host, currentUser, name)},
{"mod", "tidy"},
{"build"},
}
ignore := fmt.Sprintf("/%[1]s\n/%[1]s.exe\n", name)
if err := writeFile(filepath.Join(name, ".gitignore"), []byte(ignore), 0644); err != nil {
return err
}
for _, args := range goCmds {
goCmd := m.newCommand(goExe, args...)
goCmd.Dir = name
if err := goCmd.Run(); err != nil {
return fmt.Errorf("failed to set up go module: %w", err)
}
}
scopedClient := m.gitClient.ForRepo(name)
if _, err := scopedClient.CommandOutput([]string{"add", "."}); err != nil {
return err
}
if _, err := scopedClient.CommandOutput([]string{"commit", "-m", "initial commit"}); err != nil {
return ErrInitialCommitFailed
}
return nil
}
func isSymlink(m os.FileMode) bool {
return m&os.ModeSymlink != 0
}
func writeFile(p string, contents []byte, mode os.FileMode) error {
if dir := filepath.Dir(p); dir != "." {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
}
return os.WriteFile(p, contents, mode)
}
// reads the product of makeSymlink on Windows
func readPathFromFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
b := make([]byte, 1024)
n, err := f.Read(b)
return strings.TrimSpace(string(b[:n])), err
}
func isBinExtension(client *http.Client, repo ghrepo.Interface) (isBin bool, err error) {
var r *release
r, err = fetchLatestRelease(client, repo)
if err != nil {
return
}
for _, a := range r.Assets {
dists := possibleDists()
for _, d := range dists {
suffix := d
if strings.HasPrefix(d, "windows") {
suffix += ".exe"
}
if strings.HasSuffix(a.Name, suffix) {
isBin = true
break
}
}
}
return
}
func repoFromPath(gitClient gitClient, path string) (ghrepo.Interface, error) {
scopedClient := gitClient.ForRepo(path)
remotes, err := scopedClient.Remotes()
if err != nil {
return nil, err
}
if len(remotes) == 0 {
return nil, fmt.Errorf("no remotes configured for %s", path)
}
var remote *git.Remote
for _, r := range remotes {
if r.Name == "origin" {
remote = r
break
}
}
if remote == nil {
remote = remotes[0]
}
return ghrepo.FromURL(remote.FetchURL)
}
func possibleDists() []string {
return []string{
"aix-ppc64",
"android-386",
"android-amd64",
"android-arm",
"android-arm64",
"darwin-amd64",
"darwin-arm64",
"dragonfly-amd64",
"freebsd-386",
"freebsd-amd64",
"freebsd-arm",
"freebsd-arm64",
"illumos-amd64",
"ios-amd64",
"ios-arm64",
"js-wasm",
"linux-386",
"linux-amd64",
"linux-arm",
"linux-arm64",
"linux-mips",
"linux-mips64",
"linux-mips64le",
"linux-mipsle",
"linux-ppc64",
"linux-ppc64le",
"linux-riscv64",
"linux-s390x",
"netbsd-386",
"netbsd-amd64",
"netbsd-arm",
"netbsd-arm64",
"openbsd-386",
"openbsd-amd64",
"openbsd-arm",
"openbsd-arm64",
"openbsd-mips64",
"plan9-386",
"plan9-amd64",
"plan9-arm",
"solaris-amd64",
"windows-386",
"windows-amd64",
"windows-arm",
"windows-arm64",
}
}
var hasRosetta = func() bool {
_, err := os.Stat("/Library/Apple/usr/libexec/oah/libRosettaRuntime")
return err == nil
}
func codesignBinary(binPath string) error {
codesignExe, err := safeexec.LookPath("codesign")
if err != nil {
return err
}
cmd := exec.Command(codesignExe, "--sign", "-", "--force", "--preserve-metadata=entitlements,requirements,flags,runtime", binPath)
return cmd.Run()
}
// cleanExtensionUpdateDir deletes the extension-specific directory containing metadata used in checking for updates.
// Because extension names are not unique across GitHub organizations and users, we feel its important to clean up this metadata
// before installing or removing an extension with the same name to avoid confusing the extension manager based on past extensions.
//
// As of cli/cli#9934, the only effect on gh from not cleaning up metadata before installing or removing an extension are:
//
// 1. The last `checked_for_update_at` timestamp is sufficiently in the past and will check for an update on first use,
// which would happen if no extension update metadata existed.
//
// 2. The last `checked_for_update_at` timestamp is sufficiently in the future and will not check for an update,
// this is not a major concern as users could manually modify this.
//
// This could change over time as other functionality is added to extensions, which we cannot predict within cli/cli#9934,
// such as extension manifest and lock files within cli/cli#6118.
func (m *Manager) cleanExtensionUpdateDir(name string) error {
if err := os.RemoveAll(m.UpdateDir(name)); err != nil {
return fmt.Errorf("failed to remove previous extension update state: %w", err)
}
return nil
}
// normalizeExtension makes sure that the provided extension name is prefixed with "gh-".
func normalizeExtension(name string) string {
if !strings.HasPrefix(name, "gh-") {
name = "gh-" + name
}
return name
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/browse/browse.go | pkg/cmd/extension/browse/browse.go | package browse
import (
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/charmbracelet/glamour"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/search"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
"github.com/spf13/cobra"
)
const pagingOffset = 24
type ExtBrowseOpts struct {
Cmd *cobra.Command
Browser ibrowser
IO *iostreams.IOStreams
Searcher search.Searcher
Em extensions.ExtensionManager
Client *http.Client
Logger *log.Logger
Cfg gh.Config
Rg *readmeGetter
Debug bool
SingleColumn bool
}
type ibrowser interface {
Browse(string) error
}
type uiRegistry struct {
// references to some of the heavily cross-referenced tview primitives. Not
// everything is in here because most things are just used once in one place
// and don't need to be easy to look up like this.
App *tview.Application
Outerflex *tview.Flex
List *tview.List
Pages *tview.Pages
CmdFlex *tview.Flex
}
type extEntry struct {
URL string
Name string
FullName string
Installed bool
Official bool
description string
}
func (e extEntry) Title() string {
var installed string
var official string
if e.Installed {
installed = " [green](installed)"
}
if e.Official {
official = " [yellow](official)"
}
return fmt.Sprintf("%s%s%s", e.FullName, official, installed)
}
func (e extEntry) Description() string {
if e.description == "" {
return "no description provided"
}
return e.description
}
type extList struct {
ui uiRegistry
extEntries []extEntry
app *tview.Application
filter string
opts ExtBrowseOpts
QueueUpdateDraw func(func()) *tview.Application
WaitGroup wGroup
}
type wGroup interface {
Add(int)
Done()
Wait()
}
type fakeGroup struct{}
func (w *fakeGroup) Add(int) {}
func (w *fakeGroup) Done() {}
func (w *fakeGroup) Wait() {}
func newExtList(opts ExtBrowseOpts, ui uiRegistry, extEntries []extEntry) *extList {
ui.List.SetTitleColor(tcell.ColorWhite)
ui.List.SetSelectedTextColor(tcell.ColorBlack)
ui.List.SetSelectedBackgroundColor(tcell.ColorWhite)
ui.List.SetWrapAround(false)
ui.List.SetBorderPadding(1, 1, 1, 1)
ui.List.SetSelectedFunc(func(ix int, _, _ string, _ rune) {
ui.Pages.SwitchToPage("readme")
})
el := &extList{
ui: ui,
extEntries: extEntries,
app: ui.App,
opts: opts,
QueueUpdateDraw: ui.App.QueueUpdateDraw,
WaitGroup: &fakeGroup{},
}
el.Reset()
return el
}
func (el *extList) createModal() *tview.Modal {
m := tview.NewModal()
m.SetBackgroundColor(tcell.ColorPurple)
m.SetDoneFunc(func(_ int, _ string) {
el.ui.Pages.SwitchToPage("main")
el.Refresh()
})
return m
}
func (el *extList) toggleSelected(verb string) {
ee, ix := el.FindSelected()
if ix < 0 {
el.opts.Logger.Println("failed to find selected entry")
return
}
modal := el.createModal()
if (ee.Installed && verb == "install") || (!ee.Installed && verb == "remove") {
return
}
var action func() error
if !ee.Installed {
modal.SetText(fmt.Sprintf("Installing %s...", ee.FullName))
action = func() error {
repo, err := ghrepo.FromFullName(ee.FullName)
if err != nil {
el.opts.Logger.Println(fmt.Errorf("failed to install '%s': %w", ee.FullName, err))
return err
}
err = el.opts.Em.Install(repo, "")
if err != nil {
return fmt.Errorf("failed to install %s: %w", ee.FullName, err)
}
return nil
}
} else {
modal.SetText(fmt.Sprintf("Removing %s...", ee.FullName))
action = func() error {
name := strings.TrimPrefix(ee.Name, "gh-")
err := el.opts.Em.Remove(name)
if err != nil {
return fmt.Errorf("failed to remove %s: %w", ee.FullName, err)
}
return nil
}
}
el.ui.CmdFlex.Clear()
el.ui.CmdFlex.AddItem(modal, 0, 1, true)
var err error
wg := el.WaitGroup
wg.Add(1)
go func() {
el.QueueUpdateDraw(func() {
el.ui.Pages.SwitchToPage("command")
wg.Add(1)
wg.Done()
go func() {
el.QueueUpdateDraw(func() {
err = action()
if err != nil {
modal.SetText(err.Error())
} else {
modalText := fmt.Sprintf("Installed %s!", ee.FullName)
if verb == "remove" {
modalText = fmt.Sprintf("Removed %s!", ee.FullName)
}
modal.SetText(modalText)
modal.AddButtons([]string{"ok"})
el.app.SetFocus(modal)
}
wg.Done()
})
}()
})
}()
// TODO blocking the app's thread and deadlocking
wg.Wait()
if err == nil {
el.toggleInstalled(ix)
}
}
func (el *extList) InstallSelected() {
el.toggleSelected("install")
}
func (el *extList) RemoveSelected() {
el.toggleSelected("remove")
}
func (el *extList) toggleInstalled(ix int) {
ee := el.extEntries[ix]
ee.Installed = !ee.Installed
el.extEntries[ix] = ee
}
func (el *extList) Focus() {
el.app.SetFocus(el.ui.List)
}
func (el *extList) Refresh() {
el.Reset()
el.Filter(el.filter)
}
func (el *extList) Reset() {
el.ui.List.Clear()
for _, ee := range el.extEntries {
el.ui.List.AddItem(ee.Title(), ee.Description(), rune(0), func() {})
}
}
func (el *extList) PageDown() {
el.ui.List.SetCurrentItem(el.ui.List.GetCurrentItem() + pagingOffset)
}
func (el *extList) PageUp() {
i := el.ui.List.GetCurrentItem() - pagingOffset
if i < 0 {
i = 0
}
el.ui.List.SetCurrentItem(i)
}
func (el *extList) ScrollDown() {
el.ui.List.SetCurrentItem(el.ui.List.GetCurrentItem() + 1)
}
func (el *extList) ScrollUp() {
i := el.ui.List.GetCurrentItem() - 1
if i < 0 {
i = 0
}
el.ui.List.SetCurrentItem(i)
}
func (el *extList) FindSelected() (extEntry, int) {
if el.ui.List.GetItemCount() == 0 {
return extEntry{}, -1
}
title, desc := el.ui.List.GetItemText(el.ui.List.GetCurrentItem())
for x, e := range el.extEntries {
if e.Title() == title && e.Description() == desc {
return e, x
}
}
return extEntry{}, -1
}
func (el *extList) Filter(text string) {
el.filter = text
if text == "" {
return
}
el.ui.List.Clear()
for _, ee := range el.extEntries {
if strings.Contains(ee.Title()+ee.Description(), text) {
el.ui.List.AddItem(ee.Title(), ee.Description(), rune(0), func() {})
}
}
}
func getSelectedReadme(opts ExtBrowseOpts, readme *tview.TextView, el *extList) (string, error) {
ee, ix := el.FindSelected()
if ix < 0 {
return "", errors.New("failed to find selected entry")
}
fullName := ee.FullName
rm, err := opts.Rg.Get(fullName)
if err != nil {
return "", err
}
_, _, wrap, _ := readme.GetInnerRect()
// using glamour directly because if I don't horrible things happen
renderer, err := glamour.NewTermRenderer(
glamour.WithStylePath("dark"),
glamour.WithWordWrap(wrap))
if err != nil {
return "", err
}
rendered, err := renderer.Render(rm)
if err != nil {
return "", err
}
return rendered, nil
}
func getExtensions(opts ExtBrowseOpts) ([]extEntry, error) {
extEntries := []extEntry{}
installed := opts.Em.List()
result, err := opts.Searcher.Repositories(search.Query{
Kind: search.KindRepositories,
Limit: 1000,
Qualifiers: search.Qualifiers{
Topic: []string{"gh-extension"},
},
})
if err != nil {
return extEntries, fmt.Errorf("failed to search for extensions: %w", err)
}
host, _ := opts.Cfg.Authentication().DefaultHost()
for _, repo := range result.Items {
if !strings.HasPrefix(repo.Name, "gh-") {
continue
}
ee := extEntry{
URL: "https://" + host + "/" + repo.FullName,
FullName: repo.FullName,
Name: repo.Name,
description: repo.Description,
}
for _, v := range installed {
// TODO consider a Repo() on Extension interface
var installedRepo string
if u, err := git.ParseURL(v.URL()); err == nil {
if r, err := ghrepo.FromURL(u); err == nil {
installedRepo = ghrepo.FullName(r)
}
}
if repo.FullName == installedRepo {
ee.Installed = true
}
}
if repo.Owner.Login == "cli" || repo.Owner.Login == "github" {
ee.Official = true
}
extEntries = append(extEntries, ee)
}
return extEntries, nil
}
func ExtBrowse(opts ExtBrowseOpts) error {
if opts.Debug {
f, err := os.CreateTemp("", "extBrowse-*.txt")
if err != nil {
return err
}
defer os.Remove(f.Name())
opts.Logger = log.New(f, "", log.Lshortfile)
} else {
opts.Logger = log.New(io.Discard, "", 0)
}
opts.IO.StartProgressIndicator()
extEntries, err := getExtensions(opts)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
opts.Rg = newReadmeGetter(opts.Client, time.Hour*24)
app := tview.NewApplication()
outerFlex := tview.NewFlex()
innerFlex := tview.NewFlex()
header := tview.NewTextView().SetText(fmt.Sprintf("browsing %d gh extensions", len(extEntries)))
header.SetTextAlign(tview.AlignCenter).SetTextColor(tcell.ColorWhite)
filter := tview.NewInputField().SetLabel("filter: ")
filter.SetFieldBackgroundColor(tcell.ColorGray)
filter.SetBorderPadding(0, 0, 20, 20)
list := tview.NewList()
readme := tview.NewTextView()
readme.SetBorderPadding(1, 1, 0, 1)
readme.SetBorder(true).SetBorderColor(tcell.ColorPurple)
help := tview.NewTextView()
help.SetDynamicColors(true)
help.SetText("[::b]?[-:-:-]: help [::b]j/k[-:-:-]: move [::b]i[-:-:-]: install [::b]r[-:-:-]: remove [::b]w[-:-:-]: web [::b]↵[-:-:-]: view readme [::b]q[-:-:-]: quit")
cmdFlex := tview.NewFlex()
pages := tview.NewPages()
ui := uiRegistry{
App: app,
Outerflex: outerFlex,
List: list,
Pages: pages,
CmdFlex: cmdFlex,
}
extList := newExtList(opts, ui, extEntries)
loadSelectedReadme := func() {
rendered, err := getSelectedReadme(opts, readme, extList)
if err != nil {
opts.Logger.Println(err.Error())
readme.SetText("unable to fetch readme :(")
return
}
app.QueueUpdateDraw(func() {
readme.SetText("")
readme.SetDynamicColors(true)
w := tview.ANSIWriter(readme)
_, _ = w.Write([]byte(rendered))
readme.ScrollToBeginning()
})
}
filter.SetChangedFunc(func(text string) {
extList.Filter(text)
go loadSelectedReadme()
})
filter.SetDoneFunc(func(key tcell.Key) {
switch key {
case tcell.KeyEnter:
extList.Focus()
case tcell.KeyEscape:
filter.SetText("")
extList.Reset()
extList.Focus()
}
})
innerFlex.SetDirection(tview.FlexColumn)
innerFlex.AddItem(list, 0, 1, true)
if !opts.SingleColumn {
innerFlex.AddItem(readme, 0, 1, false)
}
outerFlex.SetDirection(tview.FlexRow)
outerFlex.AddItem(header, 1, -1, false)
outerFlex.AddItem(filter, 1, -1, false)
outerFlex.AddItem(innerFlex, 0, 1, true)
outerFlex.AddItem(help, 1, -1, false)
helpBig := tview.NewTextView()
helpBig.SetDynamicColors(true)
helpBig.SetBorderPadding(0, 0, 2, 0)
helpBig.SetText(heredoc.Doc(`
[::b]Application[-:-:-]
?: toggle help
q: quit
[::b]Navigation[-:-:-]
↓, j: scroll list of extensions down by 1
↑, k: scroll list of extensions up by 1
shift+j, space: scroll list of extensions down by 25
shift+k, ctrl+space (mac), shift+space (windows): scroll list of extensions up by 25
[::b]Extension Management[-:-:-]
i: install highlighted extension
r: remove highlighted extension
w: open highlighted extension in web browser
[::b]Filtering[-:-:-]
/: focus filter
enter: finish filtering and go back to list
escape: clear filter and reset list
[::b]Readmes[-:-:-]
enter: open highlighted extension's readme full screen
page down: scroll readme pane down
page up: scroll readme pane up
(On a mac, page down and page up are fn+down arrow and fn+up arrow)
`))
pages.AddPage("main", outerFlex, true, true)
pages.AddPage("help", helpBig, true, false)
pages.AddPage("readme", readme, true, false)
pages.AddPage("command", cmdFlex, true, false)
app.SetRoot(pages, true)
// Force fetching of initial readme by loading it just prior to the first
// draw. The callback is removed immediately after draw.
app.SetBeforeDrawFunc(func(_ tcell.Screen) bool {
go loadSelectedReadme()
return false // returning true would halt drawing which we do not want
})
app.SetAfterDrawFunc(func(_ tcell.Screen) {
app.SetBeforeDrawFunc(nil)
app.SetAfterDrawFunc(nil)
})
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if filter.HasFocus() {
return event
}
curPage, _ := pages.GetFrontPage()
if curPage != "main" {
if curPage == "command" {
return event
}
if event.Rune() == 'q' || event.Key() == tcell.KeyEscape {
pages.SwitchToPage("main")
return nil
}
switch curPage {
case "readme":
switch event.Key() {
case tcell.KeyPgUp:
row, col := readme.GetScrollOffset()
if row > 0 {
readme.ScrollTo(row-2, col)
}
case tcell.KeyPgDn:
row, col := readme.GetScrollOffset()
readme.ScrollTo(row+2, col)
}
case "help":
switch event.Rune() {
case '?':
pages.SwitchToPage("main")
}
}
return nil
}
switch event.Rune() {
case '?':
pages.SwitchToPage("help")
return nil
case 'q':
app.Stop()
case 'k':
extList.ScrollUp()
readme.SetText("...fetching readme...")
go loadSelectedReadme()
case 'j':
extList.ScrollDown()
readme.SetText("...fetching readme...")
go loadSelectedReadme()
case 'w':
ee, ix := extList.FindSelected()
if ix < 0 {
opts.Logger.Println("failed to find selected entry")
return nil
}
err = opts.Browser.Browse(ee.URL)
if err != nil {
opts.Logger.Println(fmt.Errorf("could not open browser for '%s': %w", ee.URL, err))
}
case 'i':
extList.InstallSelected()
case 'r':
extList.RemoveSelected()
case ' ':
// The shift check works on windows and not linux/mac:
if event.Modifiers()&tcell.ModShift != 0 {
extList.PageUp()
} else {
extList.PageDown()
}
go loadSelectedReadme()
case '/':
app.SetFocus(filter)
return nil
}
switch event.Key() {
case tcell.KeyUp:
extList.ScrollUp()
go loadSelectedReadme()
return nil
case tcell.KeyDown:
extList.ScrollDown()
go loadSelectedReadme()
return nil
case tcell.KeyEscape:
filter.SetText("")
extList.Reset()
case tcell.KeyCtrlSpace:
// The ctrl check works on linux/mac and not windows:
extList.PageUp()
go loadSelectedReadme()
case tcell.KeyCtrlJ:
extList.PageDown()
go loadSelectedReadme()
case tcell.KeyCtrlK:
extList.PageUp()
go loadSelectedReadme()
}
return event
})
if err := app.Run(); err != nil {
return err
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/browse/browse_test.go | pkg/cmd/extension/browse/browse_test.go | package browse
import (
"encoding/base64"
"io"
"log"
"net/http"
"net/url"
"sync"
"testing"
"time"
"github.com/cli/cli/v2/internal/config"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/repo/view"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/search"
"github.com/rivo/tview"
"github.com/stretchr/testify/assert"
)
func Test_getSelectedReadme(t *testing.T) {
reg := httpmock.Registry{}
defer reg.Verify(t)
content := base64.StdEncoding.EncodeToString([]byte("lol"))
reg.Register(
httpmock.REST("GET", "repos/cli/gh-cool/readme"),
httpmock.JSONResponse(view.RepoReadme{Content: content}))
client := &http.Client{Transport: ®}
rg := newReadmeGetter(client, time.Second)
opts := ExtBrowseOpts{
Rg: rg,
}
readme := tview.NewTextView()
ui := uiRegistry{
List: tview.NewList(),
}
extEntries := []extEntry{
{
Name: "gh-cool",
FullName: "cli/gh-cool",
Installed: false,
Official: true,
description: "it's just cool ok",
},
{
Name: "gh-screensaver",
FullName: "vilmibm/gh-screensaver",
Installed: true,
Official: false,
description: "animations in your terminal",
},
}
el := newExtList(opts, ui, extEntries)
content, err := getSelectedReadme(opts, readme, el)
assert.NoError(t, err)
assert.Contains(t, content, "lol")
}
func Test_getExtensionRepos(t *testing.T) {
reg := httpmock.Registry{}
defer reg.Verify(t)
client := &http.Client{Transport: ®}
values := url.Values{
"page": []string{"1"},
"per_page": []string{"100"},
"q": []string{"topic:gh-extension"},
}
cfg := config.NewBlankConfig()
cfg.AuthenticationFunc = func() gh.AuthConfig {
authCfg := &config.AuthConfig{}
authCfg.SetDefaultHost("github.com", "")
return authCfg
}
reg.Register(
httpmock.QueryMatcher("GET", "search/repositories", values),
httpmock.JSONResponse(map[string]interface{}{
"incomplete_results": false,
"total_count": 4,
"items": []interface{}{
map[string]interface{}{
"name": "gh-screensaver",
"full_name": "vilmibm/gh-screensaver",
"description": "terminal animations",
"owner": map[string]interface{}{
"login": "vilmibm",
},
},
map[string]interface{}{
"name": "gh-cool",
"full_name": "cli/gh-cool",
"description": "it's just cool ok",
"owner": map[string]interface{}{
"login": "cli",
},
},
map[string]interface{}{
"name": "gh-triage",
"full_name": "samcoe/gh-triage",
"description": "helps with triage",
"owner": map[string]interface{}{
"login": "samcoe",
},
},
map[string]interface{}{
"name": "gh-gei",
"full_name": "github/gh-gei",
"description": "something something enterprise",
"owner": map[string]interface{}{
"login": "github",
},
},
},
}),
)
searcher := search.NewSearcher(client, "github.com", &fd.DisabledDetectorMock{})
emMock := &extensions.ExtensionManagerMock{}
emMock.ListFunc = func() []extensions.Extension {
return []extensions.Extension{
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/vilmibm/gh-screensaver"
},
},
&extensions.ExtensionMock{
URLFunc: func() string {
return "https://github.com/github/gh-gei"
},
},
}
}
opts := ExtBrowseOpts{
Searcher: searcher,
Em: emMock,
Cfg: cfg,
}
extEntries, err := getExtensions(opts)
assert.NoError(t, err)
expectedEntries := []extEntry{
{
URL: "https://github.com/vilmibm/gh-screensaver",
Name: "gh-screensaver",
FullName: "vilmibm/gh-screensaver",
Installed: true,
Official: false,
description: "terminal animations",
},
{
URL: "https://github.com/cli/gh-cool",
Name: "gh-cool",
FullName: "cli/gh-cool",
Installed: false,
Official: true,
description: "it's just cool ok",
},
{
URL: "https://github.com/samcoe/gh-triage",
Name: "gh-triage",
FullName: "samcoe/gh-triage",
Installed: false,
Official: false,
description: "helps with triage",
},
{
URL: "https://github.com/github/gh-gei",
Name: "gh-gei",
FullName: "github/gh-gei",
Installed: true,
Official: true,
description: "something something enterprise",
},
}
assert.Equal(t, expectedEntries, extEntries)
}
func Test_extEntry(t *testing.T) {
cases := []struct {
name string
ee extEntry
expectedTitle string
expectedDesc string
}{
{
name: "official",
ee: extEntry{
Name: "gh-cool",
FullName: "cli/gh-cool",
Installed: false,
Official: true,
description: "it's just cool ok",
},
expectedTitle: "cli/gh-cool [yellow](official)",
expectedDesc: "it's just cool ok",
},
{
name: "no description",
ee: extEntry{
Name: "gh-nodesc",
FullName: "barryburton/gh-nodesc",
Installed: false,
Official: false,
description: "",
},
expectedTitle: "barryburton/gh-nodesc",
expectedDesc: "no description provided",
},
{
name: "installed",
ee: extEntry{
Name: "gh-screensaver",
FullName: "vilmibm/gh-screensaver",
Installed: true,
Official: false,
description: "animations in your terminal",
},
expectedTitle: "vilmibm/gh-screensaver [green](installed)",
expectedDesc: "animations in your terminal",
},
{
name: "neither",
ee: extEntry{
Name: "gh-triage",
FullName: "samcoe/gh-triage",
Installed: false,
Official: false,
description: "help with triage",
},
expectedTitle: "samcoe/gh-triage",
expectedDesc: "help with triage",
},
{
name: "both",
ee: extEntry{
Name: "gh-gei",
FullName: "github/gh-gei",
Installed: true,
Official: true,
description: "something something enterprise",
},
expectedTitle: "github/gh-gei [yellow](official) [green](installed)",
expectedDesc: "something something enterprise",
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expectedTitle, tt.ee.Title())
assert.Equal(t, tt.expectedDesc, tt.ee.Description())
})
}
}
func Test_extList(t *testing.T) {
opts := ExtBrowseOpts{
Logger: log.New(io.Discard, "", 0),
Em: &extensions.ExtensionManagerMock{
InstallFunc: func(repo ghrepo.Interface, _ string) error {
assert.Equal(t, "cli/gh-cool", ghrepo.FullName(repo))
return nil
},
RemoveFunc: func(name string) error {
assert.Equal(t, "cool", name)
return nil
},
},
}
cmdFlex := tview.NewFlex()
app := tview.NewApplication()
list := tview.NewList()
pages := tview.NewPages()
ui := uiRegistry{
List: list,
App: app,
CmdFlex: cmdFlex,
Pages: pages,
}
extEntries := []extEntry{
{
Name: "gh-cool",
FullName: "cli/gh-cool",
Installed: false,
Official: true,
description: "it's just cool ok",
},
{
Name: "gh-screensaver",
FullName: "vilmibm/gh-screensaver",
Installed: true,
Official: false,
description: "animations in your terminal",
},
{
Name: "gh-triage",
FullName: "samcoe/gh-triage",
Installed: false,
Official: false,
description: "help with triage",
},
{
Name: "gh-gei",
FullName: "github/gh-gei",
Installed: true,
Official: true,
description: "something something enterprise",
},
}
extList := newExtList(opts, ui, extEntries)
extList.QueueUpdateDraw = func(f func()) *tview.Application {
f()
return app
}
extList.WaitGroup = &sync.WaitGroup{}
extList.Filter("cool")
assert.Equal(t, 1, extList.ui.List.GetItemCount())
title, _ := extList.ui.List.GetItemText(0)
assert.Equal(t, "cli/gh-cool [yellow](official)", title)
extList.InstallSelected()
assert.True(t, extList.extEntries[0].Installed)
// so I think the goroutines are causing a later failure because the toggleInstalled isn't seen.
extList.Refresh()
assert.Equal(t, 1, extList.ui.List.GetItemCount())
title, _ = extList.ui.List.GetItemText(0)
assert.Equal(t, "cli/gh-cool [yellow](official) [green](installed)", title)
extList.RemoveSelected()
assert.False(t, extList.extEntries[0].Installed)
extList.Refresh()
assert.Equal(t, 1, extList.ui.List.GetItemCount())
title, _ = extList.ui.List.GetItemText(0)
assert.Equal(t, "cli/gh-cool [yellow](official)", title)
extList.Reset()
assert.Equal(t, 4, extList.ui.List.GetItemCount())
ee, ix := extList.FindSelected()
assert.Equal(t, 0, ix)
assert.Equal(t, "cli/gh-cool [yellow](official)", ee.Title())
extList.ScrollDown()
ee, ix = extList.FindSelected()
assert.Equal(t, 1, ix)
assert.Equal(t, "vilmibm/gh-screensaver [green](installed)", ee.Title())
extList.ScrollUp()
ee, ix = extList.FindSelected()
assert.Equal(t, 0, ix)
assert.Equal(t, "cli/gh-cool [yellow](official)", ee.Title())
extList.PageDown()
ee, ix = extList.FindSelected()
assert.Equal(t, 3, ix)
assert.Equal(t, "github/gh-gei [yellow](official) [green](installed)", ee.Title())
extList.PageUp()
ee, ix = extList.FindSelected()
assert.Equal(t, 0, ix)
assert.Equal(t, "cli/gh-cool [yellow](official)", ee.Title())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/extension/browse/rg.go | pkg/cmd/extension/browse/rg.go | package browse
import (
"net/http"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/repo/view"
)
type readmeGetter struct {
client *http.Client
}
func newReadmeGetter(client *http.Client, cacheTTL time.Duration) *readmeGetter {
cachingClient := api.NewCachedHTTPClient(client, cacheTTL)
return &readmeGetter{
client: cachingClient,
}
}
func (g *readmeGetter) Get(repoFullName string) (string, error) {
repo, err := ghrepo.FromFullName(repoFullName)
if err != nil {
return "", err
}
readme, err := view.RepositoryReadme(g.client, repo, "")
if err != nil {
return "", err
}
return readme.Content, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/auth.go | pkg/cmd/auth/auth.go | package auth
import (
gitCredentialCmd "github.com/cli/cli/v2/pkg/cmd/auth/gitcredential"
authLoginCmd "github.com/cli/cli/v2/pkg/cmd/auth/login"
authLogoutCmd "github.com/cli/cli/v2/pkg/cmd/auth/logout"
authRefreshCmd "github.com/cli/cli/v2/pkg/cmd/auth/refresh"
authSetupGitCmd "github.com/cli/cli/v2/pkg/cmd/auth/setupgit"
authStatusCmd "github.com/cli/cli/v2/pkg/cmd/auth/status"
authSwitchCmd "github.com/cli/cli/v2/pkg/cmd/auth/switch"
authTokenCmd "github.com/cli/cli/v2/pkg/cmd/auth/token"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdAuth(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "auth <command>",
Short: "Authenticate gh and git with GitHub",
GroupID: "core",
}
cmdutil.DisableAuthCheck(cmd)
cmd.AddCommand(authLoginCmd.NewCmdLogin(f, nil))
cmd.AddCommand(authLogoutCmd.NewCmdLogout(f, nil))
cmd.AddCommand(authStatusCmd.NewCmdStatus(f, nil))
cmd.AddCommand(authRefreshCmd.NewCmdRefresh(f, nil))
cmd.AddCommand(gitCredentialCmd.NewCmdCredential(f, nil))
cmd.AddCommand(authSetupGitCmd.NewCmdSetupGit(f, nil))
cmd.AddCommand(authTokenCmd.NewCmdToken(f, nil))
cmd.AddCommand(authSwitchCmd.NewCmdSwitch(f, nil))
return cmd
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/setupgit/setupgit_test.go | pkg/cmd/auth/setupgit/setupgit_test.go | package setupgit
import (
"bytes"
"errors"
"fmt"
"io"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/require"
)
type gitCredentialsConfigurerSpy struct {
hosts []string
setupErr error
}
func (gf *gitCredentialsConfigurerSpy) ConfigureOurs(hostname string) error {
gf.hosts = append(gf.hosts, hostname)
return gf.setupErr
}
func TestNewCmdSetupGit(t *testing.T) {
tests := []struct {
name string
cli string
wantsErr bool
errMsg string
}{
{
name: "--force without hostname",
cli: "--force",
wantsErr: true,
errMsg: "`--force` must be used in conjunction with `--hostname`",
},
{
name: "no error when --force used with hostname",
cli: "--force --hostname ghe.io",
wantsErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &cmdutil.Factory{}
argv, err := shlex.Split(tt.cli)
require.NoError(t, err)
cmd := NewCmdSetupGit(f, func(opts *SetupGitOptions) error {
return nil
})
// TODO cobra hack-around
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantsErr {
require.Error(t, err)
require.Equal(t, err.Error(), tt.errMsg)
return
}
require.NoError(t, err)
})
}
}
func Test_setupGitRun(t *testing.T) {
tests := []struct {
name string
opts *SetupGitOptions
setupErr error
cfgStubs func(*testing.T, gh.Config)
expectedHostsSetup []string
expectedErr error
expectedErrOut string
}{
{
name: "opts.Config returns an error",
opts: &SetupGitOptions{
Config: func() (gh.Config, error) {
return nil, fmt.Errorf("oops")
},
},
expectedErr: errors.New("oops"),
},
{
name: "when an unknown hostname is provided without forcing, return an error",
opts: &SetupGitOptions{
Hostname: "ghe.io",
},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", false)
},
expectedErr: errors.New("You are not logged into the GitHub host \"ghe.io\". Run gh auth login -h ghe.io to authenticate or provide `--force`"),
},
{
name: "when an unknown hostname is provided with forcing, set it up",
opts: &SetupGitOptions{
Hostname: "ghe.io",
Force: true,
},
expectedHostsSetup: []string{"ghe.io"},
},
{
name: "when a known hostname is provided without forcing, set it up",
opts: &SetupGitOptions{
Hostname: "ghe.io",
},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "ghe.io", "test-user", "gho_ABCDEFG", "https", false)
},
expectedHostsSetup: []string{"ghe.io"},
},
{
name: "when a hostname is provided but setting it up errors, that error is bubbled",
opts: &SetupGitOptions{
Hostname: "ghe.io",
},
setupErr: fmt.Errorf("broken"),
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "ghe.io", "test-user", "gho_ABCDEFG", "https", false)
},
expectedErr: errors.New("failed to set up git credential helper: broken"),
expectedErrOut: "",
},
{
name: "when there are no known hosts and no hostname is provided, return an error",
opts: &SetupGitOptions{},
expectedErr: cmdutil.SilentError,
expectedErrOut: "You are not logged into any GitHub hosts. Run gh auth login to authenticate.\n",
},
{
name: "when there are known hosts, and no hostname is provided, set them all up",
opts: &SetupGitOptions{},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "ghe.io", "test-user", "gho_ABCDEFG", "https", false)
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", false)
},
expectedHostsSetup: []string{"github.com", "ghe.io"},
},
{
name: "when no hostname is provided but setting one up errors, that error is bubbled",
opts: &SetupGitOptions{},
setupErr: fmt.Errorf("broken"),
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "ghe.io", "test-user", "gho_ABCDEFG", "https", false)
},
expectedErr: errors.New("failed to set up git credential helper: broken"),
expectedErrOut: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, stderr := iostreams.Test()
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
ios.SetStdoutTTY(true)
tt.opts.IO = ios
cfg, _ := config.NewIsolatedTestConfig(t)
if tt.cfgStubs != nil {
tt.cfgStubs(t, cfg)
}
if tt.opts.Config == nil {
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
}
credentialsConfigurerSpy := &gitCredentialsConfigurerSpy{setupErr: tt.setupErr}
tt.opts.CredentialsHelperConfig = credentialsConfigurerSpy
err := setupGitRun(tt.opts)
if tt.expectedErr != nil {
require.Equal(t, err, tt.expectedErr)
} else {
require.NoError(t, err)
}
if tt.expectedHostsSetup != nil {
require.Equal(t, tt.expectedHostsSetup, credentialsConfigurerSpy.hosts)
}
require.Equal(t, tt.expectedErrOut, stderr.String())
})
}
}
func login(t *testing.T, c gh.Config, hostname, username, token, gitProtocol string, secureStorage bool) {
t.Helper()
_, err := c.Authentication().Login(hostname, username, token, gitProtocol, secureStorage)
require.NoError(t, err)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/setupgit/setupgit.go | pkg/cmd/auth/setupgit/setupgit.go | package setupgit
import (
"fmt"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type gitCredentialsConfigurer interface {
ConfigureOurs(hostname string) error
}
type SetupGitOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
Hostname string
Force bool
CredentialsHelperConfig gitCredentialsConfigurer
}
func NewCmdSetupGit(f *cmdutil.Factory, runF func(*SetupGitOptions) error) *cobra.Command {
opts := &SetupGitOptions{
IO: f.IOStreams,
Config: f.Config,
}
cmd := &cobra.Command{
Use: "setup-git",
Short: "Setup git with GitHub CLI",
Long: heredoc.Docf(`
This command configures %[1]sgit%[1]s to use GitHub CLI as a credential helper.
For more information on git credential helpers please reference:
<https://git-scm.com/docs/gitcredentials>.
By default, GitHub CLI will be set as the credential helper for all authenticated hosts.
If there is no authenticated hosts the command fails with an error.
Alternatively, use the %[1]s--hostname%[1]s flag to specify a single host to be configured.
If the host is not authenticated with, the command fails with an error.
`, "`"),
Example: heredoc.Doc(`
# Configure git to use GitHub CLI as the credential helper for all authenticated hosts
$ gh auth setup-git
# Configure git to use GitHub CLI as the credential helper for enterprise.internal host
$ gh auth setup-git --hostname enterprise.internal
`),
RunE: func(cmd *cobra.Command, args []string) error {
opts.CredentialsHelperConfig = &gitcredentials.HelperConfig{
SelfExecutablePath: f.Executable(),
GitClient: f.GitClient,
}
if opts.Hostname == "" && opts.Force {
return cmdutil.FlagErrorf("`--force` must be used in conjunction with `--hostname`")
}
if runF != nil {
return runF(opts)
}
return setupGitRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname to configure git for")
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Force setup even if the host is not known. Must be used in conjunction with `--hostname`")
return cmd
}
func setupGitRun(opts *SetupGitOptions) error {
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
hostnames := authCfg.Hosts()
stderr := opts.IO.ErrOut
cs := opts.IO.ColorScheme()
// If a hostname was provided, we'll set up just that one
if opts.Hostname != "" {
if !opts.Force && !has(opts.Hostname, hostnames) {
return fmt.Errorf("You are not logged into the GitHub host %q. Run %s to authenticate or provide `--force`",
opts.Hostname,
cs.Bold(fmt.Sprintf("gh auth login -h %s", opts.Hostname)),
)
}
if err := opts.CredentialsHelperConfig.ConfigureOurs(opts.Hostname); err != nil {
return fmt.Errorf("failed to set up git credential helper: %s", err)
}
return nil
}
// Otherwise we'll set up any known hosts
if len(hostnames) == 0 {
fmt.Fprintf(
stderr,
"You are not logged into any GitHub hosts. Run %s to authenticate.\n",
cs.Bold("gh auth login"),
)
return cmdutil.SilentError
}
for _, hostname := range hostnames {
if err := opts.CredentialsHelperConfig.ConfigureOurs(hostname); err != nil {
return fmt.Errorf("failed to set up git credential helper: %s", err)
}
}
return nil
}
func has(needle string, haystack []string) bool {
for _, s := range haystack {
if strings.EqualFold(s, needle) {
return true
}
}
return false
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/login/login_test.go | pkg/cmd/auth/login/login_test.go | package login
import (
"bytes"
"fmt"
"net/http"
"regexp"
"runtime"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func stubHomeDir(t *testing.T, dir string) {
homeEnv := "HOME"
switch runtime.GOOS {
case "windows":
homeEnv = "USERPROFILE"
case "plan9":
homeEnv = "home"
}
t.Setenv(homeEnv, dir)
}
func Test_NewCmdLogin(t *testing.T) {
tests := []struct {
name string
cli string
stdin string
stdinTTY bool
defaultHost string
wants LoginOptions
wantsErr bool
}{
{
name: "nontty, with-token",
stdin: "abc123\n",
cli: "--with-token",
wants: LoginOptions{
Hostname: "github.com",
Token: "abc123",
},
},
{
name: "nontty, with-token, enterprise default host",
stdin: "abc123\n",
cli: "--with-token",
defaultHost: "git.example.com",
wants: LoginOptions{
Hostname: "git.example.com",
Token: "abc123",
},
},
{
name: "tty, with-token",
stdinTTY: true,
stdin: "def456",
cli: "--with-token",
wants: LoginOptions{
Hostname: "github.com",
Token: "def456",
},
},
{
name: "nontty, hostname",
stdinTTY: false,
cli: "--hostname claire.redfield",
wants: LoginOptions{
Hostname: "claire.redfield",
Token: "",
},
},
{
name: "nontty",
stdinTTY: false,
cli: "",
wants: LoginOptions{
Hostname: "github.com",
Token: "",
},
},
{
name: "nontty, with-token, hostname",
cli: "--hostname claire.redfield --with-token",
stdin: "abc123\n",
wants: LoginOptions{
Hostname: "claire.redfield",
Token: "abc123",
},
},
{
name: "tty, with-token, hostname",
stdinTTY: true,
stdin: "ghi789",
cli: "--with-token --hostname brad.vickers",
wants: LoginOptions{
Hostname: "brad.vickers",
Token: "ghi789",
},
},
{
name: "tty, hostname",
stdinTTY: true,
cli: "--hostname barry.burton",
wants: LoginOptions{
Hostname: "barry.burton",
Token: "",
Interactive: true,
},
},
{
name: "tty",
stdinTTY: true,
cli: "",
wants: LoginOptions{
Hostname: "",
Token: "",
Interactive: true,
},
},
{
name: "tty web and clipboard",
stdinTTY: true,
cli: "--web --clipboard",
wants: LoginOptions{
Hostname: "github.com",
Web: true,
Interactive: true,
Clipboard: true,
},
},
{
name: "nontty web and clipboard",
cli: "--web --clipboard",
wants: LoginOptions{
Hostname: "github.com",
Web: true,
Clipboard: true,
},
},
{
name: "tty web",
stdinTTY: true,
cli: "--web",
wants: LoginOptions{
Hostname: "github.com",
Web: true,
Interactive: true,
},
},
{
name: "nontty web",
cli: "--web",
wants: LoginOptions{
Hostname: "github.com",
Web: true,
},
},
{
name: "web and with-token",
cli: "--web --with-token",
wantsErr: true,
},
{
name: "tty one scope",
stdinTTY: true,
cli: "--scopes repo:invite",
wants: LoginOptions{
Hostname: "",
Scopes: []string{"repo:invite"},
Token: "",
Interactive: true,
},
},
{
name: "tty scopes",
stdinTTY: true,
cli: "--scopes repo:invite,read:public_key",
wants: LoginOptions{
Hostname: "",
Scopes: []string{"repo:invite", "read:public_key"},
Token: "",
Interactive: true,
},
},
{
name: "tty secure-storage",
stdinTTY: true,
cli: "--secure-storage",
wants: LoginOptions{
Interactive: true,
},
},
{
name: "nontty secure-storage",
cli: "--secure-storage",
wants: LoginOptions{
Hostname: "github.com",
},
},
{
name: "tty insecure-storage",
stdinTTY: true,
cli: "--insecure-storage",
wants: LoginOptions{
Interactive: true,
InsecureStorage: true,
},
},
{
name: "nontty insecure-storage",
cli: "--insecure-storage",
wants: LoginOptions{
Hostname: "github.com",
InsecureStorage: true,
},
},
{
name: "tty skip-ssh-key",
stdinTTY: true,
cli: "--skip-ssh-key",
wants: LoginOptions{
SkipSSHKeyPrompt: true,
Interactive: true,
},
},
{
name: "nontty skip-ssh-key",
cli: "--skip-ssh-key",
wants: LoginOptions{
Hostname: "github.com",
SkipSSHKeyPrompt: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Make sure there is a default host set so that
// the local configuration file never read from.
if tt.defaultHost == "" {
tt.defaultHost = "github.com"
}
t.Setenv("GH_HOST", tt.defaultHost)
ios, stdin, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
ios.SetStdoutTTY(true)
ios.SetStdinTTY(tt.stdinTTY)
if tt.stdin != "" {
stdin.WriteString(tt.stdin)
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts *LoginOptions
cmd := NewCmdLogin(f, func(opts *LoginOptions) error {
gotOpts = opts
return nil
})
// TODO cobra hack-around
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.Token, gotOpts.Token)
assert.Equal(t, tt.wants.Hostname, gotOpts.Hostname)
assert.Equal(t, tt.wants.Web, gotOpts.Web)
assert.Equal(t, tt.wants.Interactive, gotOpts.Interactive)
assert.Equal(t, tt.wants.Scopes, gotOpts.Scopes)
assert.Equal(t, tt.wants.Clipboard, gotOpts.Clipboard)
})
}
}
func Test_loginRun_nontty(t *testing.T) {
tests := []struct {
name string
opts *LoginOptions
env map[string]string
httpStubs func(*httpmock.Registry)
cfgStubs func(*testing.T, gh.Config)
wantHosts string
wantErr string
wantStderr string
wantSecureToken string
}{
{
name: "insecure with token",
opts: &LoginOptions{
Hostname: "github.com",
Token: "abc123",
InsecureStorage: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantHosts: "github.com:\n users:\n monalisa:\n oauth_token: abc123\n oauth_token: abc123\n user: monalisa\n",
},
{
name: "insecure with token and https git-protocol",
opts: &LoginOptions{
Hostname: "github.com",
Token: "abc123",
GitProtocol: "https",
InsecureStorage: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantHosts: "github.com:\n users:\n monalisa:\n oauth_token: abc123\n git_protocol: https\n oauth_token: abc123\n user: monalisa\n",
},
{
name: "with token and non-default host",
opts: &LoginOptions{
Hostname: "albert.wesker",
Token: "abc123",
InsecureStorage: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantHosts: "albert.wesker:\n users:\n monalisa:\n oauth_token: abc123\n oauth_token: abc123\n user: monalisa\n",
},
{
name: "missing repo scope",
opts: &LoginOptions{
Hostname: "github.com",
Token: "abc456",
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("read:org"))
},
wantErr: `error validating token: missing required scope 'repo'`,
},
{
name: "missing read scope",
opts: &LoginOptions{
Hostname: "github.com",
Token: "abc456",
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo"))
},
wantErr: `error validating token: missing required scope 'read:org'`,
},
{
name: "has admin scope",
opts: &LoginOptions{
Hostname: "github.com",
Token: "abc456",
InsecureStorage: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,admin:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantHosts: "github.com:\n users:\n monalisa:\n oauth_token: abc456\n oauth_token: abc456\n user: monalisa\n",
},
{
name: "github.com token from environment",
opts: &LoginOptions{
Hostname: "github.com",
Token: "abc456",
},
env: map[string]string{"GH_TOKEN": "value_from_env"},
wantErr: "SilentError",
wantStderr: heredoc.Doc(`
The value of the GH_TOKEN environment variable is being used for authentication.
To have GitHub CLI store credentials instead, first clear the value from the environment.
`),
},
{
name: "GHE token from environment",
opts: &LoginOptions{
Hostname: "ghe.io",
Token: "abc456",
},
env: map[string]string{"GH_ENTERPRISE_TOKEN": "value_from_env"},
wantErr: "SilentError",
wantStderr: heredoc.Doc(`
The value of the GH_ENTERPRISE_TOKEN environment variable is being used for authentication.
To have GitHub CLI store credentials instead, first clear the value from the environment.
`),
},
{
name: "with token and secure storage",
opts: &LoginOptions{
Hostname: "github.com",
Token: "abc123",
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantHosts: "github.com:\n users:\n monalisa:\n user: monalisa\n",
wantSecureToken: "abc123",
},
{
name: "given we are already logged in, and log in as a new user, it is added to the config",
opts: &LoginOptions{
Hostname: "github.com",
Token: "newUserToken",
},
cfgStubs: func(t *testing.T, c gh.Config) {
_, err := c.Authentication().Login("github.com", "monalisa", "abc123", "https", false)
require.NoError(t, err)
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"newUser"}}}`))
},
wantHosts: heredoc.Doc(`
github.com:
users:
monalisa:
oauth_token: abc123
newUser:
git_protocol: https
user: newUser
`),
wantSecureToken: "newUserToken",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdinTTY(false)
ios.SetStdoutTTY(false)
tt.opts.IO = ios
cfg, readConfigs := config.NewIsolatedTestConfig(t)
if tt.cfgStubs != nil {
tt.cfgStubs(t, cfg)
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
reg := &httpmock.Registry{}
defer reg.Verify(t)
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.PlainHttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
for k, v := range tt.env {
t.Setenv(k, v)
}
_, restoreRun := run.Stub()
defer restoreRun(t)
err := loginRun(tt.opts)
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
} else {
assert.NoError(t, err)
}
mainBuf := bytes.Buffer{}
hostsBuf := bytes.Buffer{}
readConfigs(&mainBuf, &hostsBuf)
secureToken, _ := cfg.Authentication().TokenFromKeyring(tt.opts.Hostname)
assert.Equal(t, "", stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
assert.Equal(t, tt.wantHosts, hostsBuf.String())
assert.Equal(t, tt.wantSecureToken, secureToken)
})
}
}
func Test_loginRun_Survey(t *testing.T) {
stubHomeDir(t, t.TempDir())
tests := []struct {
name string
opts *LoginOptions
httpStubs func(*httpmock.Registry)
prompterStubs func(*prompter.PrompterMock)
runStubs func(*run.CommandStubber)
cfgStubs func(*testing.T, gh.Config)
wantHosts string
wantErrOut *regexp.Regexp
wantSecureToken string
}{
{
name: "hostname set",
opts: &LoginOptions{
Hostname: "rebecca.chambers",
Interactive: true,
InsecureStorage: true,
},
wantHosts: heredoc.Doc(`
rebecca.chambers:
users:
jillv:
oauth_token: def456
git_protocol: https
oauth_token: def456
user: jillv
`),
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "What is your preferred protocol for Git operations on this host?":
return prompter.IndexFor(opts, "HTTPS")
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
}
},
runStubs: func(rs *run.CommandStubber) {
rs.Register(`git config credential\.https:/`, 1, "")
rs.Register(`git config credential\.helper`, 1, "")
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"jillv"}}}`))
},
wantErrOut: regexp.MustCompile("Tip: you can generate a Personal Access Token here https://rebecca.chambers/settings/tokens"),
},
{
name: "choose Other",
wantHosts: heredoc.Doc(`
brad.vickers:
users:
jillv:
oauth_token: def456
git_protocol: https
oauth_token: def456
user: jillv
`),
opts: &LoginOptions{
Interactive: true,
InsecureStorage: true,
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "Where do you use GitHub?":
return prompter.IndexFor(opts, "Other")
case "What is your preferred protocol for Git operations on this host?":
return prompter.IndexFor(opts, "HTTPS")
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
}
pm.InputHostnameFunc = func() (string, error) {
return "brad.vickers", nil
}
},
runStubs: func(rs *run.CommandStubber) {
rs.Register(`git config credential\.https:/`, 1, "")
rs.Register(`git config credential\.helper`, 1, "")
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo,read:org,read:public_key"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"jillv"}}}`))
},
wantErrOut: regexp.MustCompile("Tip: you can generate a Personal Access Token here https://brad.vickers/settings/tokens"),
},
{
name: "choose github.com",
wantHosts: heredoc.Doc(`
github.com:
users:
jillv:
oauth_token: def456
git_protocol: https
oauth_token: def456
user: jillv
`),
opts: &LoginOptions{
Interactive: true,
InsecureStorage: true,
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "Where do you use GitHub?":
return prompter.IndexFor(opts, "GitHub.com")
case "What is your preferred protocol for Git operations on this host?":
return prompter.IndexFor(opts, "HTTPS")
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
}
},
runStubs: func(rs *run.CommandStubber) {
rs.Register(`git config credential\.https:/`, 1, "")
rs.Register(`git config credential\.helper`, 1, "")
},
wantErrOut: regexp.MustCompile("Tip: you can generate a Personal Access Token here https://github.com/settings/tokens"),
},
{
name: "sets git_protocol",
wantHosts: heredoc.Doc(`
github.com:
users:
jillv:
oauth_token: def456
git_protocol: ssh
oauth_token: def456
user: jillv
`),
opts: &LoginOptions{
Interactive: true,
InsecureStorage: true,
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "Where do you use GitHub?":
return prompter.IndexFor(opts, "GitHub.com")
case "What is your preferred protocol for Git operations on this host?":
return prompter.IndexFor(opts, "SSH")
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
}
},
wantErrOut: regexp.MustCompile("Tip: you can generate a Personal Access Token here https://github.com/settings/tokens"),
},
{
name: "secure storage",
opts: &LoginOptions{
Hostname: "github.com",
Interactive: true,
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "What is your preferred protocol for Git operations on this host?":
return prompter.IndexFor(opts, "HTTPS")
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
}
},
runStubs: func(rs *run.CommandStubber) {
rs.Register(`git config credential\.https:/`, 1, "")
rs.Register(`git config credential\.helper`, 1, "")
},
wantHosts: heredoc.Doc(`
github.com:
git_protocol: https
users:
jillv:
user: jillv
`),
wantErrOut: regexp.MustCompile("Logged in as jillv"),
wantSecureToken: "def456",
},
{
name: "given we log in as a user that is already in the config, we get an informational message",
opts: &LoginOptions{
Hostname: "github.com",
Interactive: true,
InsecureStorage: true,
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "What is your preferred protocol for Git operations on this host?":
return prompter.IndexFor(opts, "HTTPS")
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
}
},
cfgStubs: func(t *testing.T, c gh.Config) {
_, err := c.Authentication().Login("github.com", "monalisa", "abc123", "https", false)
require.NoError(t, err)
},
runStubs: func(rs *run.CommandStubber) {
rs.Register(`git config credential\.https:/`, 1, "")
rs.Register(`git config credential\.helper`, 1, "")
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantHosts: heredoc.Doc(`
github.com:
users:
monalisa:
oauth_token: def456
git_protocol: https
user: monalisa
oauth_token: def456
`),
wantErrOut: regexp.MustCompile(`! You were already logged in to this account`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.opts == nil {
tt.opts = &LoginOptions{}
}
ios, _, _, stderr := iostreams.Test()
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
ios.SetStdoutTTY(true)
tt.opts.IO = ios
cfg, readConfigs := config.NewIsolatedTestConfig(t)
if tt.cfgStubs != nil {
tt.cfgStubs(t, cfg)
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
reg := &httpmock.Registry{}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.PlainHttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
if tt.httpStubs != nil {
tt.httpStubs(reg)
} else {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org,read:public_key"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"jillv"}}}`))
}
pm := &prompter.PrompterMock{}
pm.ConfirmFunc = func(_ string, _ bool) (bool, error) {
return false, nil
}
pm.AuthTokenFunc = func() (string, error) {
return "def456", nil
}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
tt.opts.Prompter = pm
tt.opts.GitClient = &git.Client{GitPath: "some/path/git"}
rs, restoreRun := run.Stub()
defer restoreRun(t)
if tt.runStubs != nil {
tt.runStubs(rs)
}
err := loginRun(tt.opts)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
mainBuf := bytes.Buffer{}
hostsBuf := bytes.Buffer{}
readConfigs(&mainBuf, &hostsBuf)
secureToken, _ := cfg.Authentication().TokenFromKeyring(tt.opts.Hostname)
assert.Equal(t, tt.wantHosts, hostsBuf.String())
assert.Equal(t, tt.wantSecureToken, secureToken)
if tt.wantErrOut == nil {
assert.Equal(t, "", stderr.String())
} else {
assert.Regexp(t, tt.wantErrOut, stderr.String())
}
reg.Verify(t)
})
}
}
func Test_promptForHostname(t *testing.T) {
tests := []struct {
name string
options []string
selectedIndex int
// This is so we can test that the options in the function don't change
expectedSelection string
inputHostname string
expect string
}{
{
name: "select 'GitHub.com'",
selectedIndex: 0,
expectedSelection: "GitHub.com",
expect: "github.com",
},
{
name: "select 'Other'",
selectedIndex: 1,
expectedSelection: "Other",
inputHostname: "github.enterprise.com",
expect: "github.enterprise.com",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
promptMock := &prompter.PrompterMock{
SelectFunc: func(_ string, _ string, options []string) (int, error) {
if options[tt.selectedIndex] != tt.expectedSelection {
return 0, fmt.Errorf("expected %s at index %d, but got %s", tt.expectedSelection, tt.selectedIndex, options[tt.selectedIndex])
}
return tt.selectedIndex, nil
},
InputHostnameFunc: func() (string, error) {
return tt.inputHostname, nil
},
}
opts := &LoginOptions{
Prompter: promptMock,
}
hostname, err := promptForHostname(opts)
require.NoError(t, err)
require.Equal(t, tt.expect, hostname)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/login/login.go | pkg/cmd/auth/login/login.go | package login
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
"github.com/spf13/cobra"
)
type LoginOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
HttpClient func() (*http.Client, error)
PlainHttpClient func() (*http.Client, error)
GitClient *git.Client
Prompter shared.Prompt
Browser browser.Browser
MainExecutable string
Interactive bool
Hostname string
Scopes []string
Token string
Web bool
GitProtocol string
InsecureStorage bool
SkipSSHKeyPrompt bool
Clipboard bool
}
func NewCmdLogin(f *cmdutil.Factory, runF func(*LoginOptions) error) *cobra.Command {
opts := &LoginOptions{
IO: f.IOStreams,
Config: f.Config,
HttpClient: f.HttpClient,
PlainHttpClient: f.PlainHttpClient,
GitClient: f.GitClient,
Prompter: f.Prompter,
Browser: f.Browser,
}
var tokenStdin bool
cmd := &cobra.Command{
Use: "login",
Args: cobra.ExactArgs(0),
Short: "Log in to a GitHub account",
Long: heredoc.Docf(`
Authenticate with a GitHub host.
The default hostname is %[1]sgithub.com%[1]s. This can be overridden using the %[1]s--hostname%[1]s
flag.
The default authentication mode is a web-based browser flow. After completion, an
authentication token will be stored securely in the system credential store.
If a credential store is not found or there is an issue using it gh will fallback
to writing the token to a plain text file. See %[1]sgh auth status%[1]s for its
stored location.
Alternatively, use %[1]s--with-token%[1]s to pass in a personal access token (classic) on standard input.
The minimum required scopes for the token are: %[1]srepo%[1]s, %[1]sread:org%[1]s, and %[1]sgist%[1]s.
Take care when passing a fine-grained personal access token to %[1]s--with-token%[1]s
as the inherent scoping to certain resources may cause confusing behaviour when interacting with other
resources. Favour setting %[1]sGH_TOKEN%[1]s for fine-grained personal access token usage.
Alternatively, gh will use the authentication token found in environment variables.
This method is most suitable for "headless" use of gh such as in automation. See
%[1]sgh help environment%[1]s for more info.
To use gh in GitHub Actions, add %[1]sGH_TOKEN: ${{ github.token }}%[1]s to %[1]senv%[1]s.
The git protocol to use for git operations on this host can be set with %[1]s--git-protocol%[1]s,
or during the interactive prompting. Although login is for a single account on a host, setting
the git protocol will take effect for all users on the host.
Specifying %[1]sssh%[1]s for the git protocol will detect existing SSH keys to upload,
prompting to create and upload a new key if one is not found. This can be skipped with
%[1]s--skip-ssh-key%[1]s flag.
For more information on OAuth scopes, see
<https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps/>.
`, "`"),
Example: heredoc.Doc(`
# Start interactive setup
$ gh auth login
# Open a browser to authenticate and copy one-time OAuth code to clipboard
$ gh auth login --web --clipboard
# Authenticate against github.com by reading the token from a file
$ gh auth login --with-token < mytoken.txt
# Authenticate with specific host
$ gh auth login --hostname enterprise.internal
`),
RunE: func(cmd *cobra.Command, args []string) error {
if tokenStdin && opts.Web {
return cmdutil.FlagErrorf("specify only one of `--web` or `--with-token`")
}
if tokenStdin && len(opts.Scopes) > 0 {
return cmdutil.FlagErrorf("specify only one of `--scopes` or `--with-token`")
}
if tokenStdin {
defer opts.IO.In.Close()
token, err := io.ReadAll(opts.IO.In)
if err != nil {
return fmt.Errorf("failed to read token from standard input: %w", err)
}
opts.Token = strings.TrimSpace(string(token))
}
if opts.IO.CanPrompt() && opts.Token == "" {
opts.Interactive = true
}
if cmd.Flags().Changed("hostname") {
if err := ghinstance.HostnameValidator(opts.Hostname); err != nil {
return cmdutil.FlagErrorf("error parsing hostname: %w", err)
}
}
if opts.Hostname == "" && (!opts.Interactive || opts.Web) {
opts.Hostname, _ = ghauth.DefaultHost()
}
opts.MainExecutable = f.Executable()
if runF != nil {
return runF(opts)
}
return loginRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname of the GitHub instance to authenticate with")
cmd.Flags().StringSliceVarP(&opts.Scopes, "scopes", "s", nil, "Additional authentication scopes to request")
cmd.Flags().BoolVar(&tokenStdin, "with-token", false, "Read token from standard input")
cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open a browser to authenticate")
cmd.Flags().BoolVarP(&opts.Clipboard, "clipboard", "c", false, "Copy one-time OAuth device code to clipboard")
cmdutil.StringEnumFlag(cmd, &opts.GitProtocol, "git-protocol", "p", "", []string{"ssh", "https"}, "The protocol to use for git operations on this host")
// secure storage became the default on 2023/4/04; this flag is left as a no-op for backwards compatibility
var secureStorage bool
cmd.Flags().BoolVar(&secureStorage, "secure-storage", false, "Save authentication credentials in secure credential store")
_ = cmd.Flags().MarkHidden("secure-storage")
cmd.Flags().BoolVar(&opts.InsecureStorage, "insecure-storage", false, "Save authentication credentials in plain text instead of credential store")
cmd.Flags().BoolVar(&opts.SkipSSHKeyPrompt, "skip-ssh-key", false, "Skip generate/upload SSH key prompt")
return cmd
}
func loginRun(opts *LoginOptions) error {
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
hostname := opts.Hostname
if opts.Interactive && hostname == "" {
var err error
hostname, err = promptForHostname(opts)
if err != nil {
return err
}
}
// The go-gh Config object currently does not support case-insensitive lookups for host names,
// so normalize the host name case here before performing any lookups with it or persisting it.
// https://github.com/cli/go-gh/pull/105
hostname = strings.ToLower(hostname)
if src, writeable := shared.AuthTokenWriteable(authCfg, hostname); !writeable {
fmt.Fprintf(opts.IO.ErrOut, "The value of the %s environment variable is being used for authentication.\n", src)
fmt.Fprint(opts.IO.ErrOut, "To have GitHub CLI store credentials instead, first clear the value from the environment.\n")
return cmdutil.SilentError
}
plainHTTPClient, err := opts.PlainHttpClient()
if err != nil {
return err
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
if opts.Token != "" {
if err := shared.HasMinimumScopes(httpClient, hostname, opts.Token); err != nil {
return fmt.Errorf("error validating token: %w", err)
}
username, err := shared.GetCurrentLogin(httpClient, hostname, opts.Token)
if err != nil {
return fmt.Errorf("error retrieving current user: %w", err)
}
// Adding a user key ensures that a nonempty host section gets written to the config file.
_, loginErr := authCfg.Login(hostname, username, opts.Token, opts.GitProtocol, !opts.InsecureStorage)
return loginErr
}
return shared.Login(&shared.LoginOptions{
IO: opts.IO,
Config: authCfg,
HTTPClient: httpClient,
PlainHTTPClient: plainHTTPClient,
Hostname: hostname,
Interactive: opts.Interactive,
Web: opts.Web,
Scopes: opts.Scopes,
GitProtocol: opts.GitProtocol,
Prompter: opts.Prompter,
Browser: opts.Browser,
CredentialFlow: &shared.GitCredentialFlow{
Prompter: opts.Prompter,
HelperConfig: &gitcredentials.HelperConfig{
SelfExecutablePath: opts.MainExecutable,
GitClient: opts.GitClient,
},
Updater: &gitcredentials.Updater{
GitClient: opts.GitClient,
},
},
SecureStorage: !opts.InsecureStorage,
SkipSSHKeyPrompt: opts.SkipSSHKeyPrompt,
CopyToClipboard: opts.Clipboard,
})
}
func promptForHostname(opts *LoginOptions) (string, error) {
options := []string{"GitHub.com", "Other"}
hostType, err := opts.Prompter.Select(
"Where do you use GitHub?",
options[0],
options)
if err != nil {
return "", err
}
isGitHubDotCom := hostType == 0
if isGitHubDotCom {
return ghinstance.Default(), nil
}
return opts.Prompter.InputHostname()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/switch/switch.go | pkg/cmd/auth/switch/switch.go | package authswitch
import (
"errors"
"fmt"
"slices"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type SwitchOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
Prompter shared.Prompt
Hostname string
Username string
}
func NewCmdSwitch(f *cmdutil.Factory, runF func(*SwitchOptions) error) *cobra.Command {
opts := SwitchOptions{
IO: f.IOStreams,
Config: f.Config,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "switch",
Args: cobra.ExactArgs(0),
Short: "Switch active GitHub account",
Long: heredoc.Docf(`
Switch the active account for a GitHub host.
This command changes the authentication configuration that will
be used when running commands targeting the specified GitHub host.
If the specified host has two accounts, the active account will be switched
automatically. If there are more than two accounts, disambiguation will be
required either through the %[1]s--user%[1]s flag or an interactive prompt.
For a list of authenticated accounts you can run %[1]sgh auth status%[1]s.
`, "`"),
Example: heredoc.Doc(`
# Select what host and account to switch to via a prompt
$ gh auth switch
# Switch the active account on a specific host to a specific user
$ gh auth switch --hostname enterprise.internal --user monalisa
`),
RunE: func(c *cobra.Command, args []string) error {
if runF != nil {
return runF(&opts)
}
return switchRun(&opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname of the GitHub instance to switch account for")
cmd.Flags().StringVarP(&opts.Username, "user", "u", "", "The account to switch to")
return cmd
}
type hostUser struct {
host string
user string
active bool
}
type candidates []hostUser
func switchRun(opts *SwitchOptions) error {
hostname := opts.Hostname
username := opts.Username
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
knownHosts := authCfg.Hosts()
if len(knownHosts) == 0 {
return fmt.Errorf("not logged in to any hosts")
}
if hostname != "" {
if !slices.Contains(knownHosts, hostname) {
return fmt.Errorf("not logged in to %s", hostname)
}
if username != "" {
knownUsers := cfg.Authentication().UsersForHost(hostname)
if !slices.Contains(knownUsers, username) {
return fmt.Errorf("not logged in to %s account %s", hostname, username)
}
}
}
var candidates candidates
for _, host := range knownHosts {
if hostname != "" && host != hostname {
continue
}
hostActiveUser, err := authCfg.ActiveUser(host)
if err != nil {
return err
}
knownUsers := cfg.Authentication().UsersForHost(host)
for _, user := range knownUsers {
if username != "" && user != username {
continue
}
candidates = append(candidates, hostUser{host: host, user: user, active: user == hostActiveUser})
}
}
if len(candidates) == 0 {
return errors.New("no accounts matched that criteria")
} else if len(candidates) == 1 {
hostname = candidates[0].host
username = candidates[0].user
} else if len(candidates) == 2 &&
candidates[0].host == candidates[1].host {
// If there is a single host with two users, automatically switch to the
// inactive user without prompting.
hostname = candidates[0].host
username = candidates[0].user
if candidates[0].active {
username = candidates[1].user
}
} else if !opts.IO.CanPrompt() {
return errors.New("unable to determine which account to switch to, please specify `--hostname` and `--user`")
} else {
prompts := make([]string, len(candidates))
for i, c := range candidates {
prompt := fmt.Sprintf("%s (%s)", c.user, c.host)
if c.active {
prompt += " - active"
}
prompts[i] = prompt
}
selected, err := opts.Prompter.Select(
"What account do you want to switch to?", "", prompts)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
hostname = candidates[selected].host
username = candidates[selected].user
}
if src, writeable := shared.AuthTokenWriteable(authCfg, hostname); !writeable {
fmt.Fprintf(opts.IO.ErrOut, "The value of the %s environment variable is being used for authentication.\n", src)
fmt.Fprint(opts.IO.ErrOut, "To have GitHub CLI manage credentials instead, first clear the value from the environment.\n")
return cmdutil.SilentError
}
cs := opts.IO.ColorScheme()
if err := authCfg.SwitchUser(hostname, username); err != nil {
fmt.Fprintf(opts.IO.ErrOut, "%s Failed to switch account for %s to %s\n",
cs.FailureIcon(), hostname, cs.Bold(username))
return err
}
fmt.Fprintf(opts.IO.ErrOut, "%s Switched active account for %s to %s\n",
cs.SuccessIcon(), hostname, cs.Bold(username))
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/switch/switch_test.go | pkg/cmd/auth/switch/switch_test.go | package authswitch
import (
"bytes"
"errors"
"fmt"
"io"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/keyring"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/require"
)
func TestNewCmdSwitch(t *testing.T) {
tests := []struct {
name string
input string
expectedOpts SwitchOptions
expectedErrMsg string
}{
{
name: "no flags",
input: "",
expectedOpts: SwitchOptions{},
},
{
name: "hostname flag",
input: "--hostname github.com",
expectedOpts: SwitchOptions{
Hostname: "github.com",
},
},
{
name: "user flag",
input: "--user monalisa",
expectedOpts: SwitchOptions{
Username: "monalisa",
},
},
{
name: "positional args is an error",
input: "some-positional-arg",
expectedErrMsg: "accepts 0 arg(s), received 1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &cmdutil.Factory{}
argv, err := shlex.Split(tt.input)
require.NoError(t, err)
var gotOpts *SwitchOptions
cmd := NewCmdSwitch(f, func(opts *SwitchOptions) error {
gotOpts = opts
return nil
})
// Override the help flag as happens in production to allow -h flag
// to be used for hostname.
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.expectedErrMsg != "" {
require.ErrorContains(t, err, tt.expectedErrMsg)
return
}
require.NoError(t, err)
require.Equal(t, &tt.expectedOpts, gotOpts)
})
}
}
func TestSwitchRun(t *testing.T) {
type user struct {
name string
token string
}
type hostUsers struct {
host string
users []user
}
type successfulExpectation struct {
switchedHost string
activeUser string
activeToken string
hostsCfg string
stderr string
}
type failedExpectation struct {
err error
stderr string
}
userWithMissingToken := "user-that-is-broken-by-the-test"
tests := []struct {
name string
opts SwitchOptions
cfgHosts []hostUsers
env map[string]string
expectedSuccess successfulExpectation
expectedFailure failedExpectation
prompterStubs func(*prompter.PrompterMock)
}{
{
name: "given one host with two users, switches to the other user",
opts: SwitchOptions{},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
expectedSuccess: successfulExpectation{
switchedHost: "github.com",
activeUser: "inactive-user",
activeToken: "inactive-user-token",
hostsCfg: "github.com:\n git_protocol: ssh\n users:\n inactive-user:\n active-user:\n user: inactive-user\n",
stderr: "✓ Switched active account for github.com to inactive-user",
},
},
{
name: "given one host, with three users, switches to the specified user",
opts: SwitchOptions{
Username: "inactive-user-2",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user-1", "inactive-user-1-token"},
{"inactive-user-2", "inactive-user-2-token"},
{"active-user", "active-user-token"},
}},
},
expectedSuccess: successfulExpectation{
switchedHost: "github.com",
activeUser: "inactive-user-2",
activeToken: "inactive-user-2-token",
hostsCfg: "github.com:\n git_protocol: ssh\n users:\n inactive-user-1:\n inactive-user-2:\n active-user:\n user: inactive-user-2\n",
stderr: "✓ Switched active account for github.com to inactive-user-2",
},
},
{
name: "given multiple hosts, with multiple users, switches to the specific user on the host",
opts: SwitchOptions{
Hostname: "ghe.io",
Username: "inactive-user",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
{"ghe.io", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
expectedSuccess: successfulExpectation{
switchedHost: "ghe.io",
activeUser: "inactive-user",
activeToken: "inactive-user-token",
hostsCfg: "github.com:\n git_protocol: ssh\n users:\n inactive-user:\n active-user:\n user: active-user\nghe.io:\n git_protocol: ssh\n users:\n inactive-user:\n active-user:\n user: inactive-user\n",
stderr: "✓ Switched active account for ghe.io to inactive-user",
},
},
{
name: "given we're not logged into any hosts, provide an informative error",
opts: SwitchOptions{},
cfgHosts: []hostUsers{},
expectedFailure: failedExpectation{
err: errors.New("not logged in to any hosts"),
},
},
{
name: "given we can't disambiguate users across hosts",
opts: SwitchOptions{
Username: "inactive-user",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
{"ghe.io", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
expectedFailure: failedExpectation{
err: errors.New("unable to determine which account to switch to, please specify `--hostname` and `--user`"),
},
},
{
name: "given we can't disambiguate user on a single host",
opts: SwitchOptions{
Hostname: "github.com",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user-1", "inactive-user-1-token"},
{"inactive-user-2", "inactive-user-2-token"},
{"active-user", "active-user-token"},
}},
},
expectedFailure: failedExpectation{
err: errors.New("unable to determine which account to switch to, please specify `--hostname` and `--user`"),
},
},
{
name: "given the auth token isn't writeable (e.g. a token env var is set)",
opts: SwitchOptions{},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
env: map[string]string{"GH_TOKEN": "unimportant-test-value"},
expectedFailure: failedExpectation{
err: cmdutil.SilentError,
stderr: "The value of the GH_TOKEN environment variable is being used for authentication.",
},
},
{
name: "specified hostname doesn't exist",
opts: SwitchOptions{
Hostname: "ghe.io",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
expectedFailure: failedExpectation{
err: errors.New("not logged in to ghe.io"),
},
},
{
name: "specified user doesn't exist on host",
opts: SwitchOptions{
Hostname: "github.com",
Username: "non-existent-user",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
expectedFailure: failedExpectation{
err: errors.New("not logged in to github.com account non-existent-user"),
},
},
{
name: "specified user doesn't exist on any host",
opts: SwitchOptions{
Username: "non-existent-user",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"active-user", "active-user-token"},
}},
{"ghe.io", []user{
{"active-user", "active-user-token"},
}},
},
expectedFailure: failedExpectation{
err: errors.New("no accounts matched that criteria"),
},
},
{
name: "when options need to be disambiguated, the user is prompted with matrix of options including active users (if possible)",
opts: SwitchOptions{},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
{"ghe.io", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
require.Equal(t, "What account do you want to switch to?", prompt)
require.Equal(t, []string{
"inactive-user (github.com)",
"active-user (github.com) - active",
"inactive-user (ghe.io)",
"active-user (ghe.io) - active",
}, opts)
return prompter.IndexFor(opts, "inactive-user (ghe.io)")
}
},
expectedSuccess: successfulExpectation{
switchedHost: "ghe.io",
activeUser: "inactive-user",
activeToken: "inactive-user-token",
hostsCfg: "github.com:\n git_protocol: ssh\n users:\n inactive-user:\n active-user:\n user: active-user\nghe.io:\n git_protocol: ssh\n users:\n inactive-user:\n active-user:\n user: inactive-user\n",
stderr: "✓ Switched active account for ghe.io to inactive-user",
},
},
{
name: "options need to be disambiguated given two hosts, one with two users",
opts: SwitchOptions{},
cfgHosts: []hostUsers{
{"github.com", []user{
{"inactive-user", "inactive-user-token"},
{"active-user", "active-user-token"},
}},
{"ghe.io", []user{
{"active-user", "active-user-token"},
}},
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
require.Equal(t, "What account do you want to switch to?", prompt)
require.Equal(t, []string{
"inactive-user (github.com)",
"active-user (github.com) - active",
"active-user (ghe.io) - active",
}, opts)
return prompter.IndexFor(opts, "inactive-user (github.com)")
}
},
expectedSuccess: successfulExpectation{
switchedHost: "github.com",
activeUser: "inactive-user",
activeToken: "inactive-user-token",
hostsCfg: "github.com:\n git_protocol: ssh\n users:\n inactive-user:\n active-user:\n user: inactive-user\nghe.io:\n git_protocol: ssh\n users:\n active-user:\n user: active-user\n",
stderr: "✓ Switched active account for github.com to inactive-user",
},
},
{
name: "when switching fails due to something other than user error, an informative message is printed to explain their new state",
opts: SwitchOptions{
Username: userWithMissingToken,
},
cfgHosts: []hostUsers{
{"github.com", []user{
{userWithMissingToken, "inactive-user-token"},
{"active-user", "active-user-token"},
}},
},
expectedFailure: failedExpectation{
err: fmt.Errorf("no token found for %s", userWithMissingToken),
stderr: fmt.Sprintf("X Failed to switch account for github.com to %s", userWithMissingToken),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, readConfigs := config.NewIsolatedTestConfig(t)
for k, v := range tt.env {
t.Setenv(k, v)
}
isInteractive := tt.prompterStubs != nil
if isInteractive {
pm := &prompter.PrompterMock{}
tt.prompterStubs(pm)
tt.opts.Prompter = pm
defer func() {
require.Len(t, pm.SelectCalls(), 1)
}()
}
for _, hostUsers := range tt.cfgHosts {
for _, user := range hostUsers.users {
_, err := cfg.Authentication().Login(
hostUsers.host,
user.name,
user.token, "ssh", true,
)
require.NoError(t, err)
if user.name == userWithMissingToken {
require.NoError(t, keyring.Delete(fmt.Sprintf("gh:%s", hostUsers.host), userWithMissingToken))
}
}
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
ios, _, _, stderr := iostreams.Test()
ios.SetStdinTTY(isInteractive)
ios.SetStdoutTTY(isInteractive)
tt.opts.IO = ios
err := switchRun(&tt.opts)
if tt.expectedFailure.err != nil {
require.Equal(t, tt.expectedFailure.err, err)
require.Contains(t, stderr.String(), tt.expectedFailure.stderr)
return
}
require.NoError(t, err)
activeUser, err := cfg.Authentication().ActiveUser(tt.expectedSuccess.switchedHost)
require.NoError(t, err)
require.Equal(t, tt.expectedSuccess.activeUser, activeUser)
activeToken, _ := cfg.Authentication().TokenFromKeyring(tt.expectedSuccess.switchedHost)
require.Equal(t, tt.expectedSuccess.activeToken, activeToken)
hostsBuf := bytes.Buffer{}
readConfigs(io.Discard, &hostsBuf)
require.Equal(t, tt.expectedSuccess.hostsCfg, hostsBuf.String())
require.Contains(t, stderr.String(), tt.expectedSuccess.stderr)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/refresh/refresh.go | pkg/cmd/auth/refresh/refresh.go | package refresh
import (
"fmt"
"net/http"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/authflow"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/set"
"github.com/spf13/cobra"
)
type token string
type username string
type RefreshOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
PlainHttpClient func() (*http.Client, error)
GitClient *git.Client
Prompter shared.Prompt
MainExecutable string
Hostname string
Scopes []string
RemoveScopes []string
ResetScopes bool
AuthFlow func(*http.Client, *iostreams.IOStreams, string, []string, bool, bool) (token, username, error)
Interactive bool
InsecureStorage bool
Clipboard bool
}
func NewCmdRefresh(f *cmdutil.Factory, runF func(*RefreshOptions) error) *cobra.Command {
opts := &RefreshOptions{
IO: f.IOStreams,
Config: f.Config,
AuthFlow: func(httpClient *http.Client, io *iostreams.IOStreams, hostname string, scopes []string, interactive bool, clipboard bool) (token, username, error) {
t, u, err := authflow.AuthFlow(httpClient, hostname, io, "", scopes, interactive, f.Browser, clipboard)
return token(t), username(u), err
},
PlainHttpClient: f.PlainHttpClient,
GitClient: f.GitClient,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "refresh",
Args: cobra.ExactArgs(0),
Short: "Refresh stored authentication credentials",
Long: heredoc.Docf(`
Expand or fix the permission scopes for stored credentials for active account.
The %[1]s--scopes%[1]s flag accepts a comma separated list of scopes you want
your gh credentials to have. If no scopes are provided, the command
maintains previously added scopes.
The %[1]s--remove-scopes%[1]s flag accepts a comma separated list of scopes you
want to remove from your gh credentials. Scope removal is idempotent.
The minimum set of scopes (%[1]srepo%[1]s, %[1]sread:org%[1]s, and %[1]sgist%[1]s) cannot be removed.
The %[1]s--reset-scopes%[1]s flag resets the scopes for your gh credentials to
the default set of scopes for your auth flow.
If you have multiple accounts in %[1]sgh auth status%[1]s and want to refresh the credentials for an
inactive account, you will have to use %[1]sgh auth switch%[1]s to that account first before using
this command, and then switch back when you are done.
For more information on OAuth scopes, see
<https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps/>.
`, "`"),
Example: heredoc.Doc(`
# Open a browser to add write:org and read:public_key scopes
$ gh auth refresh --scopes write:org,read:public_key
# Open a browser to ensure your authentication credentials have the correct minimum scopes
$ gh auth refresh
# Open a browser to idempotently remove the delete_repo scope
$ gh auth refresh --remove-scopes delete_repo
# Open a browser to re-authenticate with the default minimum scopes
$ gh auth refresh --reset-scopes
# Open a browser to re-authenticate and copy one-time OAuth code to clipboard
$ gh auth refresh --clipboard
`),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Interactive = opts.IO.CanPrompt()
if !opts.Interactive && opts.Hostname == "" {
return cmdutil.FlagErrorf("--hostname required when not running interactively")
}
opts.MainExecutable = f.Executable()
if runF != nil {
return runF(opts)
}
return refreshRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The GitHub host to use for authentication")
cmd.Flags().StringSliceVarP(&opts.Scopes, "scopes", "s", nil, "Additional authentication scopes for gh to have")
cmd.Flags().StringSliceVarP(&opts.RemoveScopes, "remove-scopes", "r", nil, "Authentication scopes to remove from gh")
cmd.Flags().BoolVar(&opts.ResetScopes, "reset-scopes", false, "Reset authentication scopes to the default minimum set of scopes")
cmd.Flags().BoolVarP(&opts.Clipboard, "clipboard", "c", false, "Copy one-time OAuth device code to clipboard")
// secure storage became the default on 2023/4/04; this flag is left as a no-op for backwards compatibility
var secureStorage bool
cmd.Flags().BoolVar(&secureStorage, "secure-storage", false, "Save authentication credentials in secure credential store")
_ = cmd.Flags().MarkHidden("secure-storage")
cmd.Flags().BoolVarP(&opts.InsecureStorage, "insecure-storage", "", false, "Save authentication credentials in plain text instead of credential store")
return cmd
}
func refreshRun(opts *RefreshOptions) error {
plainHTTPClient, err := opts.PlainHttpClient()
if err != nil {
return err
}
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
candidates := authCfg.Hosts()
if len(candidates) == 0 {
return fmt.Errorf("not logged in to any hosts. Use 'gh auth login' to authenticate with a host")
}
hostname := opts.Hostname
if hostname == "" {
if len(candidates) == 1 {
hostname = candidates[0]
} else {
selected, err := opts.Prompter.Select("What account do you want to refresh auth for?", "", candidates)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
hostname = candidates[selected]
}
} else {
var found bool
for _, c := range candidates {
if c == hostname {
found = true
break
}
}
if !found {
return fmt.Errorf("not logged in to %s. use 'gh auth login' to authenticate with this host", hostname)
}
}
if src, writeable := shared.AuthTokenWriteable(authCfg, hostname); !writeable {
fmt.Fprintf(opts.IO.ErrOut, "The value of the %s environment variable is being used for authentication.\n", src)
fmt.Fprint(opts.IO.ErrOut, "To refresh credentials stored in GitHub CLI, first clear the value from the environment.\n")
return cmdutil.SilentError
}
additionalScopes := set.NewStringSet()
if !opts.ResetScopes {
if oldToken, _ := authCfg.ActiveToken(hostname); oldToken != "" {
if oldScopes, err := shared.GetScopes(plainHTTPClient, hostname, oldToken); err == nil {
for _, s := range strings.Split(oldScopes, ",") {
s = strings.TrimSpace(s)
if s != "" {
additionalScopes.Add(s)
}
}
}
}
}
credentialFlow := &shared.GitCredentialFlow{
Prompter: opts.Prompter,
HelperConfig: &gitcredentials.HelperConfig{
SelfExecutablePath: opts.MainExecutable,
GitClient: opts.GitClient,
},
Updater: &gitcredentials.Updater{
GitClient: opts.GitClient,
},
}
gitProtocol := cfg.GitProtocol(hostname).Value
if opts.Interactive && gitProtocol == "https" {
if err := credentialFlow.Prompt(hostname); err != nil {
return err
}
additionalScopes.AddValues(credentialFlow.Scopes())
}
additionalScopes.AddValues(opts.Scopes)
additionalScopes.RemoveValues(opts.RemoveScopes)
authedToken, authedUser, err := opts.AuthFlow(plainHTTPClient, opts.IO, hostname, additionalScopes.ToSlice(), opts.Interactive, opts.Clipboard)
if err != nil {
return err
}
activeUser, _ := authCfg.ActiveUser(hostname)
if activeUser != "" && username(activeUser) != authedUser {
return fmt.Errorf("error refreshing credentials for %s, received credentials for %s, did you use the correct account in the browser?", activeUser, authedUser)
}
if _, err := authCfg.Login(hostname, string(authedUser), string(authedToken), "", !opts.InsecureStorage); err != nil {
return err
}
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.ErrOut, "%s Authentication complete.\n", cs.SuccessIcon())
if credentialFlow.ShouldSetup() {
username, _ := authCfg.ActiveUser(hostname)
password, _ := authCfg.ActiveToken(hostname)
if err := credentialFlow.Setup(hostname, username, password); err != nil {
return err
}
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/refresh/refresh_test.go | pkg/cmd/auth/refresh/refresh_test.go | package refresh
import (
"bytes"
"io"
"net/http"
"strings"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/require"
)
func Test_NewCmdRefresh(t *testing.T) {
tests := []struct {
name string
cli string
wants RefreshOptions
wantsErr bool
tty bool
neverPrompt bool
}{
{
name: "tty no arguments",
tty: true,
wants: RefreshOptions{
Hostname: "",
},
},
{
name: "tty clipboard",
tty: true,
cli: "-c",
wants: RefreshOptions{
Hostname: "",
Clipboard: true,
},
},
{
name: "nontty no arguments",
wantsErr: true,
},
{
name: "nontty hostname and clipboard",
cli: "-h aline.cedrac -c",
wants: RefreshOptions{
Hostname: "aline.cedrac",
Clipboard: true,
},
},
{
name: "nontty hostname",
cli: "-h aline.cedrac",
wants: RefreshOptions{
Hostname: "aline.cedrac",
},
},
{
name: "tty hostname and clipboard",
tty: true,
cli: "-h aline.cedrac -c",
wants: RefreshOptions{
Hostname: "aline.cedrac",
Clipboard: true,
},
},
{
name: "tty hostname",
tty: true,
cli: "-h aline.cedrac",
wants: RefreshOptions{
Hostname: "aline.cedrac",
},
},
{
name: "prompts disabled, no args",
tty: true,
cli: "",
neverPrompt: true,
wantsErr: true,
},
{
name: "prompts disabled, hostname",
tty: true,
cli: "-h aline.cedrac",
neverPrompt: true,
wants: RefreshOptions{
Hostname: "aline.cedrac",
},
},
{
name: "tty one scope",
tty: true,
cli: "--scopes repo:invite",
wants: RefreshOptions{
Scopes: []string{"repo:invite"},
},
},
{
name: "tty scopes",
tty: true,
cli: "--scopes repo:invite,read:public_key",
wants: RefreshOptions{
Scopes: []string{"repo:invite", "read:public_key"},
},
},
{
name: "secure storage",
tty: true,
cli: "--secure-storage",
wants: RefreshOptions{},
},
{
name: "insecure storage",
tty: true,
cli: "--insecure-storage",
wants: RefreshOptions{
InsecureStorage: true,
},
},
{
name: "reset scopes",
tty: true,
cli: "--reset-scopes",
wants: RefreshOptions{
ResetScopes: true,
},
},
{
name: "remove scope",
tty: true,
cli: "--remove-scopes read:public_key",
wants: RefreshOptions{
RemoveScopes: []string{"read:public_key"},
},
},
{
name: "remove multiple scopes",
tty: true,
cli: "--remove-scopes workflow,read:public_key",
wants: RefreshOptions{
RemoveScopes: []string{"workflow", "read:public_key"},
},
},
{
name: "remove scope shorthand",
tty: true,
cli: "-r read:public_key",
wants: RefreshOptions{
RemoveScopes: []string{"read:public_key"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
ios.SetStdinTTY(tt.tty)
ios.SetStdoutTTY(tt.tty)
ios.SetNeverPrompt(tt.neverPrompt)
argv, err := shlex.Split(tt.cli)
require.NoError(t, err)
var gotOpts *RefreshOptions
cmd := NewCmdRefresh(f, func(opts *RefreshOptions) error {
gotOpts = opts
return nil
})
// TODO cobra hack-around
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsErr {
require.Error(t, err)
return
}
require.NoError(t, err)
require.Equal(t, tt.wants.Hostname, gotOpts.Hostname)
require.Equal(t, tt.wants.Scopes, gotOpts.Scopes)
require.Equal(t, tt.wants.Clipboard, gotOpts.Clipboard)
})
}
}
type authArgs struct {
hostname string
scopes []string
interactive bool
clipboard bool
secureStorage bool
}
type authOut struct {
username string
token string
err error
}
func Test_refreshRun(t *testing.T) {
tests := []struct {
name string
opts *RefreshOptions
prompterStubs func(*prompter.PrompterMock)
cfgHosts []string
authOut authOut
oldScopes string
wantErr string
nontty bool
wantAuthArgs authArgs
}{
{
name: "no hosts configured",
opts: &RefreshOptions{},
wantErr: `not logged in to any hosts`,
},
{
name: "hostname given but not previously authenticated with it",
cfgHosts: []string{
"github.com",
"aline.cedrac",
},
opts: &RefreshOptions{
Hostname: "obed.morton",
},
wantErr: `not logged in to obed.morton`,
},
{
name: "hostname provided and is configured",
cfgHosts: []string{
"obed.morton",
"github.com",
},
opts: &RefreshOptions{
Hostname: "obed.morton",
},
wantAuthArgs: authArgs{
hostname: "obed.morton",
scopes: []string{},
secureStorage: true,
},
},
{
name: "no hostname, one host configured, clipboard enabled",
cfgHosts: []string{
"github.com",
},
opts: &RefreshOptions{
Hostname: "",
Clipboard: true,
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{},
secureStorage: true,
clipboard: true,
},
},
{
name: "no hostname, one host configured",
cfgHosts: []string{
"github.com",
},
opts: &RefreshOptions{
Hostname: "",
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{},
secureStorage: true,
},
},
{
name: "no hostname, multiple hosts configured",
cfgHosts: []string{
"github.com",
"aline.cedrac",
},
opts: &RefreshOptions{
Hostname: "",
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "github.com")
}
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{},
secureStorage: true,
},
},
{
name: "scopes provided",
cfgHosts: []string{
"github.com",
},
opts: &RefreshOptions{
Scopes: []string{"repo:invite", "public_key:read"},
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{"repo:invite", "public_key:read"},
secureStorage: true,
},
},
{
name: "more scopes provided",
cfgHosts: []string{
"github.com",
},
oldScopes: "delete_repo, codespace",
opts: &RefreshOptions{
Scopes: []string{"repo:invite", "public_key:read"},
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{"delete_repo", "codespace", "repo:invite", "public_key:read"},
secureStorage: true,
},
},
{
name: "secure storage",
cfgHosts: []string{
"obed.morton",
},
opts: &RefreshOptions{
Hostname: "obed.morton",
},
wantAuthArgs: authArgs{
hostname: "obed.morton",
scopes: []string{},
secureStorage: true,
},
},
{
name: "insecure storage",
cfgHosts: []string{
"obed.morton",
},
opts: &RefreshOptions{
Hostname: "obed.morton",
InsecureStorage: true,
},
wantAuthArgs: authArgs{
hostname: "obed.morton",
scopes: []string{},
},
},
{
name: "reset scopes",
cfgHosts: []string{
"github.com",
},
oldScopes: "delete_repo, codespace",
opts: &RefreshOptions{
Hostname: "github.com",
ResetScopes: true,
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{},
secureStorage: true,
},
},
{
name: "reset scopes and add some scopes",
cfgHosts: []string{
"github.com",
},
oldScopes: "repo:invite, delete_repo, codespace",
opts: &RefreshOptions{
Scopes: []string{"public_key:read", "workflow"},
ResetScopes: true,
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{"public_key:read", "workflow"},
secureStorage: true,
},
},
{
name: "remove scopes",
cfgHosts: []string{
"github.com",
},
oldScopes: "delete_repo, codespace, repo:invite, public_key:read",
opts: &RefreshOptions{
Hostname: "github.com",
RemoveScopes: []string{"delete_repo", "repo:invite"},
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{"codespace", "public_key:read"},
secureStorage: true,
},
},
{
name: "remove scope but no old scope",
cfgHosts: []string{
"github.com",
},
opts: &RefreshOptions{
Hostname: "github.com",
RemoveScopes: []string{"delete_repo"},
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{},
secureStorage: true,
},
},
{
name: "remove and add scopes at the same time",
cfgHosts: []string{
"github.com",
},
oldScopes: "repo:invite, delete_repo, codespace",
opts: &RefreshOptions{
Scopes: []string{"repo:invite", "public_key:read", "workflow"},
RemoveScopes: []string{"codespace", "repo:invite", "workflow"},
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{"delete_repo", "public_key:read"},
secureStorage: true,
},
},
{
name: "remove scopes that don't exist",
cfgHosts: []string{
"github.com",
},
oldScopes: "repo:invite, delete_repo, codespace",
opts: &RefreshOptions{
RemoveScopes: []string{"codespace", "repo:invite", "public_key:read"},
},
wantAuthArgs: authArgs{
hostname: "github.com",
scopes: []string{"delete_repo"},
secureStorage: true,
},
},
{
name: "errors when active user does not match user returned by auth flow",
cfgHosts: []string{
"github.com",
},
authOut: authOut{
username: "not-test-user",
token: "xyz456",
},
opts: &RefreshOptions{},
wantErr: "error refreshing credentials for test-user, received credentials for not-test-user, did you use the correct account in the browser?",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
aa := authArgs{}
tt.opts.AuthFlow = func(_ *http.Client, _ *iostreams.IOStreams, hostname string, scopes []string, interactive bool, clipboard bool) (token, username, error) {
aa.hostname = hostname
aa.scopes = scopes
aa.interactive = interactive
aa.clipboard = clipboard
if tt.authOut != (authOut{}) {
return token(tt.authOut.token), username(tt.authOut.username), tt.authOut.err
}
return token("xyz456"), username("test-user"), nil
}
cfg, _ := config.NewIsolatedTestConfig(t)
for _, hostname := range tt.cfgHosts {
_, err := cfg.Authentication().Login(hostname, "test-user", "abc123", "https", false)
require.NoError(t, err)
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
ios, _, _, _ := iostreams.Test()
ios.SetStdinTTY(!tt.nontty)
ios.SetStdoutTTY(!tt.nontty)
tt.opts.IO = ios
httpReg := &httpmock.Registry{}
httpReg.Register(
httpmock.REST("GET", ""),
func(req *http.Request) (*http.Response, error) {
statusCode := 200
if req.Header.Get("Authorization") != "token abc123" {
statusCode = 400
}
return &http.Response{
Request: req,
StatusCode: statusCode,
Body: io.NopCloser(strings.NewReader(``)),
Header: http.Header{
"X-Oauth-Scopes": {tt.oldScopes},
},
}, nil
},
)
tt.opts.PlainHttpClient = func() (*http.Client, error) {
return &http.Client{Transport: httpReg}, nil
}
pm := &prompter.PrompterMock{}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
tt.opts.Prompter = pm
err := refreshRun(tt.opts)
if tt.wantErr != "" {
require.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
require.Equal(t, tt.wantAuthArgs.hostname, aa.hostname)
require.Equal(t, tt.wantAuthArgs.scopes, aa.scopes)
require.Equal(t, tt.wantAuthArgs.interactive, aa.interactive)
require.Equal(t, tt.wantAuthArgs.clipboard, aa.clipboard)
authCfg := cfg.Authentication()
activeUser, _ := authCfg.ActiveUser(aa.hostname)
activeToken, _ := authCfg.ActiveToken(aa.hostname)
require.Equal(t, "test-user", activeUser)
require.Equal(t, "xyz456", activeToken)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/token/token_test.go | pkg/cmd/auth/token/token_test.go | package token
import (
"bytes"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/require"
)
func TestNewCmdToken(t *testing.T) {
tests := []struct {
name string
input string
output TokenOptions
wantErr bool
wantErrMsg string
}{
{
name: "no flags",
input: "",
output: TokenOptions{},
},
{
name: "with hostname",
input: "--hostname github.mycompany.com",
output: TokenOptions{Hostname: "github.mycompany.com"},
},
{
name: "with user",
input: "--user test-user",
output: TokenOptions{Username: "test-user"},
},
{
name: "with shorthand user",
input: "-u test-user",
output: TokenOptions{Username: "test-user"},
},
{
name: "with shorthand hostname",
input: "-h github.mycompany.com",
output: TokenOptions{Hostname: "github.mycompany.com"},
},
{
name: "with secure-storage",
input: "--secure-storage",
output: TokenOptions{SecureStorage: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
Config: func() (gh.Config, error) {
cfg := config.NewBlankConfig()
return cfg, nil
},
}
argv, err := shlex.Split(tt.input)
require.NoError(t, err)
var cmdOpts *TokenOptions
cmd := NewCmdToken(f, func(opts *TokenOptions) error {
cmdOpts = opts
return nil
})
// TODO cobra hack-around
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantErr {
require.Error(t, err)
require.EqualError(t, err, tt.wantErrMsg)
return
}
require.NoError(t, err)
require.Equal(t, tt.output.Hostname, cmdOpts.Hostname)
require.Equal(t, tt.output.SecureStorage, cmdOpts.SecureStorage)
})
}
}
func TestTokenRun(t *testing.T) {
tests := []struct {
name string
opts TokenOptions
env map[string]string
cfgStubs func(*testing.T, gh.Config)
wantStdout string
wantErr bool
wantErrMsg string
}{
{
name: "token",
opts: TokenOptions{},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", false)
},
wantStdout: "gho_ABCDEFG\n",
},
{
name: "token by hostname",
opts: TokenOptions{
Hostname: "github.mycompany.com",
},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", false)
login(t, cfg, "github.mycompany.com", "test-user", "gho_1234567", "https", false)
},
wantStdout: "gho_1234567\n",
},
{
name: "no token",
opts: TokenOptions{},
wantErr: true,
wantErrMsg: "no oauth token found for github.com",
},
{
name: "no token for hostname user",
opts: TokenOptions{
Hostname: "ghe.io",
Username: "test-user",
},
wantErr: true,
wantErrMsg: "no oauth token found for ghe.io account test-user",
},
{
name: "uses default host when one is not provided",
opts: TokenOptions{},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", false)
login(t, cfg, "github.mycompany.com", "test-user", "gho_1234567", "https", false)
},
env: map[string]string{"GH_HOST": "github.mycompany.com"},
wantStdout: "gho_1234567\n",
},
{
name: "token for user",
opts: TokenOptions{
Hostname: "github.com",
Username: "test-user",
},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", false)
login(t, cfg, "github.com", "test-user-2", "gho_1234567", "https", false)
},
wantStdout: "gho_ABCDEFG\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, _ := iostreams.Test()
tt.opts.IO = ios
for k, v := range tt.env {
t.Setenv(k, v)
}
cfg, _ := config.NewIsolatedTestConfig(t)
if tt.cfgStubs != nil {
tt.cfgStubs(t, cfg)
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
err := tokenRun(&tt.opts)
if tt.wantErr {
require.Error(t, err)
require.EqualError(t, err, tt.wantErrMsg)
return
}
require.NoError(t, err)
require.Equal(t, tt.wantStdout, stdout.String())
})
}
}
func TestTokenRunSecureStorage(t *testing.T) {
tests := []struct {
name string
opts TokenOptions
cfgStubs func(*testing.T, gh.Config)
wantStdout string
wantErr bool
wantErrMsg string
}{
{
name: "token",
opts: TokenOptions{},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", true)
},
wantStdout: "gho_ABCDEFG\n",
},
{
name: "token by hostname",
opts: TokenOptions{
Hostname: "mycompany.com",
},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "mycompany.com", "test-user", "gho_1234567", "https", true)
},
wantStdout: "gho_1234567\n",
},
{
name: "no token",
opts: TokenOptions{},
wantErr: true,
wantErrMsg: "no oauth token found for github.com",
},
{
name: "no token for hostname user",
opts: TokenOptions{
Hostname: "ghe.io",
Username: "test-user",
},
wantErr: true,
wantErrMsg: "no oauth token found for ghe.io account test-user",
},
{
name: "token for user",
opts: TokenOptions{
Hostname: "github.com",
Username: "test-user",
},
cfgStubs: func(t *testing.T, cfg gh.Config) {
login(t, cfg, "github.com", "test-user", "gho_ABCDEFG", "https", true)
login(t, cfg, "github.com", "test-user-2", "gho_1234567", "https", true)
},
wantStdout: "gho_ABCDEFG\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, _ := iostreams.Test()
tt.opts.IO = ios
tt.opts.SecureStorage = true
cfg, _ := config.NewIsolatedTestConfig(t)
if tt.cfgStubs != nil {
tt.cfgStubs(t, cfg)
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
err := tokenRun(&tt.opts)
if tt.wantErr {
require.Error(t, err)
require.EqualError(t, err, tt.wantErrMsg)
return
}
require.NoError(t, err)
require.Equal(t, tt.wantStdout, stdout.String())
})
}
}
func login(t *testing.T, c gh.Config, hostname, username, token, gitProtocol string, secureStorage bool) {
t.Helper()
_, err := c.Authentication().Login(hostname, username, token, gitProtocol, secureStorage)
require.NoError(t, err)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/token/token.go | pkg/cmd/auth/token/token.go | package token
import (
"errors"
"fmt"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type TokenOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
Hostname string
Username string
SecureStorage bool
}
func NewCmdToken(f *cmdutil.Factory, runF func(*TokenOptions) error) *cobra.Command {
opts := &TokenOptions{
IO: f.IOStreams,
Config: f.Config,
}
cmd := &cobra.Command{
Use: "token",
Short: "Print the authentication token gh uses for a hostname and account",
Long: heredoc.Docf(`
This command outputs the authentication token for an account on a given GitHub host.
Without the %[1]s--hostname%[1]s flag, the default host is chosen.
Without the %[1]s--user%[1]s flag, the active account for the host is chosen.
`, "`"),
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
if runF != nil {
return runF(opts)
}
return tokenRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname of the GitHub instance authenticated with")
cmd.Flags().StringVarP(&opts.Username, "user", "u", "", "The account to output the token for")
cmd.Flags().BoolVarP(&opts.SecureStorage, "secure-storage", "", false, "Search only secure credential store for authentication token")
_ = cmd.Flags().MarkHidden("secure-storage")
return cmd
}
func tokenRun(opts *TokenOptions) error {
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
hostname := opts.Hostname
if hostname == "" {
hostname, _ = authCfg.DefaultHost()
}
var val string
// If this conditional logic ends up being duplicated anywhere,
// we should consider making a factory function that returns the correct
// behavior. For now, keeping it all inline is simplest.
if opts.SecureStorage {
if opts.Username == "" {
val, _ = authCfg.TokenFromKeyring(hostname)
} else {
val, _ = authCfg.TokenFromKeyringForUser(hostname, opts.Username)
}
} else {
if opts.Username == "" {
val, _ = authCfg.ActiveToken(hostname)
} else {
val, _, _ = authCfg.TokenForUser(hostname, opts.Username)
}
}
if val == "" {
errMsg := fmt.Sprintf("no oauth token found for %s", hostname)
if opts.Username != "" {
errMsg += fmt.Sprintf(" account %s", opts.Username)
}
return errors.New(errMsg)
}
if val != "" {
fmt.Fprintf(opts.IO.Out, "%s\n", val)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/logout/logout.go | pkg/cmd/auth/logout/logout.go | package logout
import (
"errors"
"fmt"
"slices"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type LogoutOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
Prompter shared.Prompt
Hostname string
Username string
}
func NewCmdLogout(f *cmdutil.Factory, runF func(*LogoutOptions) error) *cobra.Command {
opts := &LogoutOptions{
IO: f.IOStreams,
Config: f.Config,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "logout",
Args: cobra.ExactArgs(0),
Short: "Log out of a GitHub account",
Long: heredoc.Doc(`
Remove authentication for a GitHub account.
This command removes the stored authentication configuration
for an account. The authentication configuration is only
removed locally.
This command does not revoke authentication tokens.
To revoke all authentication tokens generated by the GitHub CLI:
1. Visit <https://github.com/settings/applications>
2. Select the "GitHub CLI" application
3. Select "Revoke Access"
4. Select "I understand, revoke access"
Note: this procedure will revoke all authentication tokens ever
generated by the GitHub CLI across all your devices.
For more information about revoking OAuth application tokens, see:
<https://docs.github.com/en/apps/oauth-apps/using-oauth-apps/reviewing-your-authorized-oauth-apps>
`),
Example: heredoc.Doc(`
# Select what host and account to log out of via a prompt
$ gh auth logout
# Log out of a specific host and specific account
$ gh auth logout --hostname enterprise.internal --user monalisa
`),
RunE: func(cmd *cobra.Command, args []string) error {
if runF != nil {
return runF(opts)
}
return logoutRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname of the GitHub instance to log out of")
cmd.Flags().StringVarP(&opts.Username, "user", "u", "", "The account to log out of")
return cmd
}
func logoutRun(opts *LogoutOptions) error {
hostname := opts.Hostname
username := opts.Username
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
knownHosts := authCfg.Hosts()
if len(knownHosts) == 0 {
return fmt.Errorf("not logged in to any hosts")
}
if hostname != "" {
if !slices.Contains(knownHosts, hostname) {
return fmt.Errorf("not logged in to %s", hostname)
}
if username != "" {
knownUsers := cfg.Authentication().UsersForHost(hostname)
if !slices.Contains(knownUsers, username) {
return fmt.Errorf("not logged in to %s account %s", hostname, username)
}
}
}
type hostUser struct {
host string
user string
}
var candidates []hostUser
for _, host := range knownHosts {
if hostname != "" && host != hostname {
continue
}
knownUsers := cfg.Authentication().UsersForHost(host)
for _, user := range knownUsers {
if username != "" && user != username {
continue
}
candidates = append(candidates, hostUser{host: host, user: user})
}
}
if len(candidates) == 0 {
return errors.New("no accounts matched that criteria")
} else if len(candidates) == 1 {
hostname = candidates[0].host
username = candidates[0].user
} else if !opts.IO.CanPrompt() {
return errors.New("unable to determine which account to log out of, please specify `--hostname` and `--user`")
} else {
prompts := make([]string, len(candidates))
for i, c := range candidates {
prompts[i] = fmt.Sprintf("%s (%s)", c.user, c.host)
}
selected, err := opts.Prompter.Select(
"What account do you want to log out of?", "", prompts)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
hostname = candidates[selected].host
username = candidates[selected].user
}
if src, writeable := shared.AuthTokenWriteable(authCfg, hostname); !writeable {
fmt.Fprintf(opts.IO.ErrOut, "The value of the %s environment variable is being used for authentication.\n", src)
fmt.Fprint(opts.IO.ErrOut, "To erase credentials stored in GitHub CLI, first clear the value from the environment.\n")
return cmdutil.SilentError
}
// We can ignore the error here because a host must always have an active user
preLogoutActiveUser, _ := authCfg.ActiveUser(hostname)
if err := authCfg.Logout(hostname, username); err != nil {
return err
}
postLogoutActiveUser, _ := authCfg.ActiveUser(hostname)
hasSwitchedToNewUser := preLogoutActiveUser != postLogoutActiveUser &&
postLogoutActiveUser != ""
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.ErrOut, "%s Logged out of %s account %s\n",
cs.SuccessIcon(), hostname, cs.Bold(username))
if hasSwitchedToNewUser {
fmt.Fprintf(opts.IO.ErrOut, "%s Switched active account for %s to %s\n",
cs.SuccessIcon(), hostname, cs.Bold(postLogoutActiveUser))
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/logout/logout_test.go | pkg/cmd/auth/logout/logout_test.go | package logout
import (
"bytes"
"io"
"regexp"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/require"
)
func Test_NewCmdLogout(t *testing.T) {
tests := []struct {
name string
cli string
wants LogoutOptions
tty bool
}{
{
name: "nontty no arguments",
cli: "",
wants: LogoutOptions{},
},
{
name: "tty no arguments",
tty: true,
cli: "",
wants: LogoutOptions{},
},
{
name: "tty with hostname",
tty: true,
cli: "--hostname github.com",
wants: LogoutOptions{
Hostname: "github.com",
},
},
{
name: "nontty with hostname",
cli: "--hostname github.com",
wants: LogoutOptions{
Hostname: "github.com",
},
},
{
name: "tty with user",
tty: true,
cli: "--user monalisa",
wants: LogoutOptions{
Username: "github.com",
},
},
{
name: "nontty with user",
cli: "--user monalisa",
wants: LogoutOptions{
Username: "github.com",
},
},
{
name: "tty with hostname and user",
tty: true,
cli: "--hostname github.com --user monalisa",
wants: LogoutOptions{
Hostname: "github.com",
Username: "monalisa",
},
},
{
name: "nontty with hostname and user",
cli: "--hostname github.com --user monalisa",
wants: LogoutOptions{
Hostname: "github.com",
Username: "monalisa",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
ios.SetStdinTTY(tt.tty)
ios.SetStdoutTTY(tt.tty)
argv, err := shlex.Split(tt.cli)
require.NoError(t, err)
var gotOpts *LogoutOptions
cmd := NewCmdLogout(f, func(opts *LogoutOptions) error {
gotOpts = opts
return nil
})
// TODO cobra hack-around
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
require.NoError(t, err)
require.Equal(t, tt.wants.Hostname, gotOpts.Hostname)
})
}
}
type user struct {
name string
token string
}
type hostUsers struct {
host string
users []user
}
type tokenAssertion func(t *testing.T, cfg gh.Config)
func Test_logoutRun_tty(t *testing.T) {
tests := []struct {
name string
opts *LogoutOptions
prompterStubs func(*prompter.PrompterMock)
cfgHosts []hostUsers
secureStorage bool
wantHosts string
assertToken tokenAssertion
wantErrOut *regexp.Regexp
wantErr string
}{
{
name: "logs out prompted user when multiple known hosts with one user each",
opts: &LogoutOptions{},
cfgHosts: []hostUsers{
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
}},
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "monalisa (github.com)")
}
},
assertToken: hasNoToken("github.com"),
wantHosts: "ghe.io:\n users:\n monalisa-ghe:\n oauth_token: abc123\n git_protocol: ssh\n oauth_token: abc123\n user: monalisa-ghe\n",
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "logs out prompted user when multiple known hosts with multiple users each",
opts: &LogoutOptions{},
cfgHosts: []hostUsers{
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
{"monalisa-ghe2", "abc123"},
}},
{"github.com", []user{
{"monalisa", "monalisa-token"},
{"monalisa2", "monalisa2-token"},
}},
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "monalisa (github.com)")
}
},
assertToken: hasActiveToken("github.com", "monalisa2-token"),
wantHosts: "ghe.io:\n users:\n monalisa-ghe:\n oauth_token: abc123\n monalisa-ghe2:\n oauth_token: abc123\n git_protocol: ssh\n user: monalisa-ghe2\n oauth_token: abc123\ngithub.com:\n users:\n monalisa2:\n oauth_token: monalisa2-token\n git_protocol: ssh\n user: monalisa2\n oauth_token: monalisa2-token\n",
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "logs out only logged in user",
opts: &LogoutOptions{},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantHosts: "{}\n",
assertToken: hasNoToken("github.com"),
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "logs out prompted user when one known host with multiple users",
opts: &LogoutOptions{},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "monalisa-token"},
{"monalisa2", "monalisa2-token"},
}},
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "monalisa (github.com)")
}
},
wantHosts: "github.com:\n users:\n monalisa2:\n oauth_token: monalisa2-token\n git_protocol: ssh\n user: monalisa2\n oauth_token: monalisa2-token\n",
assertToken: hasActiveToken("github.com", "monalisa2-token"),
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "logs out specified user when multiple known hosts with one user each",
opts: &LogoutOptions{
Hostname: "ghe.io",
Username: "monalisa-ghe",
},
cfgHosts: []hostUsers{
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
}},
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantHosts: "github.com:\n users:\n monalisa:\n oauth_token: abc123\n git_protocol: ssh\n oauth_token: abc123\n user: monalisa\n",
assertToken: hasNoToken("ghe.io"),
wantErrOut: regexp.MustCompile(`Logged out of ghe.io account monalisa-ghe`),
},
{
name: "logs out specified user that is using secure storage",
secureStorage: true,
opts: &LogoutOptions{
Hostname: "github.com",
Username: "monalisa",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantHosts: "{}\n",
assertToken: hasNoToken("github.com"),
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "errors when no known hosts",
opts: &LogoutOptions{},
wantErr: `not logged in to any hosts`,
},
{
name: "errors when specified host is not a known host",
opts: &LogoutOptions{
Hostname: "ghe.io",
Username: "monalisa-ghe",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantErr: "not logged in to ghe.io",
},
{
name: "errors when specified user is not logged in on specified host",
opts: &LogoutOptions{
Hostname: "ghe.io",
Username: "unknown-user",
},
cfgHosts: []hostUsers{
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
}},
},
wantErr: "not logged in to ghe.io account unknown-user",
},
{
name: "errors when user is specified but doesn't exist on any host",
opts: &LogoutOptions{
Username: "unknown-user",
},
cfgHosts: []hostUsers{
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
}},
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantErr: "no accounts matched that criteria",
},
{
name: "switches user if there is another one available",
opts: &LogoutOptions{
Hostname: "github.com",
Username: "monalisa2",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "monalisa-token"},
{"monalisa2", "monalisa2-token"},
}},
},
wantHosts: "github.com:\n users:\n monalisa:\n oauth_token: monalisa-token\n git_protocol: ssh\n user: monalisa\n oauth_token: monalisa-token\n",
assertToken: hasActiveToken("github.com", "monalisa-token"),
wantErrOut: regexp.MustCompile("✓ Switched active account for github.com to monalisa"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, readConfigs := config.NewIsolatedTestConfig(t)
for _, hostUsers := range tt.cfgHosts {
for _, user := range hostUsers.users {
_, _ = cfg.Authentication().Login(
string(hostUsers.host),
user.name,
user.token, "ssh", tt.secureStorage,
)
}
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
ios, _, _, stderr := iostreams.Test()
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
tt.opts.IO = ios
pm := &prompter.PrompterMock{}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
tt.opts.Prompter = pm
err := logoutRun(tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
if tt.wantErrOut == nil {
require.Equal(t, "", stderr.String())
} else {
require.True(t, tt.wantErrOut.MatchString(stderr.String()), stderr.String())
}
hostsBuf := bytes.Buffer{}
readConfigs(io.Discard, &hostsBuf)
require.Equal(t, tt.wantHosts, hostsBuf.String())
if tt.assertToken != nil {
tt.assertToken(t, cfg)
}
})
}
}
func Test_logoutRun_nontty(t *testing.T) {
tests := []struct {
name string
opts *LogoutOptions
cfgHosts []hostUsers
secureStorage bool
wantHosts string
assertToken tokenAssertion
wantErrOut *regexp.Regexp
wantErr string
}{
{
name: "logs out specified user when one known host",
opts: &LogoutOptions{
Hostname: "github.com",
Username: "monalisa",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantHosts: "{}\n",
assertToken: hasNoToken("github.com"),
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "logs out specified user when multiple known hosts",
opts: &LogoutOptions{
Hostname: "github.com",
Username: "monalisa",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
}},
},
wantHosts: "ghe.io:\n users:\n monalisa-ghe:\n oauth_token: abc123\n git_protocol: ssh\n oauth_token: abc123\n user: monalisa-ghe\n",
assertToken: hasNoToken("github.com"),
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "logs out specified user that is using secure storage",
secureStorage: true,
opts: &LogoutOptions{
Hostname: "github.com",
Username: "monalisa",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantHosts: "{}\n",
assertToken: hasNoToken("github.com"),
wantErrOut: regexp.MustCompile(`Logged out of github.com account monalisa`),
},
{
name: "errors when no known hosts",
opts: &LogoutOptions{
Hostname: "github.com",
Username: "monalisa",
},
wantErr: `not logged in to any hosts`,
},
{
name: "errors when specified host is not a known host",
opts: &LogoutOptions{
Hostname: "ghe.io",
Username: "monalisa-ghe",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
},
wantErr: "not logged in to ghe.io",
},
{
name: "errors when specified user is not logged in on specified host",
opts: &LogoutOptions{
Hostname: "ghe.io",
Username: "unknown-user",
},
cfgHosts: []hostUsers{
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
}},
},
wantErr: "not logged in to ghe.io account unknown-user",
},
{
name: "errors when host is specified but user is ambiguous",
opts: &LogoutOptions{
Hostname: "ghe.io",
},
cfgHosts: []hostUsers{
{"ghe.io", []user{
{"monalisa-ghe", "abc123"},
{"monalisa-ghe2", "abc123"},
}},
},
wantErr: "unable to determine which account to log out of, please specify `--hostname` and `--user`",
},
{
name: "errors when user is specified but host is ambiguous",
opts: &LogoutOptions{
Username: "monalisa",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "abc123"},
}},
{"ghe.io", []user{
{"monalisa", "abc123"},
}},
},
wantErr: "unable to determine which account to log out of, please specify `--hostname` and `--user`",
},
{
name: "switches user if there is another one available",
opts: &LogoutOptions{
Hostname: "github.com",
Username: "monalisa2",
},
cfgHosts: []hostUsers{
{"github.com", []user{
{"monalisa", "monalisa-token"},
{"monalisa2", "monalisa2-token"},
}},
},
wantHosts: "github.com:\n users:\n monalisa:\n oauth_token: monalisa-token\n git_protocol: ssh\n user: monalisa\n oauth_token: monalisa-token\n",
assertToken: hasActiveToken("github.com", "monalisa-token"),
wantErrOut: regexp.MustCompile("✓ Switched active account for github.com to monalisa"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, readConfigs := config.NewIsolatedTestConfig(t)
for _, hostUsers := range tt.cfgHosts {
for _, user := range hostUsers.users {
_, _ = cfg.Authentication().Login(
string(hostUsers.host),
user.name,
user.token, "ssh", tt.secureStorage,
)
}
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
ios, _, _, stderr := iostreams.Test()
ios.SetStdinTTY(false)
ios.SetStdoutTTY(false)
tt.opts.IO = ios
err := logoutRun(tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
if tt.wantErrOut == nil {
require.Equal(t, "", stderr.String())
} else {
require.True(t, tt.wantErrOut.MatchString(stderr.String()), stderr.String())
}
hostsBuf := bytes.Buffer{}
readConfigs(io.Discard, &hostsBuf)
require.Equal(t, tt.wantHosts, hostsBuf.String())
if tt.assertToken != nil {
tt.assertToken(t, cfg)
}
})
}
}
func hasNoToken(hostname string) tokenAssertion {
return func(t *testing.T, cfg gh.Config) {
t.Helper()
token, _ := cfg.Authentication().ActiveToken(hostname)
require.Empty(t, token)
}
}
func hasActiveToken(hostname string, expectedToken string) tokenAssertion {
return func(t *testing.T, cfg gh.Config) {
t.Helper()
token, _ := cfg.Authentication().ActiveToken(hostname)
require.Equal(t, expectedToken, token)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/status/status.go | pkg/cmd/auth/status/status.go | package status
import (
"errors"
"fmt"
"net"
"net/http"
"path/filepath"
"slices"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type authEntryState string
const (
authEntryStateSuccess = "success"
authEntryStateTimeout = "timeout"
authEntryStateError = "error"
)
type authEntry struct {
State authEntryState `json:"state"`
Error string `json:"error,omitempty"`
Active bool `json:"active"`
Host string `json:"host"`
Login string `json:"login"`
TokenSource string `json:"tokenSource"`
Token string `json:"token,omitempty"`
Scopes string `json:"scopes,omitempty"`
GitProtocol string `json:"gitProtocol"`
}
type authStatus struct {
Hosts map[string][]authEntry `json:"hosts"`
}
func newAuthStatus() *authStatus {
return &authStatus{
Hosts: make(map[string][]authEntry),
}
}
var authStatusFields = []string{
"hosts",
}
func (a authStatus) ExportData(fields []string) map[string]interface{} {
return cmdutil.StructExportData(a, fields)
}
func (e authEntry) String(cs *iostreams.ColorScheme) string {
var sb strings.Builder
switch e.State {
case authEntryStateSuccess:
sb.WriteString(
fmt.Sprintf(" %s Logged in to %s account %s (%s)\n", cs.SuccessIcon(), e.Host, cs.Bold(e.Login), e.TokenSource),
)
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
sb.WriteString(fmt.Sprintf(" - Git operations protocol: %s\n", cs.Bold(e.GitProtocol)))
sb.WriteString(fmt.Sprintf(" - Token: %s\n", cs.Bold(e.Token)))
if expectScopes(e.Token) {
sb.WriteString(fmt.Sprintf(" - Token scopes: %s\n", cs.Bold(displayScopes(e.Scopes))))
if err := shared.HeaderHasMinimumScopes(e.Scopes); err != nil {
var missingScopesError *shared.MissingScopesError
if errors.As(err, &missingScopesError) {
missingScopes := strings.Join(missingScopesError.MissingScopes, ",")
sb.WriteString(fmt.Sprintf(" %s Missing required token scopes: %s\n",
cs.WarningIcon(),
cs.Bold(displayScopes(missingScopes))))
refreshInstructions := fmt.Sprintf("gh auth refresh -h %s", e.Host)
sb.WriteString(fmt.Sprintf(" - To request missing scopes, run: %s\n", cs.Bold(refreshInstructions)))
}
}
}
case authEntryStateError:
if e.Login != "" {
sb.WriteString(fmt.Sprintf(" %s Failed to log in to %s account %s (%s)\n", cs.Red("X"), e.Host, cs.Bold(e.Login), e.TokenSource))
} else {
sb.WriteString(fmt.Sprintf(" %s Failed to log in to %s using token (%s)\n", cs.Red("X"), e.Host, e.TokenSource))
}
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
sb.WriteString(fmt.Sprintf(" - The token in %s is invalid.\n", e.TokenSource))
if authTokenWriteable(e.TokenSource) {
loginInstructions := fmt.Sprintf("gh auth login -h %s", e.Host)
logoutInstructions := fmt.Sprintf("gh auth logout -h %s -u %s", e.Host, e.Login)
sb.WriteString(fmt.Sprintf(" - To re-authenticate, run: %s\n", cs.Bold(loginInstructions)))
sb.WriteString(fmt.Sprintf(" - To forget about this account, run: %s\n", cs.Bold(logoutInstructions)))
}
case authEntryStateTimeout:
if e.Login != "" {
sb.WriteString(fmt.Sprintf(" %s Timeout trying to log in to %s account %s (%s)\n", cs.Red("X"), e.Host, cs.Bold(e.Login), e.TokenSource))
} else {
sb.WriteString(fmt.Sprintf(" %s Timeout trying to log in to %s using token (%s)\n", cs.Red("X"), e.Host, e.TokenSource))
}
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
}
return sb.String()
}
type StatusOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Config func() (gh.Config, error)
Exporter cmdutil.Exporter
Hostname string
ShowToken bool
Active bool
}
func NewCmdStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobra.Command {
opts := &StatusOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
Config: f.Config,
}
cmd := &cobra.Command{
Use: "status",
Args: cobra.ExactArgs(0),
Short: "Display active account and authentication state on each known GitHub host",
Long: heredoc.Docf(`
Display active account and authentication state on each known GitHub host.
For each host, the authentication state of each known account is tested and any issues are included in the output.
Each host section will indicate the active account, which will be used when targeting that host.
If an account on any host (or only the one given via %[1]s--hostname%[1]s) has authentication issues,
the command will exit with 1 and output to stderr. Note that when using the %[1]s--json%[1]s option, the command
will always exit with zero regardless of any authentication issues, unless there is a fatal error.
To change the active account for a host, see %[1]sgh auth switch%[1]s.
`, "`"),
Example: heredoc.Doc(`
# Display authentication status for all accounts on all hosts
$ gh auth status
# Display authentication status for the active account on a specific host
$ gh auth status --active --hostname github.example.com
# Display tokens in plain text
$ gh auth status --show-token
# Format authentication status as JSON
$ gh auth status --json hosts
# Include plain text token in JSON output
$ gh auth status --json hosts --show-token
# Format hosts as a flat JSON array
$ gh auth status --json hosts --jq '.hosts | add'
`),
RunE: func(cmd *cobra.Command, args []string) error {
if runF != nil {
return runF(opts)
}
return statusRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "Check only a specific hostname's auth status")
cmd.Flags().BoolVarP(&opts.ShowToken, "show-token", "t", false, "Display the auth token")
cmd.Flags().BoolVarP(&opts.Active, "active", "a", false, "Display the active account only")
// the json flags are intentionally not given a shorthand to avoid conflict with -t/--show-token
cmdutil.AddJSONFlagsWithoutShorthand(cmd, &opts.Exporter, authStatusFields)
return cmd
}
func statusRun(opts *StatusOptions) error {
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
stderr := opts.IO.ErrOut
stdout := opts.IO.Out
cs := opts.IO.ColorScheme()
hostnames := authCfg.Hosts()
if len(hostnames) == 0 {
fmt.Fprintf(stderr,
"You are not logged into any GitHub hosts. To log in, run: %s\n", cs.Bold("gh auth login"))
if opts.Exporter != nil {
// In machine-friendly mode, we always exit with no error.
opts.Exporter.Write(opts.IO, newAuthStatus())
return nil
}
return cmdutil.SilentError
}
if opts.Hostname != "" && !slices.Contains(hostnames, opts.Hostname) {
fmt.Fprintf(stderr,
"You are not logged into any accounts on %s\n", opts.Hostname)
if opts.Exporter != nil {
// In machine-friendly mode, we always exit with no error.
opts.Exporter.Write(opts.IO, newAuthStatus())
return nil
}
return cmdutil.SilentError
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
var finalErr error
statuses := newAuthStatus()
for _, hostname := range hostnames {
if opts.Hostname != "" && opts.Hostname != hostname {
continue
}
var activeUser string
gitProtocol := cfg.GitProtocol(hostname).Value
activeUserToken, activeUserTokenSource := authCfg.ActiveToken(hostname)
if authTokenWriteable(activeUserTokenSource) {
activeUser, _ = authCfg.ActiveUser(hostname)
}
entry := buildEntry(httpClient, buildEntryOptions{
active: true,
gitProtocol: gitProtocol,
hostname: hostname,
token: activeUserToken,
tokenSource: activeUserTokenSource,
username: activeUser,
})
statuses.Hosts[hostname] = append(statuses.Hosts[hostname], entry)
if finalErr == nil && entry.State != authEntryStateSuccess {
finalErr = cmdutil.SilentError
}
if opts.Active {
continue
}
users := authCfg.UsersForHost(hostname)
for _, username := range users {
if username == activeUser {
continue
}
token, tokenSource, _ := authCfg.TokenForUser(hostname, username)
entry := buildEntry(httpClient, buildEntryOptions{
active: false,
gitProtocol: gitProtocol,
hostname: hostname,
token: token,
tokenSource: tokenSource,
username: username,
})
statuses.Hosts[hostname] = append(statuses.Hosts[hostname], entry)
if finalErr == nil && entry.State != authEntryStateSuccess {
finalErr = cmdutil.SilentError
}
}
}
if !opts.ShowToken {
for _, host := range statuses.Hosts {
for i := range host {
if opts.Exporter != nil {
// In machine-readable we just drop the token
host[i].Token = ""
} else {
host[i].Token = maskToken(host[i].Token)
}
}
}
}
if opts.Exporter != nil {
// In machine-friendly mode, we always exit with no error.
opts.Exporter.Write(opts.IO, statuses)
return nil
}
prevEntry := false
for _, hostname := range hostnames {
entries, ok := statuses.Hosts[hostname]
if !ok {
continue
}
stream := stdout
if finalErr != nil {
stream = stderr
}
if prevEntry {
fmt.Fprint(stream, "\n")
}
prevEntry = true
fmt.Fprintf(stream, "%s\n", cs.Bold(hostname))
for i, entry := range entries {
fmt.Fprintf(stream, "%s", entry.String(cs))
if i < len(entries)-1 {
fmt.Fprint(stream, "\n")
}
}
}
return finalErr
}
func maskToken(token string) string {
if idx := strings.LastIndexByte(token, '_'); idx > -1 {
prefix := token[0 : idx+1]
return prefix + strings.Repeat("*", len(token)-len(prefix))
}
return strings.Repeat("*", len(token))
}
func displayScopes(scopes string) string {
if scopes == "" {
return "none"
}
list := strings.Split(scopes, ",")
for i, s := range list {
list[i] = fmt.Sprintf("'%s'", strings.TrimSpace(s))
}
return strings.Join(list, ", ")
}
func expectScopes(token string) bool {
return strings.HasPrefix(token, "ghp_") || strings.HasPrefix(token, "gho_")
}
type buildEntryOptions struct {
active bool
gitProtocol string
hostname string
token string
tokenSource string
username string
}
func buildEntry(httpClient *http.Client, opts buildEntryOptions) authEntry {
tokenSource := opts.tokenSource
if tokenSource == "oauth_token" {
// The go-gh function TokenForHost returns this value as source for tokens read from the
// config file, but we want the file path instead. This attempts to reconstruct it.
tokenSource = filepath.Join(config.ConfigDir(), "hosts.yml")
}
entry := authEntry{
Active: opts.active,
Host: opts.hostname,
Login: opts.username,
TokenSource: tokenSource,
Token: opts.token,
GitProtocol: opts.gitProtocol,
}
// If token is not writeable, then it came from an environment variable and
// we need to fetch the username as it won't be stored in the config.
if !authTokenWriteable(tokenSource) {
// The httpClient will automatically use the correct token here as
// the token from the environment variable take highest precedence.
apiClient := api.NewClientFromHTTP(httpClient)
var err error
entry.Login, err = api.CurrentLoginName(apiClient, opts.hostname)
if err != nil {
entry.State = authEntryStateError
entry.Error = err.Error()
return entry
}
}
// Get scopes for token.
scopesHeader, err := shared.GetScopes(httpClient, opts.hostname, opts.token)
if err != nil {
var networkError net.Error
if errors.As(err, &networkError) && networkError.Timeout() {
entry.State = authEntryStateTimeout
entry.Error = err.Error()
return entry
}
entry.State = authEntryStateError
entry.Error = err.Error()
return entry
}
entry.Scopes = scopesHeader
entry.State = authEntryStateSuccess
return entry
}
func authTokenWriteable(src string) bool {
return !strings.HasSuffix(src, "_TOKEN")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/status/status_test.go | pkg/cmd/auth/status/status_test.go | package status
import (
"bytes"
"context"
"encoding/json"
"net/http"
"path/filepath"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/jsonfieldstest"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdStatus(t *testing.T) {
tests := []struct {
name string
cli string
wants StatusOptions
}{
{
name: "no arguments",
cli: "",
wants: StatusOptions{},
},
{
name: "hostname set",
cli: "--hostname ellie.williams",
wants: StatusOptions{
Hostname: "ellie.williams",
},
},
{
name: "show token",
cli: "--show-token",
wants: StatusOptions{
ShowToken: true,
},
},
{
name: "active",
cli: "--active",
wants: StatusOptions{
Active: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &cmdutil.Factory{}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts *StatusOptions
cmd := NewCmdStatus(f, func(opts *StatusOptions) error {
gotOpts = opts
return nil
})
// TODO cobra hack-around
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
assert.NoError(t, err)
assert.Equal(t, tt.wants.Hostname, gotOpts.Hostname)
assert.Equal(t, tt.wants.ShowToken, gotOpts.ShowToken)
assert.Equal(t, tt.wants.Active, gotOpts.Active)
})
}
}
func TestJSONFields(t *testing.T) {
jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdStatus, []string{
"hosts",
})
}
func Test_statusRun(t *testing.T) {
tests := []struct {
name string
opts StatusOptions
jsonFields []string
env map[string]string
httpStubs func(*httpmock.Registry)
cfgStubs func(*testing.T, gh.Config)
wantErr error
wantOut string
wantErrOut string
}{
{
name: "timeout error",
opts: StatusOptions{
Hostname: "github.com",
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), func(req *http.Request) (*http.Response, error) {
// timeout error
return nil, context.DeadlineExceeded
})
},
wantErr: cmdutil.SilentError,
wantErrOut: heredoc.Doc(`
github.com
X Timeout trying to log in to github.com account monalisa (GH_CONFIG_DIR/hosts.yml)
- Active account: true
`),
},
{
name: "hostname set",
opts: StatusOptions{
Hostname: "ghe.io",
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo,read:org"))
},
wantOut: heredoc.Doc(`
ghe.io
✓ Logged in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
`),
},
{
name: "missing scope",
opts: StatusOptions{},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo"))
},
wantOut: heredoc.Doc(`
ghe.io
✓ Logged in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo'
! Missing required token scopes: 'read:org'
- To request missing scopes, run: gh auth refresh -h ghe.io
`),
},
{
name: "bad token",
opts: StatusOptions{},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mock for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.StatusStringResponse(400, "no bueno"))
},
wantErr: cmdutil.SilentError,
wantErrOut: heredoc.Doc(`
ghe.io
X Failed to log in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- The token in GH_CONFIG_DIR/hosts.yml is invalid.
- To re-authenticate, run: gh auth login -h ghe.io
- To forget about this account, run: gh auth logout -h ghe.io -u monalisa-ghe
`),
},
{
name: "bad token on other host",
opts: StatusOptions{
Hostname: "ghe.io",
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
},
wantOut: heredoc.Doc(`
ghe.io
✓ Logged in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
`),
},
{
name: "bad token on selected host",
opts: StatusOptions{
Hostname: "ghe.io",
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.StatusStringResponse(400, "no bueno"))
},
wantErr: cmdutil.SilentError,
wantErrOut: heredoc.Doc(`
ghe.io
X Failed to log in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- The token in GH_CONFIG_DIR/hosts.yml is invalid.
- To re-authenticate, run: gh auth login -h ghe.io
- To forget about this account, run: gh auth logout -h ghe.io -u monalisa-ghe
`),
},
{
name: "all good",
opts: StatusOptions{},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "ssh")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to github.com
reg.Register(
httpmock.REST("GET", ""),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
// mocks for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(
httpmock.REST("GET", "api/v3/"),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", ""))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
ghe.io
✓ Logged in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: ssh
- Token: gho_******
- Token scopes: none
`),
},
{
name: "token from env",
opts: StatusOptions{},
env: map[string]string{"GH_TOKEN": "gho_abc123"},
cfgStubs: func(t *testing.T, c gh.Config) {},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", ""),
httpmock.ScopesResponder(""))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa (GH_TOKEN)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: none
`),
},
{
name: "server-to-server token",
opts: StatusOptions{},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "ghs_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to github.com
reg.Register(
httpmock.REST("GET", ""),
httpmock.ScopesResponder(""))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: ghs_******
`),
},
{
name: "PAT V2 token",
opts: StatusOptions{},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "github_pat_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to github.com
reg.Register(
httpmock.REST("GET", ""),
httpmock.ScopesResponder(""))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: github_pat_******
`),
},
{
name: "show token",
opts: StatusOptions{
ShowToken: true,
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_xyz456", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes on a non-github.com host
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo,read:org"))
// mocks for HeaderHasMinimumScopes on github.com
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_abc123
- Token scopes: 'repo', 'read:org'
ghe.io
✓ Logged in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_xyz456
- Token scopes: 'repo', 'read:org'
`),
},
{
name: "missing hostname",
opts: StatusOptions{
Hostname: "github.example.com",
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {},
wantErr: cmdutil.SilentError,
wantErrOut: "You are not logged into any accounts on github.example.com\n",
},
{
name: "multiple accounts on a host",
opts: StatusOptions{},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "github.com", "monalisa-2", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org,project:read"))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa-2 (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
✓ Logged in to github.com account monalisa (GH_CONFIG_DIR/hosts.yml)
- Active account: false
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org', 'project:read'
`),
},
{
name: "multiple hosts with multiple accounts with environment tokens and with errors",
opts: StatusOptions{},
env: map[string]string{"GH_ENTERPRISE_TOKEN": "gho_abc123"}, // monalisa-ghe-2
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_def456", "https")
login(t, c, "github.com", "monalisa-2", "gho_ghi789", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_xyz123", "ssh")
},
httpStubs: func(reg *httpmock.Registry) {
// Get scopes for monalisa-2
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
// Get scopes for monalisa
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo"))
// Get scopes for monalisa-ghe-2
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo,read:org"))
// Error getting scopes for monalisa-ghe
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.StatusStringResponse(404, "{}"))
// Get username for monalisa-ghe-2
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa-ghe-2"}}}`))
},
wantErr: cmdutil.SilentError,
wantErrOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa-2 (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
✓ Logged in to github.com account monalisa (GH_CONFIG_DIR/hosts.yml)
- Active account: false
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo'
! Missing required token scopes: 'read:org'
- To request missing scopes, run: gh auth refresh -h github.com
ghe.io
✓ Logged in to ghe.io account monalisa-ghe-2 (GH_ENTERPRISE_TOKEN)
- Active account: true
- Git operations protocol: ssh
- Token: gho_******
- Token scopes: 'repo', 'read:org'
X Failed to log in to ghe.io account monalisa-ghe (GH_CONFIG_DIR/hosts.yml)
- Active account: false
- The token in GH_CONFIG_DIR/hosts.yml is invalid.
- To re-authenticate, run: gh auth login -h ghe.io
- To forget about this account, run: gh auth logout -h ghe.io -u monalisa-ghe
`),
},
{
name: "multiple accounts on a host, only active users",
opts: StatusOptions{
Active: true,
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "github.com", "monalisa-2", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa-2 (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
`),
},
{
name: "multiple hosts with multiple accounts, only active users",
opts: StatusOptions{
Active: true,
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "github.com", "monalisa-2", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "ssh")
login(t, c, "ghe.io", "monalisa-ghe-2", "gho_abc123", "ssh")
},
httpStubs: func(reg *httpmock.Registry) {
// Get scopes for monalisa-2
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
// Get scopes for monalisa-ghe-2
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.ScopesResponder("repo,read:org"))
},
wantOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa-2 (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
ghe.io
✓ Logged in to ghe.io account monalisa-ghe-2 (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: ssh
- Token: gho_******
- Token scopes: 'repo', 'read:org'
`),
},
{
name: "multiple hosts with multiple accounts, only active users with errors",
opts: StatusOptions{
Active: true,
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "github.com", "monalisa-2", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "ssh")
login(t, c, "ghe.io", "monalisa-ghe-2", "gho_abc123", "ssh")
},
httpStubs: func(reg *httpmock.Registry) {
// Get scopes for monalisa-2
reg.Register(httpmock.REST("GET", ""), httpmock.ScopesResponder("repo,read:org"))
// Error getting scopes for monalisa-ghe-2
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.StatusStringResponse(404, "{}"))
},
wantErr: cmdutil.SilentError,
wantErrOut: heredoc.Doc(`
github.com
✓ Logged in to github.com account monalisa-2 (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- Git operations protocol: https
- Token: gho_******
- Token scopes: 'repo', 'read:org'
ghe.io
X Failed to log in to ghe.io account monalisa-ghe-2 (GH_CONFIG_DIR/hosts.yml)
- Active account: true
- The token in GH_CONFIG_DIR/hosts.yml is invalid.
- To re-authenticate, run: gh auth login -h ghe.io
- To forget about this account, run: gh auth logout -h ghe.io -u monalisa-ghe-2
`),
},
{
name: "json, no tokens",
opts: StatusOptions{},
jsonFields: []string{"hosts"},
wantOut: "{\"hosts\":{}}\n",
wantErrOut: "You are not logged into any GitHub hosts. To log in, run: gh auth login\n",
wantErr: nil, // should not return error in machine-readable mode
},
{
name: "json, no token for given --hostname",
opts: StatusOptions{
Hostname: "foo.com",
},
jsonFields: []string{"hosts"},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
},
wantOut: "{\"hosts\":{}}\n",
wantErrOut: "You are not logged into any accounts on foo.com\n",
wantErr: nil, // should not return error in machine-readable mode
},
{
name: "json, all valid tokens",
opts: StatusOptions{},
jsonFields: []string{"hosts"},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "github.com", "monalisa2", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mock for HeaderHasMinimumScopes api requests to github.com
reg.Register(
httpmock.REST("GET", ""),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
reg.Register(
httpmock.REST("GET", ""),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
// mock for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(
httpmock.REST("GET", "api/v3/"),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
},
wantOut: `{"hosts":{"ghe.io":[{"state":"success","active":true,"host":"ghe.io","login":"monalisa-ghe","tokenSource":"GH_CONFIG_DIR/hosts.yml","scopes":"repo, read:org","gitProtocol":"https"}],"github.com":[{"state":"success","active":true,"host":"github.com","login":"monalisa2","tokenSource":"GH_CONFIG_DIR/hosts.yml","scopes":"repo, read:org","gitProtocol":"https"},{"state":"success","active":false,"host":"github.com","login":"monalisa","tokenSource":"GH_CONFIG_DIR/hosts.yml","scopes":"repo, read:org","gitProtocol":"https"}]}}` + "\n",
},
{
name: "json, all valid tokens with hostname",
opts: StatusOptions{
Hostname: "github.com",
},
jsonFields: []string{"hosts"},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "github.com", "monalisa2", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to github.com
reg.Register(
httpmock.REST("GET", ""),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
reg.Register(
httpmock.REST("GET", ""),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
},
wantOut: `{"hosts":{"github.com":[{"state":"success","active":true,"host":"github.com","login":"monalisa2","tokenSource":"GH_CONFIG_DIR/hosts.yml","scopes":"repo, read:org","gitProtocol":"https"},{"state":"success","active":false,"host":"github.com","login":"monalisa","tokenSource":"GH_CONFIG_DIR/hosts.yml","scopes":"repo, read:org","gitProtocol":"https"}]}}` + "\n",
},
{
name: "json, all valid tokens with active",
opts: StatusOptions{
Active: true,
},
jsonFields: []string{"hosts"},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "gho_abc123", "https")
login(t, c, "github.com", "monalisa2", "gho_abc123", "https")
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to github.com
reg.Register(
httpmock.REST("GET", ""),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
reg.Register(
httpmock.REST("GET", "api/v3/"),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
},
wantOut: `{"hosts":{"ghe.io":[{"state":"success","active":true,"host":"ghe.io","login":"monalisa-ghe","tokenSource":"GH_CONFIG_DIR/hosts.yml","scopes":"repo, read:org","gitProtocol":"https"}],"github.com":[{"state":"success","active":true,"host":"github.com","login":"monalisa2","tokenSource":"GH_CONFIG_DIR/hosts.yml","scopes":"repo, read:org","gitProtocol":"https"}]}}` + "\n",
},
{
name: "json, token from env",
opts: StatusOptions{},
jsonFields: []string{"hosts"},
env: map[string]string{"GH_TOKEN": "gho_abc123"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", ""),
httpmock.ScopesResponder(""))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
},
wantOut: `{"hosts":{"github.com":[{"state":"success","active":true,"host":"github.com","login":"monalisa","tokenSource":"GH_TOKEN","gitProtocol":"https"}]}}` + "\n",
},
{
name: "json, bad token",
opts: StatusOptions{},
jsonFields: []string{"hosts"},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mock for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.StatusStringResponse(400, "no bueno"))
},
wantOut: `{"hosts":{"ghe.io":[{"state":"error","error":"HTTP 400 (https://ghe.io/api/v3/)","active":true,"host":"ghe.io","login":"monalisa-ghe","tokenSource":"GH_CONFIG_DIR/hosts.yml","gitProtocol":"https"}]}}` + "\n",
wantErr: nil, // should not return error in machine-readable mode
},
{
name: "json, bad token from env",
opts: StatusOptions{},
jsonFields: []string{"hosts"},
env: map[string]string{"GH_TOKEN": "gho_abc123"},
httpStubs: func(reg *httpmock.Registry) {
// mock for HeaderHasMinimumScopes api requests to a non-github.com host
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StatusStringResponse(400, `no bueno`))
},
wantOut: `{"hosts":{"github.com":[{"state":"error","error":"non-200 OK status code: body: \"no bueno\"","active":true,"host":"github.com","login":"","tokenSource":"GH_TOKEN","gitProtocol":"https"}]}}` + "\n",
wantErr: nil, // should not return error in machine-readable mode
},
{
name: "json, timeout error",
opts: StatusOptions{
Hostname: "github.com",
},
jsonFields: []string{"hosts"},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", ""), func(req *http.Request) (*http.Response, error) {
// timeout error
return nil, context.DeadlineExceeded
})
},
wantOut: `{"hosts":{"github.com":[{"state":"timeout","error":"Get \"https://api.github.com/\": context deadline exceeded","active":true,"host":"github.com","login":"monalisa","tokenSource":"GH_CONFIG_DIR/hosts.yml","gitProtocol":"https"}]}}` + "\n",
wantErr: nil, // should not return error in machine-readable mode
},
{
name: "json, with show token",
opts: StatusOptions{
Hostname: "github.com",
ShowToken: true,
},
jsonFields: []string{"hosts"},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "abc123", "https")
},
httpStubs: func(reg *httpmock.Registry) {
// mocks for HeaderHasMinimumScopes api requests to github.com
reg.Register(
httpmock.REST("GET", ""),
httpmock.WithHeader(httpmock.ScopesResponder("repo,read:org"), "X-Oauth-Scopes", "repo, read:org"))
},
wantOut: `{"hosts":{"github.com":[{"state":"success","active":true,"host":"github.com","login":"monalisa","tokenSource":"GH_CONFIG_DIR/hosts.yml","token":"abc123","scopes":"repo, read:org","gitProtocol":"https"}]}}` + "\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
ios.SetStdoutTTY(true)
tt.opts.IO = ios
cfg, _ := config.NewIsolatedTestConfig(t)
if tt.cfgStubs != nil {
tt.cfgStubs(t, cfg)
}
tt.opts.Config = func() (gh.Config, error) {
return cfg, nil
}
reg := &httpmock.Registry{}
defer reg.Verify(t)
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
if tt.jsonFields != nil {
jsonExporter := cmdutil.NewJSONExporter()
jsonExporter.SetFields(tt.jsonFields)
tt.opts.Exporter = jsonExporter
}
for k, v := range tt.env {
t.Setenv(k, v)
}
err := statusRun(&tt.opts)
if tt.wantErr != nil {
require.Equal(t, err, tt.wantErr)
} else {
require.NoError(t, err)
}
output := replaceAll(stdout.String(), config.ConfigDir()+string(filepath.Separator), "GH_CONFIG_DIR/")
errorOutput := replaceAll(stderr.String(), config.ConfigDir()+string(filepath.Separator), "GH_CONFIG_DIR/")
require.Equal(t, tt.wantErrOut, errorOutput)
require.Equal(t, tt.wantOut, output)
})
}
}
func login(t *testing.T, c gh.Config, hostname, username, token, protocol string) {
t.Helper()
_, err := c.Authentication().Login(hostname, username, token, protocol, false)
require.NoError(t, err)
}
// replaceAll replaces all instances of old with new in s, as well as all instances
// of the JSON-escaped version of old with the JSON-escaped version of new.
// This is because when the test is run on Windows the paths will have backslashes
// escaped in JSON and a simple strings.ReplaceAll won't catch them.
func replaceAll(s string, old string, new string) string {
jsonEscapedOld, _ := json.Marshal(old)
jsonEscapedOld = jsonEscapedOld[1 : len(jsonEscapedOld)-1]
jsonEscapedNew, _ := json.Marshal(new)
jsonEscapedNew = jsonEscapedNew[1 : len(jsonEscapedNew)-1]
replaced := strings.ReplaceAll(s, string(jsonEscapedOld), string(jsonEscapedNew))
replaced = strings.ReplaceAll(replaced, old, new)
return replaced
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/oauth_scopes.go | pkg/cmd/auth/shared/oauth_scopes.go | package shared
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
)
type MissingScopesError struct {
MissingScopes []string
}
func (e MissingScopesError) Error() string {
var missing []string
for _, s := range e.MissingScopes {
missing = append(missing, fmt.Sprintf("'%s'", s))
}
scopes := strings.Join(missing, ", ")
if len(e.MissingScopes) == 1 {
return "missing required scope " + scopes
}
return "missing required scopes " + scopes
}
type httpClient interface {
Do(*http.Request) (*http.Response, error)
}
// GetScopes performs a GitHub API request and returns the value of the X-Oauth-Scopes header.
func GetScopes(httpClient httpClient, hostname, authToken string) (string, error) {
apiEndpoint := ghinstance.RESTPrefix(hostname)
req, err := http.NewRequest("GET", apiEndpoint, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "token "+authToken)
res, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer func() {
// Ensure the response body is fully read and closed
// before we reconnect, so that we reuse the same TCPconnection.
_, _ = io.Copy(io.Discard, res.Body)
res.Body.Close()
}()
if res.StatusCode != 200 {
return "", api.HandleHTTPError(res)
}
return res.Header.Get("X-Oauth-Scopes"), nil
}
// HasMinimumScopes performs a GitHub API request and returns an error if the token used in the request
// lacks the minimum required scopes for performing API operations with gh.
func HasMinimumScopes(httpClient httpClient, hostname, authToken string) error {
scopesHeader, err := GetScopes(httpClient, hostname, authToken)
if err != nil {
return err
}
return HeaderHasMinimumScopes(scopesHeader)
}
// HeaderHasMinimumScopes parses the comma separated scopesHeader string and returns an error
// if it lacks the minimum required scopes for performing API operations with gh.
func HeaderHasMinimumScopes(scopesHeader string) error {
if scopesHeader == "" {
// if the token reports no scopes, assume that it's an integration token and give up on
// detecting its capabilities
return nil
}
search := map[string]bool{
"repo": false,
"read:org": false,
"admin:org": false,
}
for _, s := range strings.Split(scopesHeader, ",") {
search[strings.TrimSpace(s)] = true
}
var missingScopes []string
if !search["repo"] {
missingScopes = append(missingScopes, "repo")
}
if !search["read:org"] && !search["write:org"] && !search["admin:org"] {
missingScopes = append(missingScopes, "read:org")
}
if len(missingScopes) > 0 {
return &MissingScopesError{MissingScopes: missingScopes}
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/login_flow.go | pkg/cmd/auth/shared/login_flow.go | package shared
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"slices"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/authflow"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/cmd/ssh-key/add"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/ssh"
)
const defaultSSHKeyTitle = "GitHub CLI"
type iconfig interface {
Login(string, string, string, string, bool) (bool, error)
UsersForHost(string) []string
}
type LoginOptions struct {
IO *iostreams.IOStreams
Config iconfig
HTTPClient *http.Client
PlainHTTPClient *http.Client
Hostname string
Interactive bool
Web bool
Scopes []string
GitProtocol string
Prompter Prompt
Browser browser.Browser
CredentialFlow *GitCredentialFlow
SecureStorage bool
SkipSSHKeyPrompt bool
CopyToClipboard bool
sshContext ssh.Context
}
func Login(opts *LoginOptions) error {
cfg := opts.Config
hostname := opts.Hostname
httpClient := opts.HTTPClient
cs := opts.IO.ColorScheme()
gitProtocol := strings.ToLower(opts.GitProtocol)
if opts.Interactive && gitProtocol == "" {
options := []string{
"HTTPS",
"SSH",
}
result, err := opts.Prompter.Select(
"What is your preferred protocol for Git operations on this host?",
options[0],
options)
if err != nil {
return err
}
proto := options[result]
gitProtocol = strings.ToLower(proto)
}
var additionalScopes []string
if opts.Interactive && gitProtocol == "https" {
if err := opts.CredentialFlow.Prompt(hostname); err != nil {
return err
}
additionalScopes = append(additionalScopes, opts.CredentialFlow.Scopes()...)
}
var keyToUpload string
keyTitle := defaultSSHKeyTitle
if opts.Interactive && !opts.SkipSSHKeyPrompt && gitProtocol == "ssh" {
pubKeys, err := opts.sshContext.LocalPublicKeys()
if err != nil {
return err
}
if len(pubKeys) > 0 {
options := append(pubKeys, "Skip")
keyChoice, err := opts.Prompter.Select(
"Upload your SSH public key to your GitHub account?",
options[0],
options)
if err != nil {
return err
}
if keyChoice < len(pubKeys) {
keyToUpload = pubKeys[keyChoice]
}
} else if opts.sshContext.HasKeygen() {
sshChoice, err := opts.Prompter.Confirm("Generate a new SSH key to add to your GitHub account?", true)
if err != nil {
return err
}
if sshChoice {
passphrase, err := opts.Prompter.Password(
"Enter a passphrase for your new SSH key (Optional):")
if err != nil {
return err
}
keyPair, err := opts.sshContext.GenerateSSHKey("id_ed25519", passphrase)
if err != nil {
return err
}
keyToUpload = keyPair.PublicKeyPath
}
}
if keyToUpload != "" {
var err error
keyTitle, err = opts.Prompter.Input(
"Title for your SSH key:", defaultSSHKeyTitle)
if err != nil {
return err
}
additionalScopes = append(additionalScopes, "admin:public_key")
}
}
var authMode int
if opts.Web {
authMode = 0
} else if opts.Interactive {
options := []string{"Login with a web browser", "Paste an authentication token"}
var err error
authMode, err = opts.Prompter.Select(
"How would you like to authenticate GitHub CLI?",
options[0],
options)
if err != nil {
return err
}
}
var authToken string
var username string
if authMode == 0 {
var err error
authToken, username, err = authflow.AuthFlow(opts.PlainHTTPClient, hostname, opts.IO, "", append(opts.Scopes, additionalScopes...), opts.Interactive, opts.Browser, opts.CopyToClipboard)
if err != nil {
return fmt.Errorf("failed to authenticate via web browser: %w", err)
}
fmt.Fprintf(opts.IO.ErrOut, "%s Authentication complete.\n", cs.SuccessIcon())
} else {
minimumScopes := append([]string{"repo", "read:org"}, additionalScopes...)
fmt.Fprint(opts.IO.ErrOut, heredoc.Docf(`
Tip: you can generate a Personal Access Token here https://%s/settings/tokens
The minimum required scopes are %s.
`, hostname, scopesSentence(minimumScopes)))
var err error
authToken, err = opts.Prompter.AuthToken()
if err != nil {
return err
}
if err := HasMinimumScopes(httpClient, hostname, authToken); err != nil {
return fmt.Errorf("error validating token: %w", err)
}
}
if username == "" {
var err error
username, err = GetCurrentLogin(httpClient, hostname, authToken)
if err != nil {
return fmt.Errorf("error retrieving current user: %w", err)
}
}
// Get these users before adding the new one, so that we can
// check whether the user was already logged in later.
//
// In this case we ignore the error if the host doesn't exist
// because that can occur when the user is logging into a host
// for the first time.
usersForHost := cfg.UsersForHost(hostname)
userWasAlreadyLoggedIn := slices.Contains(usersForHost, username)
if gitProtocol != "" {
fmt.Fprintf(opts.IO.ErrOut, "- gh config set -h %s git_protocol %s\n", hostname, gitProtocol)
fmt.Fprintf(opts.IO.ErrOut, "%s Configured git protocol\n", cs.SuccessIcon())
}
insecureStorageUsed, err := cfg.Login(hostname, username, authToken, gitProtocol, opts.SecureStorage)
if err != nil {
return err
}
if insecureStorageUsed {
fmt.Fprintf(opts.IO.ErrOut, "%s Authentication credentials saved in plain text\n", cs.Yellow("!"))
}
if opts.CredentialFlow.ShouldSetup() {
err := opts.CredentialFlow.Setup(hostname, username, authToken)
if err != nil {
return err
}
}
if keyToUpload != "" {
uploaded, err := sshKeyUpload(httpClient, hostname, keyToUpload, keyTitle)
if err != nil {
return err
}
if uploaded {
fmt.Fprintf(opts.IO.ErrOut, "%s Uploaded the SSH key to your GitHub account: %s\n", cs.SuccessIcon(), cs.Bold(keyToUpload))
} else {
fmt.Fprintf(opts.IO.ErrOut, "%s SSH key already existed on your GitHub account: %s\n", cs.SuccessIcon(), cs.Bold(keyToUpload))
}
}
fmt.Fprintf(opts.IO.ErrOut, "%s Logged in as %s\n", cs.SuccessIcon(), cs.Bold(username))
if userWasAlreadyLoggedIn {
fmt.Fprintf(opts.IO.ErrOut, "%s You were already logged in to this account\n", cs.WarningIcon())
}
return nil
}
func scopesSentence(scopes []string) string {
quoted := make([]string, len(scopes))
for i, s := range scopes {
quoted[i] = fmt.Sprintf("'%s'", s)
}
return strings.Join(quoted, ", ")
}
func sshKeyUpload(httpClient *http.Client, hostname, keyFile string, title string) (bool, error) {
f, err := os.Open(keyFile)
if err != nil {
return false, err
}
defer f.Close()
return add.SSHKeyUpload(httpClient, hostname, f, title)
}
func GetCurrentLogin(httpClient httpClient, hostname, authToken string) (string, error) {
query := `query UserCurrent{viewer{login}}`
reqBody, err := json.Marshal(map[string]interface{}{"query": query})
if err != nil {
return "", err
}
result := struct {
Data struct{ Viewer struct{ Login string } }
}{}
apiEndpoint := ghinstance.GraphQLEndpoint(hostname)
req, err := http.NewRequest("POST", apiEndpoint, bytes.NewBuffer(reqBody))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "token "+authToken)
res, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode > 299 {
return "", api.HandleHTTPError(res)
}
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&result)
if err != nil {
return "", err
}
return result.Data.Viewer.Login, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/git_credential.go | pkg/cmd/auth/shared/git_credential.go | package shared
import (
"errors"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
)
type HelperConfig interface {
ConfigureOurs(hostname string) error
ConfiguredHelper(hostname string) (gitcredentials.Helper, error)
}
type GitCredentialFlow struct {
Prompter Prompt
HelperConfig HelperConfig
Updater *gitcredentials.Updater
shouldSetup bool
helper gitcredentials.Helper
scopes []string
}
func (flow *GitCredentialFlow) Prompt(hostname string) error {
// First we'll fetch the credential helper that would be used for this host
var configuredHelperErr error
flow.helper, configuredHelperErr = flow.HelperConfig.ConfiguredHelper(hostname)
// If the helper is gh itself, then we don't need to ask the user if they want to update their git credentials
// because it will happen automatically by virtue of the fact that gh will return the active token.
//
// Since gh is the helper, this token may be used for git operations, so we'll additionally request the workflow
// scope to ensure that git push operations that include workflow changes succeed.
if flow.helper.IsOurs() {
flow.scopes = append(flow.scopes, "workflow")
return nil
}
// Prompt the user for whether they want to configure git with the newly obtained token
result, err := flow.Prompter.Confirm("Authenticate Git with your GitHub credentials?", true)
if err != nil {
return err
}
flow.shouldSetup = result
if flow.shouldSetup {
// If the user does want to configure git, we'll check the error returned from fetching the configured helper
// above. If the error indicates that git isn't installed, we'll return an error now to ensure that the auth
// flow is aborted before the user goes any further.
//
// Note that this is _slightly_ naive because there may be other reasons that fetching the configured helper
// fails that might cause later failures but this code has existed for a long time and I don't want to change
// it as part of a refactoring.
//
// Refs:
// * https://git-scm.com/docs/git-config#_description
// * https://github.com/cli/cli/pull/4109
var errNotInstalled *git.NotInstalled
if errors.As(configuredHelperErr, &errNotInstalled) {
return configuredHelperErr
}
// On the other hand, if the user has requested setup we'll additionally request the workflow
// scope to ensure that git push operations that include workflow changes succeed.
flow.scopes = append(flow.scopes, "workflow")
}
return nil
}
func (flow *GitCredentialFlow) Scopes() []string {
return flow.scopes
}
func (flow *GitCredentialFlow) ShouldSetup() bool {
return flow.shouldSetup
}
func (flow *GitCredentialFlow) Setup(hostname, username, authToken string) error {
// If there is no credential helper configured then we will set ourselves up as
// the credential helper for this host.
if !flow.helper.IsConfigured() {
return flow.HelperConfig.ConfigureOurs(hostname)
}
// Otherwise, we'll tell git to inform the existing credential helper of the new credentials.
return flow.Updater.Update(hostname, username, authToken)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/oauth_scopes_test.go | pkg/cmd/auth/shared/oauth_scopes_test.go | package shared
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
)
func Test_HasMinimumScopes(t *testing.T) {
tests := []struct {
name string
header string
wantErr string
}{
{
name: "write:org satisfies read:org",
header: "repo, write:org",
wantErr: "",
},
{
name: "insufficient scope",
header: "repo",
wantErr: "missing required scope 'read:org'",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fakehttp := &httpmock.Registry{}
defer fakehttp.Verify(t)
var gotAuthorization string
fakehttp.Register(httpmock.REST("GET", ""), func(req *http.Request) (*http.Response, error) {
gotAuthorization = req.Header.Get("authorization")
return &http.Response{
Request: req,
StatusCode: 200,
Body: io.NopCloser(&bytes.Buffer{}),
Header: map[string][]string{
"X-Oauth-Scopes": {tt.header},
},
}, nil
})
client := http.Client{Transport: fakehttp}
err := HasMinimumScopes(&client, "github.com", "ATOKEN")
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
} else {
assert.NoError(t, err)
}
assert.Equal(t, gotAuthorization, "token ATOKEN")
})
}
}
func Test_HeaderHasMinimumScopes(t *testing.T) {
tests := []struct {
name string
header string
wantErr string
}{
{
name: "no scopes",
header: "",
wantErr: "",
},
{
name: "default scopes",
header: "repo, read:org",
wantErr: "",
},
{
name: "admin:org satisfies read:org",
header: "repo, admin:org",
wantErr: "",
},
{
name: "write:org satisfies read:org",
header: "repo, write:org",
wantErr: "",
},
{
name: "insufficient scope",
header: "repo",
wantErr: "missing required scope 'read:org'",
},
{
name: "insufficient scopes",
header: "gist",
wantErr: "missing required scopes 'repo', 'read:org'",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := HeaderHasMinimumScopes(tt.header)
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
} else {
assert.NoError(t, err)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/git_credential_test.go | pkg/cmd/auth/shared/git_credential_test.go | package shared
import (
"testing"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
)
func TestSetup_configureExisting(t *testing.T) {
cs, restoreRun := run.Stub()
defer restoreRun(t)
cs.Register(`git credential reject`, 0, "")
cs.Register(`git credential approve`, 0, "")
f := GitCredentialFlow{
helper: gitcredentials.Helper{Cmd: "osxkeychain"},
Updater: &gitcredentials.Updater{
GitClient: &git.Client{GitPath: "some/path/git"},
},
}
if err := f.Setup("example.com", "monalisa", "PASSWD"); err != nil {
t.Errorf("Setup() error = %v", err)
}
}
func TestGitCredentialsSetup_setOurs_GH(t *testing.T) {
cs, restoreRun := run.Stub()
defer restoreRun(t)
cs.Register(`git config --global --replace-all credential\.`, 0, "", func(args []string) {
if key := args[len(args)-2]; key != "credential.https://github.com.helper" {
t.Errorf("git config key was %q", key)
}
if val := args[len(args)-1]; val != "" {
t.Errorf("global credential helper configured to %q", val)
}
})
cs.Register(`git config --global --add credential\.`, 0, "", func(args []string) {
if key := args[len(args)-2]; key != "credential.https://github.com.helper" {
t.Errorf("git config key was %q", key)
}
if val := args[len(args)-1]; val != "!/path/to/gh auth git-credential" {
t.Errorf("global credential helper configured to %q", val)
}
})
cs.Register(`git config --global --replace-all credential\.`, 0, "", func(args []string) {
if key := args[len(args)-2]; key != "credential.https://gist.github.com.helper" {
t.Errorf("git config key was %q", key)
}
if val := args[len(args)-1]; val != "" {
t.Errorf("global credential helper configured to %q", val)
}
})
cs.Register(`git config --global --add credential\.`, 0, "", func(args []string) {
if key := args[len(args)-2]; key != "credential.https://gist.github.com.helper" {
t.Errorf("git config key was %q", key)
}
if val := args[len(args)-1]; val != "!/path/to/gh auth git-credential" {
t.Errorf("global credential helper configured to %q", val)
}
})
f := GitCredentialFlow{
helper: gitcredentials.Helper{},
HelperConfig: &gitcredentials.HelperConfig{
SelfExecutablePath: "/path/to/gh",
GitClient: &git.Client{GitPath: "some/path/git"},
},
}
if err := f.Setup("github.com", "monalisa", "PASSWD"); err != nil {
t.Errorf("Setup() error = %v", err)
}
}
func TestSetup_setOurs_nonGH(t *testing.T) {
cs, restoreRun := run.Stub()
defer restoreRun(t)
cs.Register(`git config --global --replace-all credential\.`, 0, "", func(args []string) {
if key := args[len(args)-2]; key != "credential.https://example.com.helper" {
t.Errorf("git config key was %q", key)
}
if val := args[len(args)-1]; val != "" {
t.Errorf("global credential helper configured to %q", val)
}
})
cs.Register(`git config --global --add credential\.`, 0, "", func(args []string) {
if key := args[len(args)-2]; key != "credential.https://example.com.helper" {
t.Errorf("git config key was %q", key)
}
if val := args[len(args)-1]; val != "!/path/to/gh auth git-credential" {
t.Errorf("global credential helper configured to %q", val)
}
})
f := GitCredentialFlow{
helper: gitcredentials.Helper{},
HelperConfig: &gitcredentials.HelperConfig{
SelfExecutablePath: "/path/to/gh",
GitClient: &git.Client{GitPath: "some/path/git"},
},
}
if err := f.Setup("example.com", "monalisa", "PASSWD"); err != nil {
t.Errorf("Setup() error = %v", err)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/login_flow_test.go | pkg/cmd/auth/shared/login_flow_test.go | package shared
import (
"fmt"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/ssh"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type tinyConfig map[string]string
func (c tinyConfig) Login(host, username, token, gitProtocol string, encrypt bool) (bool, error) {
c[fmt.Sprintf("%s:%s", host, "user")] = username
c[fmt.Sprintf("%s:%s", host, "oauth_token")] = token
c[fmt.Sprintf("%s:%s", host, "git_protocol")] = gitProtocol
return false, nil
}
func (c tinyConfig) UsersForHost(hostname string) []string {
return nil
}
func TestLogin(t *testing.T) {
tests := []struct {
name string
opts LoginOptions
httpStubs func(*testing.T, *httpmock.Registry)
runStubs func(*testing.T, *run.CommandStubber, *LoginOptions)
wantsConfig map[string]string
wantsErr string
stdout string
stderr string
stderrAssert func(*testing.T, *LoginOptions, string)
}{
{
name: "tty, prompt (protocol: ssh, create key: yes)",
opts: LoginOptions{
Prompter: &prompter.PrompterMock{
SelectFunc: func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "What is your preferred protocol for Git operations on this host?":
return prompter.IndexFor(opts, "SSH")
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
},
PasswordFunc: func(_ string) (string, error) {
return "monkey", nil
},
ConfirmFunc: func(prompt string, _ bool) (bool, error) {
return true, nil
},
AuthTokenFunc: func() (string, error) {
return "ATOKEN", nil
},
InputFunc: func(_, _ string) (string, error) {
return "Test Key", nil
},
},
Hostname: "example.com",
Interactive: true,
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/"),
httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{ "login": "monalisa" }}}`))
reg.Register(
httpmock.REST("GET", "api/v3/user/keys"),
httpmock.StringResponse(`[]`))
reg.Register(
httpmock.REST("POST", "api/v3/user/keys"),
httpmock.StringResponse(`{}`))
},
runStubs: func(t *testing.T, cs *run.CommandStubber, opts *LoginOptions) {
dir := t.TempDir()
keyFile := filepath.Join(dir, "id_ed25519")
cs.Register(`ssh-keygen`, 0, "", func(args []string) {
expected := []string{
"ssh-keygen", "-t", "ed25519",
"-C", "",
"-N", "monkey",
"-f", keyFile,
}
assert.Equal(t, expected, args)
// simulate that the public key file has been generated
_ = os.WriteFile(keyFile+".pub", []byte("PUBKEY asdf"), 0600)
})
opts.sshContext = ssh.NewContextForTests(dir, "ssh-keygen")
},
wantsConfig: map[string]string{
"example.com:user": "monalisa",
"example.com:oauth_token": "ATOKEN",
"example.com:git_protocol": "ssh",
},
stderrAssert: func(t *testing.T, opts *LoginOptions, stderr string) {
sshDir, err := opts.sshContext.SshDir()
if err != nil {
t.Errorf("Could not load ssh config dir: %v", err)
}
assert.Equal(t, heredoc.Docf(`
Tip: you can generate a Personal Access Token here https://example.com/settings/tokens
The minimum required scopes are 'repo', 'read:org', 'admin:public_key'.
- gh config set -h example.com git_protocol ssh
✓ Configured git protocol
✓ Uploaded the SSH key to your GitHub account: %s
✓ Logged in as monalisa
`, filepath.Join(sshDir, "id_ed25519.pub")), stderr)
},
},
{
name: "tty, --git-protocol ssh, prompt (create key: yes)",
opts: LoginOptions{
Prompter: &prompter.PrompterMock{
SelectFunc: func(prompt, _ string, opts []string) (int, error) {
switch prompt {
case "How would you like to authenticate GitHub CLI?":
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
},
PasswordFunc: func(_ string) (string, error) {
return "monkey", nil
},
ConfirmFunc: func(prompt string, _ bool) (bool, error) {
return true, nil
},
AuthTokenFunc: func() (string, error) {
return "ATOKEN", nil
},
InputFunc: func(_, _ string) (string, error) {
return "Test Key", nil
},
},
Hostname: "example.com",
Interactive: true,
GitProtocol: "SSH",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/"),
httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{ "login": "monalisa" }}}`))
reg.Register(
httpmock.REST("GET", "api/v3/user/keys"),
httpmock.StringResponse(`[]`))
reg.Register(
httpmock.REST("POST", "api/v3/user/keys"),
httpmock.StringResponse(`{}`))
},
runStubs: func(t *testing.T, cs *run.CommandStubber, opts *LoginOptions) {
dir := t.TempDir()
keyFile := filepath.Join(dir, "id_ed25519")
cs.Register(`ssh-keygen`, 0, "", func(args []string) {
expected := []string{
"ssh-keygen", "-t", "ed25519",
"-C", "",
"-N", "monkey",
"-f", keyFile,
}
assert.Equal(t, expected, args)
// simulate that the public key file has been generated
_ = os.WriteFile(keyFile+".pub", []byte("PUBKEY asdf"), 0600)
})
opts.sshContext = ssh.NewContextForTests(dir, "ssh-keygen")
},
wantsConfig: map[string]string{
"example.com:user": "monalisa",
"example.com:oauth_token": "ATOKEN",
"example.com:git_protocol": "ssh",
},
stderrAssert: func(t *testing.T, opts *LoginOptions, stderr string) {
sshDir, err := opts.sshContext.SshDir()
if err != nil {
t.Errorf("Could not load ssh config dir: %v", err)
}
assert.Equal(t, heredoc.Docf(`
Tip: you can generate a Personal Access Token here https://example.com/settings/tokens
The minimum required scopes are 'repo', 'read:org', 'admin:public_key'.
- gh config set -h example.com git_protocol ssh
✓ Configured git protocol
✓ Uploaded the SSH key to your GitHub account: %s
✓ Logged in as monalisa
`, filepath.Join(sshDir, "id_ed25519.pub")), stderr)
},
},
{
name: "tty, --git-protocol ssh, --skip-ssh-key",
opts: LoginOptions{
Prompter: &prompter.PrompterMock{
SelectFunc: func(prompt, _ string, opts []string) (int, error) {
if prompt == "How would you like to authenticate GitHub CLI?" {
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
},
AuthTokenFunc: func() (string, error) {
return "ATOKEN", nil
},
},
Hostname: "example.com",
Interactive: true,
GitProtocol: "SSH",
SkipSSHKeyPrompt: true,
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/"),
httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{ "login": "monalisa" }}}`))
},
wantsConfig: map[string]string{
"example.com:user": "monalisa",
"example.com:oauth_token": "ATOKEN",
"example.com:git_protocol": "ssh",
},
stderr: heredoc.Doc(`
Tip: you can generate a Personal Access Token here https://example.com/settings/tokens
The minimum required scopes are 'repo', 'read:org'.
- gh config set -h example.com git_protocol ssh
✓ Configured git protocol
✓ Logged in as monalisa
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(t, reg)
}
cfg := tinyConfig{}
ios, _, stdout, stderr := iostreams.Test()
tt.opts.IO = ios
tt.opts.Config = &cfg
tt.opts.HTTPClient = &http.Client{Transport: reg}
tt.opts.CredentialFlow = &GitCredentialFlow{
// Intentionally not instantiating anything in here because the tests do not hit this code path.
// Right now it's better to panic if we write a test that hits the code than say, start calling
// out to git unintentionally.
}
if tt.runStubs != nil {
rs, runRestore := run.Stub()
defer runRestore(t)
tt.runStubs(t, rs, &tt.opts)
}
err := Login(&tt.opts)
if tt.wantsErr != "" {
assert.EqualError(t, err, tt.wantsErr)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.wantsConfig, map[string]string(cfg))
}
assert.Equal(t, tt.stdout, stdout.String())
if tt.stderrAssert != nil {
tt.stderrAssert(t, &tt.opts, stderr.String())
} else {
assert.Equal(t, tt.stderr, stderr.String())
}
})
}
}
func TestAuthenticatingGitCredentials(t *testing.T) {
// Given we have no host or global credential helpers configured
// And given they have chosen https as their git protocol
// When they choose to authenticate git with their GitHub credentials
// Then gh is configured as their credential helper for that host
ios, _, _, _ := iostreams.Test()
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.REST("GET", "api/v3/"),
httpmock.ScopesResponder("repo,read:org"))
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{ "login": "monalisa" }}}`))
opts := &LoginOptions{
IO: ios,
Config: tinyConfig{},
HTTPClient: &http.Client{Transport: reg},
Hostname: "example.com",
Interactive: true,
GitProtocol: "https",
Prompter: &prompter.PrompterMock{
SelectFunc: func(prompt, _ string, opts []string) (int, error) {
if prompt == "How would you like to authenticate GitHub CLI?" {
return prompter.IndexFor(opts, "Paste an authentication token")
}
return -1, prompter.NoSuchPromptErr(prompt)
},
AuthTokenFunc: func() (string, error) {
return "ATOKEN", nil
},
},
CredentialFlow: &GitCredentialFlow{
Prompter: &prompter.PrompterMock{
ConfirmFunc: func(prompt string, _ bool) (bool, error) {
return true, nil
},
},
HelperConfig: &gitcredentials.FakeHelperConfig{
SelfExecutablePath: "/path/to/gh",
Helpers: map[string]gitcredentials.Helper{},
},
// Updater not required for this test as we will be setting gh as the helper
},
}
require.NoError(t, Login(opts))
helper, err := opts.CredentialFlow.HelperConfig.ConfiguredHelper("example.com")
require.NoError(t, err)
require.True(t, helper.IsOurs(), "expected gh to be the configured helper")
}
func Test_scopesSentence(t *testing.T) {
type args struct {
scopes []string
}
tests := []struct {
name string
args args
want string
}{
{
name: "basic scopes",
args: args{
scopes: []string{"repo", "read:org"},
},
want: "'repo', 'read:org'",
},
{
name: "empty",
args: args{
scopes: []string(nil),
},
want: "",
},
{
name: "workflow scope",
args: args{
scopes: []string{"repo", "workflow"},
},
want: "'repo', 'workflow'",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := scopesSentence(tt.args.scopes); got != tt.want {
t.Errorf("scopesSentence() = %q, want %q", got, tt.want)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/prompt.go | pkg/cmd/auth/shared/prompt.go | package shared
type Prompt interface {
Select(string, string, []string) (int, error)
Confirm(string, bool) (bool, error)
InputHostname() (string, error)
AuthToken() (string, error)
Input(string, string) (string, error)
Password(string) (string, error)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/writeable.go | pkg/cmd/auth/shared/writeable.go | package shared
import (
"strings"
"github.com/cli/cli/v2/internal/gh"
)
func AuthTokenWriteable(authCfg gh.AuthConfig, hostname string) (string, bool) {
token, src := authCfg.ActiveToken(hostname)
return src, (token == "" || !strings.HasSuffix(src, "_TOKEN"))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/gitcredentials/fake_helper_config_test.go | pkg/cmd/auth/shared/gitcredentials/fake_helper_config_test.go | package gitcredentials_test
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/contract"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
)
func TestFakeHelperConfigContract(t *testing.T) {
// Note that this being mutated by `NewHelperConfig` makes these tests not parallelizable
var fhc *gitcredentials.FakeHelperConfig
contract.HelperConfig{
NewHelperConfig: func(t *testing.T) shared.HelperConfig {
// Mutate the closed over fhc so that ConfigureHelper is able to configure helpers
// for tests. An alternative would be to provide the Helper as an argument back to ConfigureHelper
// but then we'd have to type assert it back to *FakeHelperConfig, which is probably more trouble than
// it's worth to parallelize these tests, sinced it's not even possible to parallelize the real Helperconfig
// ones due to them using t.Setenv
fhc = &gitcredentials.FakeHelperConfig{
SelfExecutablePath: "/path/to/gh",
Helpers: map[string]gitcredentials.Helper{},
}
return fhc
},
ConfigureHelper: func(t *testing.T, hostname string) {
fhc.Helpers[hostname] = gitcredentials.Helper{Cmd: "test-helper"}
},
}.Test(t)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/gitcredentials/helper_config.go | pkg/cmd/auth/shared/gitcredentials/helper_config.go | package gitcredentials
import (
"context"
"fmt"
"path/filepath"
"strings"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/google/shlex"
)
// A HelperConfig is used to configure and inspect the state of git credential helpers.
type HelperConfig struct {
SelfExecutablePath string
GitClient *git.Client
}
// ConfigureOurs sets up the git credential helper chain to use the GitHub CLI credential helper for git repositories
// including gists.
func (hc *HelperConfig) ConfigureOurs(hostname string) error {
ctx := context.TODO()
credHelperKeys := []string{
keyFor(hostname),
}
gistHost := strings.TrimSuffix(ghinstance.GistHost(hostname), "/")
if strings.HasPrefix(gistHost, "gist.") {
credHelperKeys = append(credHelperKeys, keyFor(gistHost))
}
var configErr error
for _, credHelperKey := range credHelperKeys {
if configErr != nil {
break
}
// first use a blank value to indicate to git we want to sever the chain of credential helpers
preConfigureCmd, err := hc.GitClient.Command(ctx, "config", "--global", "--replace-all", credHelperKey, "")
if err != nil {
configErr = err
break
}
if _, err = preConfigureCmd.Output(); err != nil {
configErr = err
break
}
// second configure the actual helper for this host
configureCmd, err := hc.GitClient.Command(ctx,
"config", "--global", "--add",
credHelperKey,
fmt.Sprintf("!%s auth git-credential", shellQuote(hc.SelfExecutablePath)),
)
if err != nil {
configErr = err
} else {
_, configErr = configureCmd.Output()
}
}
return configErr
}
// A Helper represents a git credential helper configuration.
type Helper struct {
Cmd string
}
// IsConfigured returns true if the helper has a non-empty command, i.e. the git config had an entry
func (h Helper) IsConfigured() bool {
return h.Cmd != ""
}
// IsOurs returns true if the helper command is the GitHub CLI credential helper
func (h Helper) IsOurs() bool {
if !strings.HasPrefix(h.Cmd, "!") {
return false
}
args, err := shlex.Split(h.Cmd[1:])
if err != nil || len(args) == 0 {
return false
}
return strings.TrimSuffix(filepath.Base(args[0]), ".exe") == "gh"
}
// ConfiguredHelper returns the configured git credential helper for a given hostname.
func (hc *HelperConfig) ConfiguredHelper(hostname string) (Helper, error) {
ctx := context.TODO()
hostHelperCmd, err := hc.GitClient.Config(ctx, keyFor(hostname))
if hostHelperCmd != "" {
// TODO: This is a direct refactoring removing named and naked returns
// but we should probably look closer at the error handling here
return Helper{
Cmd: hostHelperCmd,
}, err
}
globalHelperCmd, err := hc.GitClient.Config(ctx, "credential.helper")
if globalHelperCmd != "" {
return Helper{
Cmd: globalHelperCmd,
}, err
}
return Helper{}, nil
}
func keyFor(hostname string) string {
host := strings.TrimSuffix(ghinstance.HostPrefix(hostname), "/")
return fmt.Sprintf("credential.%s.helper", host)
}
func shellQuote(s string) string {
if strings.ContainsAny(s, " $\\") {
return "'" + s + "'"
}
return s
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/gitcredentials/updater_test.go | pkg/cmd/auth/shared/gitcredentials/updater_test.go | package gitcredentials_test
import (
"bytes"
"context"
"fmt"
"path/filepath"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
"github.com/stretchr/testify/require"
)
func configureStoreCredentialHelper(t *testing.T) {
t.Helper()
tmpCredentialsFile := filepath.Join(t.TempDir(), "credentials")
gc := &git.Client{}
// Use `--file` to store credentials in a temporary file that gets cleaned up when the test has finished running
cmd, err := gc.Command(context.Background(), "config", "--global", "--add", "credential.helper", fmt.Sprintf("store --file %s", tmpCredentialsFile))
require.NoError(t, err)
require.NoError(t, cmd.Run())
}
func fillCredentials(t *testing.T) string {
gc := &git.Client{}
fillCmd, err := gc.Command(context.Background(), "credential", "fill")
require.NoError(t, err)
fillCmd.Stdin = bytes.NewBufferString(heredoc.Docf(`
protocol=https
host=%s
`, "github.com"))
b, err := fillCmd.Output()
require.NoError(t, err)
return string(b)
}
func TestUpdateAddsNewCredentials(t *testing.T) {
// Given we have an isolated git config and we're using the built in store credential helper
// https://git-scm.com/docs/git-credential-store
withIsolatedGitConfig(t)
configureStoreCredentialHelper(t)
// When we add new credentials
u := &gitcredentials.Updater{
GitClient: &git.Client{},
}
require.NoError(t, u.Update("github.com", "monalisa", "password"))
// Then our credential description is successfully filled
require.Equal(t, heredoc.Doc(`
protocol=https
host=github.com
username=monalisa
password=password
`), fillCredentials(t))
}
func TestUpdateReplacesOldCredentials(t *testing.T) {
// Given we have an isolated git config and we're using the built in store credential helper
// https://git-scm.com/docs/git-credential-store
// and we have existing credentials
withIsolatedGitConfig(t)
configureStoreCredentialHelper(t)
// When we replace old credentials
u := &gitcredentials.Updater{
GitClient: &git.Client{},
}
require.NoError(t, u.Update("github.com", "monalisa", "old-password"))
require.NoError(t, u.Update("github.com", "monalisa", "new-password"))
// Then our credential description is successfully filled
require.Equal(t, heredoc.Doc(`
protocol=https
host=github.com
username=monalisa
password=new-password
`), fillCredentials(t))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/gitcredentials/helper_config_test.go | pkg/cmd/auth/shared/gitcredentials/helper_config_test.go | package gitcredentials_test
import (
"context"
"path/filepath"
"runtime"
"testing"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/contract"
"github.com/cli/cli/v2/pkg/cmd/auth/shared/gitcredentials"
"github.com/stretchr/testify/require"
)
func withIsolatedGitConfig(t *testing.T) {
t.Helper()
// https://git-scm.com/docs/git-config#ENVIRONMENT
// Set the global git config to a temporary file
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, ".gitconfig")
t.Setenv("GIT_CONFIG_GLOBAL", configFile)
// And disable git reading the system config
t.Setenv("GIT_CONFIG_NOSYSTEM", "true")
}
func configureTestCredentialHelper(t *testing.T, key string) {
t.Helper()
gc := &git.Client{}
cmd, err := gc.Command(context.Background(), "config", "--global", "--add", key, "test-helper")
require.NoError(t, err)
require.NoError(t, cmd.Run())
}
func TestHelperConfigContract(t *testing.T) {
contract.HelperConfig{
NewHelperConfig: func(t *testing.T) shared.HelperConfig {
withIsolatedGitConfig(t)
return &gitcredentials.HelperConfig{
SelfExecutablePath: "/path/to/gh",
GitClient: &git.Client{},
}
},
ConfigureHelper: func(t *testing.T, hostname string) {
configureTestCredentialHelper(t, hostname)
},
}.Test(t)
}
// This is a whitebox test unlike the contract because although we don't use the exact configured command, it's
// important that it is exactly right since git uses it.
func TestSetsCorrectCommandInGitConfig(t *testing.T) {
withIsolatedGitConfig(t)
gc := &git.Client{}
hc := &gitcredentials.HelperConfig{
SelfExecutablePath: "/path/to/gh",
GitClient: gc,
}
require.NoError(t, hc.ConfigureOurs("github.com"))
// Check that the correct command was set in the git config
cmd, err := gc.Command(context.Background(), "config", "--get", "credential.https://github.com.helper")
require.NoError(t, err)
output, err := cmd.Output()
require.NoError(t, err)
require.Equal(t, "!/path/to/gh auth git-credential\n", string(output))
}
func TestHelperIsOurs(t *testing.T) {
tests := []struct {
name string
cmd string
want bool
windowsOnly bool
}{
{
name: "blank",
cmd: "",
want: false,
},
{
name: "invalid",
cmd: "!",
want: false,
},
{
name: "osxkeychain",
cmd: "osxkeychain",
want: false,
},
{
name: "looks like gh but isn't",
cmd: "gh auth",
want: false,
},
{
name: "ours",
cmd: "!/path/to/gh auth",
want: true,
},
{
name: "ours - Windows edition",
cmd: `!'C:\Program Files\GitHub CLI\gh.exe' auth git-credential`,
want: true,
windowsOnly: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.windowsOnly && runtime.GOOS != "windows" {
t.Skip("skipping test on non-Windows platform")
}
h := gitcredentials.Helper{Cmd: tt.cmd}
if got := h.IsOurs(); got != tt.want {
t.Errorf("IsOurs() = %v, want %v", got, tt.want)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/gitcredentials/fake_helper_config.go | pkg/cmd/auth/shared/gitcredentials/fake_helper_config.go | package gitcredentials
import (
"fmt"
"strings"
"github.com/cli/cli/v2/internal/ghinstance"
)
type FakeHelperConfig struct {
SelfExecutablePath string
Helpers map[string]Helper
}
// ConfigureOurs sets up the git credential helper chain to use the GitHub CLI credential helper for git repositories
// including gists.
func (hc *FakeHelperConfig) ConfigureOurs(hostname string) error {
credHelperKeys := []string{
keyFor(hostname),
}
gistHost := strings.TrimSuffix(ghinstance.GistHost(hostname), "/")
if strings.HasPrefix(gistHost, "gist.") {
credHelperKeys = append(credHelperKeys, keyFor(gistHost))
}
for _, credHelperKey := range credHelperKeys {
hc.Helpers[credHelperKey] = Helper{
Cmd: fmt.Sprintf("!%s auth git-credential", shellQuote(hc.SelfExecutablePath)),
}
}
return nil
}
// ConfiguredHelper returns the configured git credential helper for a given hostname.
func (hc *FakeHelperConfig) ConfiguredHelper(hostname string) (Helper, error) {
helper, ok := hc.Helpers[keyFor(hostname)]
if ok {
return helper, nil
}
helper, ok = hc.Helpers["credential.helper"]
if ok {
return helper, nil
}
return Helper{}, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/gitcredentials/updater.go | pkg/cmd/auth/shared/gitcredentials/updater.go | package gitcredentials
import (
"bytes"
"context"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/git"
)
// An Updater is used to update the git credentials for a given hostname.
type Updater struct {
GitClient *git.Client
}
// Update updates the git credentials for a given hostname, first by rejecting any existing credentials and then
// approving the new credentials.
func (u *Updater) Update(hostname, username, password string) error {
ctx := context.TODO()
// clear previous cached credentials
rejectCmd, err := u.GitClient.Command(ctx, "credential", "reject")
if err != nil {
return err
}
rejectCmd.Stdin = bytes.NewBufferString(heredoc.Docf(`
protocol=https
host=%s
`, hostname))
_, err = rejectCmd.Output()
if err != nil {
return err
}
approveCmd, err := u.GitClient.Command(ctx, "credential", "approve")
if err != nil {
return err
}
approveCmd.Stdin = bytes.NewBufferString(heredoc.Docf(`
protocol=https
host=%s
username=%s
password=%s
`, hostname, username, password))
_, err = approveCmd.Output()
if err != nil {
return err
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/shared/contract/helper_config.go | pkg/cmd/auth/shared/contract/helper_config.go | package contract
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/stretchr/testify/require"
)
// This HelperConfig contract exist to ensure that any HelperConfig implementation conforms to this behaviour.
// This is useful because we can swap in fake implementations for testing, rather than requiring our tests to be
// isolated from git.
//
// See for example, TestAuthenticatingGitCredentials for LoginFlow.
type HelperConfig struct {
NewHelperConfig func(t *testing.T) shared.HelperConfig
ConfigureHelper func(t *testing.T, hostname string)
}
func (contract HelperConfig) Test(t *testing.T) {
t.Run("when there are no credential helpers, configures gh for repo and gist host", func(t *testing.T) {
hc := contract.NewHelperConfig(t)
require.NoError(t, hc.ConfigureOurs("github.com"))
repoHelper, err := hc.ConfiguredHelper("github.com")
require.NoError(t, err)
require.True(t, repoHelper.IsConfigured(), "expected our helper to be configured")
require.True(t, repoHelper.IsOurs(), "expected the helper to be ours but was %q", repoHelper.Cmd)
gistHelper, err := hc.ConfiguredHelper("gist.github.com")
require.NoError(t, err)
require.True(t, gistHelper.IsConfigured(), "expected our helper to be configured")
require.True(t, gistHelper.IsOurs(), "expected the helper to be ours but was %q", gistHelper.Cmd)
})
t.Run("when there is a global credential helper, it should be configured but not ours", func(t *testing.T) {
hc := contract.NewHelperConfig(t)
contract.ConfigureHelper(t, "credential.helper")
helper, err := hc.ConfiguredHelper("github.com")
require.NoError(t, err)
require.True(t, helper.IsConfigured(), "expected helper to be configured")
require.False(t, helper.IsOurs(), "expected the helper not to be ours but was %q", helper.Cmd)
})
t.Run("when there is a host credential helper, it should be configured but not ours", func(t *testing.T) {
hc := contract.NewHelperConfig(t)
contract.ConfigureHelper(t, "credential.https://github.com.helper")
helper, err := hc.ConfiguredHelper("github.com")
require.NoError(t, err)
require.True(t, helper.IsConfigured(), "expected helper to be configured")
require.False(t, helper.IsOurs(), "expected the helper not to be ours but was %q", helper.Cmd)
})
t.Run("returns non configured helper when no helpers are configured", func(t *testing.T) {
hc := contract.NewHelperConfig(t)
helper, err := hc.ConfiguredHelper("github.com")
require.NoError(t, err)
require.False(t, helper.IsConfigured(), "expected no helper to be configured")
require.False(t, helper.IsOurs(), "expected the helper not to be ours but was %q", helper.Cmd)
})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/gitcredential/helper.go | pkg/cmd/auth/gitcredential/helper.go | package login
import (
"bufio"
"fmt"
"net/url"
"strings"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
const tokenUser = "x-access-token"
type config interface {
ActiveToken(string) (string, string)
ActiveUser(string) (string, error)
}
type CredentialOptions struct {
IO *iostreams.IOStreams
Config func() (config, error)
Operation string
}
func NewCmdCredential(f *cmdutil.Factory, runF func(*CredentialOptions) error) *cobra.Command {
opts := &CredentialOptions{
IO: f.IOStreams,
Config: func() (config, error) {
cfg, err := f.Config()
if err != nil {
return nil, err
}
return cfg.Authentication(), nil
},
}
cmd := &cobra.Command{
Use: "git-credential",
Args: cobra.ExactArgs(1),
Short: "Implements git credential helper protocol",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
opts.Operation = args[0]
if runF != nil {
return runF(opts)
}
return helperRun(opts)
},
}
return cmd
}
func helperRun(opts *CredentialOptions) error {
if opts.Operation == "store" {
// We pretend to implement the "store" operation, but do nothing since we already have a cached token.
return nil
}
if opts.Operation == "erase" {
// We pretend to implement the "erase" operation, but do nothing since we don't want git to cause user to be logged out.
return nil
}
if opts.Operation != "get" {
return fmt.Errorf("gh auth git-credential: %q operation not supported", opts.Operation)
}
wants := map[string]string{}
s := bufio.NewScanner(opts.IO.In)
for s.Scan() {
line := s.Text()
if line == "" {
break
}
parts := strings.SplitN(line, "=", 2)
if len(parts) < 2 {
continue
}
key, value := parts[0], parts[1]
if key == "url" {
u, err := url.Parse(value)
if err != nil {
return err
}
wants["protocol"] = u.Scheme
wants["host"] = u.Host
wants["path"] = u.Path
wants["username"] = u.User.Username()
wants["password"], _ = u.User.Password()
} else {
wants[key] = value
}
}
if err := s.Err(); err != nil {
return err
}
if wants["protocol"] != "https" {
return cmdutil.SilentError
}
cfg, err := opts.Config()
if err != nil {
return err
}
lookupHost := wants["host"]
var gotUser string
gotToken, source := cfg.ActiveToken(lookupHost)
if gotToken == "" && strings.HasPrefix(lookupHost, "gist.") {
lookupHost = strings.TrimPrefix(lookupHost, "gist.")
gotToken, source = cfg.ActiveToken(lookupHost)
}
if strings.HasSuffix(source, "_TOKEN") {
gotUser = tokenUser
} else {
gotUser, _ = cfg.ActiveUser(lookupHost)
if gotUser == "" {
gotUser = tokenUser
}
}
if gotUser == "" || gotToken == "" {
return cmdutil.SilentError
}
if wants["username"] != "" && gotUser != tokenUser && !strings.EqualFold(wants["username"], gotUser) {
return cmdutil.SilentError
}
fmt.Fprint(opts.IO.Out, "protocol=https\n")
fmt.Fprintf(opts.IO.Out, "host=%s\n", wants["host"])
fmt.Fprintf(opts.IO.Out, "username=%s\n", gotUser)
fmt.Fprintf(opts.IO.Out, "password=%s\n", gotToken)
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/auth/gitcredential/helper_test.go | pkg/cmd/auth/gitcredential/helper_test.go | package login
import (
"fmt"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/iostreams"
)
type tinyConfig map[string]string
func (c tinyConfig) ActiveToken(host string) (string, string) {
return c[fmt.Sprintf("%s:%s", host, "oauth_token")], c["_source"]
}
func (c tinyConfig) ActiveUser(host string) (string, error) {
return c[fmt.Sprintf("%s:%s", host, "user")], nil
}
func Test_helperRun(t *testing.T) {
tests := []struct {
name string
opts CredentialOptions
input string
wantStdout string
wantStderr string
wantErr bool
}{
{
name: "host only, credentials found",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "/Users/monalisa/.config/gh/hosts.yml",
"example.com:user": "monalisa",
"example.com:oauth_token": "OTOKEN",
}, nil
},
},
input: heredoc.Doc(`
protocol=https
host=example.com
`),
wantErr: false,
wantStdout: heredoc.Doc(`
protocol=https
host=example.com
username=monalisa
password=OTOKEN
`),
wantStderr: "",
},
{
name: "host plus user",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "/Users/monalisa/.config/gh/hosts.yml",
"example.com:user": "monalisa",
"example.com:oauth_token": "OTOKEN",
}, nil
},
},
input: heredoc.Doc(`
protocol=https
host=example.com
username=monalisa
`),
wantErr: false,
wantStdout: heredoc.Doc(`
protocol=https
host=example.com
username=monalisa
password=OTOKEN
`),
wantStderr: "",
},
{
name: "gist host",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "/Users/monalisa/.config/gh/hosts.yml",
"github.com:user": "monalisa",
"github.com:oauth_token": "OTOKEN",
}, nil
},
},
input: heredoc.Doc(`
protocol=https
host=gist.github.com
username=monalisa
`),
wantErr: false,
wantStdout: heredoc.Doc(`
protocol=https
host=gist.github.com
username=monalisa
password=OTOKEN
`),
wantStderr: "",
},
{
name: "url input",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "/Users/monalisa/.config/gh/hosts.yml",
"example.com:user": "monalisa",
"example.com:oauth_token": "OTOKEN",
}, nil
},
},
input: heredoc.Doc(`
url=https://monalisa@example.com
`),
wantErr: false,
wantStdout: heredoc.Doc(`
protocol=https
host=example.com
username=monalisa
password=OTOKEN
`),
wantStderr: "",
},
{
name: "host only, no credentials found",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "/Users/monalisa/.config/gh/hosts.yml",
"example.com:user": "monalisa",
}, nil
},
},
input: heredoc.Doc(`
protocol=https
host=example.com
`),
wantErr: true,
wantStdout: "",
wantStderr: "",
},
{
name: "user mismatch",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "/Users/monalisa/.config/gh/hosts.yml",
"example.com:user": "monalisa",
"example.com:oauth_token": "OTOKEN",
}, nil
},
},
input: heredoc.Doc(`
protocol=https
host=example.com
username=hubot
`),
wantErr: true,
wantStdout: "",
wantStderr: "",
},
{
name: "no username configured",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "/Users/monalisa/.config/gh/hosts.yml",
"example.com:oauth_token": "OTOKEN",
}, nil
},
},
input: heredoc.Doc(`
protocol=https
host=example.com
`),
wantErr: false,
wantStdout: heredoc.Doc(`
protocol=https
host=example.com
username=x-access-token
password=OTOKEN
`),
wantStderr: "",
},
{
name: "token from env",
opts: CredentialOptions{
Operation: "get",
Config: func() (config, error) {
return tinyConfig{
"_source": "GITHUB_ENTERPRISE_TOKEN",
"example.com:oauth_token": "OTOKEN",
}, nil
},
},
input: heredoc.Doc(`
protocol=https
host=example.com
username=hubot
`),
wantErr: false,
wantStdout: heredoc.Doc(`
protocol=https
host=example.com
username=x-access-token
password=OTOKEN
`),
wantStderr: "",
},
{
name: "noop store operation",
opts: CredentialOptions{
Operation: "store",
},
},
{
name: "noop erase operation",
opts: CredentialOptions{
Operation: "erase",
},
},
{
name: "unknown operation",
opts: CredentialOptions{
Operation: "unknown",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, stdout, stderr := iostreams.Test()
fmt.Fprint(stdin, tt.input)
opts := &tt.opts
opts.IO = ios
if err := helperRun(opts); (err != nil) != tt.wantErr {
t.Fatalf("helperRun() error = %v, wantErr %v", err, tt.wantErr)
}
if tt.wantStdout != stdout.String() {
t.Errorf("stdout: got %q, wants %q", stdout.String(), tt.wantStdout)
}
if tt.wantStderr != stderr.String() {
t.Errorf("stderr: got %q, wants %q", stderr.String(), tt.wantStderr)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/ruleset.go | pkg/cmd/ruleset/ruleset.go | package ruleset
import (
"github.com/MakeNowJust/heredoc"
cmdCheck "github.com/cli/cli/v2/pkg/cmd/ruleset/check"
cmdList "github.com/cli/cli/v2/pkg/cmd/ruleset/list"
cmdView "github.com/cli/cli/v2/pkg/cmd/ruleset/view"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdRuleset(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "ruleset <command>",
Short: "View info about repo rulesets",
Long: heredoc.Doc(`
Repository rulesets are a way to define a set of rules that apply to a repository.
These commands allow you to view information about them.
`),
Aliases: []string{"rs"},
Example: heredoc.Doc(`
$ gh ruleset list
$ gh ruleset view --repo OWNER/REPO --web
$ gh ruleset check branch-name
`),
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.AddCommand(cmdList.NewCmdList(f, nil))
cmd.AddCommand(cmdView.NewCmdView(f, nil))
cmd.AddCommand(cmdCheck.NewCmdCheck(f, nil))
return cmd
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/list/list_test.go | pkg/cmd/ruleset/list/list_test.go | package list
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/ruleset/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdList(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want ListOptions
wantErr string
}{
{
name: "no arguments",
args: "",
isTTY: true,
want: ListOptions{
Limit: 30,
IncludeParents: true,
WebMode: false,
Organization: "",
},
},
{
name: "limit",
args: "--limit 1",
isTTY: true,
want: ListOptions{
Limit: 1,
IncludeParents: true,
WebMode: false,
Organization: "",
},
},
{
name: "include parents",
args: "--parents=false",
isTTY: true,
want: ListOptions{
Limit: 30,
IncludeParents: false,
WebMode: false,
Organization: "",
},
},
{
name: "org",
args: "--org \"my-org\"",
isTTY: true,
want: ListOptions{
Limit: 30,
IncludeParents: true,
WebMode: false,
Organization: "my-org",
},
},
{
name: "web mode",
args: "--web",
isTTY: true,
want: ListOptions{
Limit: 30,
IncludeParents: true,
WebMode: true,
Organization: "",
},
},
{
name: "invalid limit",
args: "--limit 0",
isTTY: true,
wantErr: "invalid limit: 0",
},
{
name: "repo and org specified",
args: "--org \"my-org\" -R \"owner/repo\"",
isTTY: true,
wantErr: "only one of --repo and --org may be specified",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *ListOptions
cmd := NewCmdList(f, func(o *ListOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.Limit, opts.Limit)
assert.Equal(t, tt.want.WebMode, opts.WebMode)
assert.Equal(t, tt.want.Organization, opts.Organization)
})
}
}
func Test_listRun(t *testing.T) {
tests := []struct {
name string
isTTY bool
opts ListOptions
httpStubs func(*httpmock.Registry)
wantErr string
wantStdout string
wantStderr string
wantBrowse string
}{
{
name: "list repo rulesets",
isTTY: true,
wantStdout: heredoc.Doc(`
Showing 3 of 3 rulesets in OWNER/REPO
ID NAME SOURCE STATUS RULES
4 test OWNER/REPO (repo) evaluate 1
42 asdf OWNER/REPO (repo) active 2
77 foobar Org-Name (org) disabled 4
`),
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query RepoRulesetList\b`),
httpmock.FileResponse("./fixtures/rulesetList.json"),
)
},
wantStderr: "",
wantBrowse: "",
},
{
name: "list org rulesets",
isTTY: true,
opts: ListOptions{
IncludeParents: true,
Organization: "my-org",
},
wantStdout: heredoc.Doc(`
Showing 3 of 3 rulesets in my-org and its parents
ID NAME SOURCE STATUS RULES
4 test OWNER/REPO (repo) evaluate 1
42 asdf OWNER/REPO (repo) active 2
77 foobar Org-Name (org) disabled 4
`),
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query OrgRulesetList\b`),
httpmock.FileResponse("./fixtures/rulesetList.json"),
)
},
wantStderr: "",
wantBrowse: "",
},
{
name: "list repo rulesets, no rulesets",
isTTY: true,
opts: ListOptions{
IncludeParents: true,
},
wantStdout: "",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query RepoRulesetList\b`),
httpmock.JSONResponse(shared.RulesetList{
TotalCount: 0,
Rulesets: []shared.RulesetGraphQL{},
}),
)
},
wantErr: "no rulesets found in OWNER/REPO or its parents",
wantStderr: "",
wantBrowse: "",
},
{
name: "list org rulesets, no rulesets",
isTTY: true,
opts: ListOptions{
Organization: "my-org",
},
wantStdout: "",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query OrgRulesetList\b`),
httpmock.JSONResponse(shared.RulesetList{
TotalCount: 0,
Rulesets: []shared.RulesetGraphQL{},
}),
)
},
wantErr: "no rulesets found in my-org",
wantBrowse: "",
},
{
name: "machine-readable",
isTTY: false,
wantStdout: heredoc.Doc(`
4 test OWNER/REPO (repo) evaluate 1
42 asdf OWNER/REPO (repo) active 2
77 foobar Org-Name (org) disabled 4
`),
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query RepoRulesetList\b`),
httpmock.FileResponse("./fixtures/rulesetList.json"),
)
},
wantStderr: "",
wantBrowse: "",
},
{
name: "repo web mode, TTY",
isTTY: true,
opts: ListOptions{
WebMode: true,
},
wantStdout: "Opening https://github.com/OWNER/REPO/rules in your browser.\n",
wantStderr: "",
wantBrowse: "https://github.com/OWNER/REPO/rules",
},
{
name: "org web mode, TTY",
isTTY: true,
opts: ListOptions{
WebMode: true,
Organization: "my-org",
},
wantStdout: "Opening https://github.com/organizations/my-org/settings/rules in your browser.\n",
wantStderr: "",
wantBrowse: "https://github.com/organizations/my-org/settings/rules",
},
{
name: "repo web mode, non-TTY",
isTTY: false,
opts: ListOptions{
WebMode: true,
},
wantStdout: "",
wantStderr: "",
wantBrowse: "https://github.com/OWNER/REPO/rules",
},
{
name: "org web mode, non-TTY",
isTTY: false,
opts: ListOptions{
WebMode: true,
Organization: "my-org",
},
wantStdout: "",
wantStderr: "",
wantBrowse: "https://github.com/organizations/my-org/settings/rules",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
// only set this if org is not set, because the repo isn't needed if --org is provided and
// leaving it undefined will catch potential errors
if tt.opts.Organization == "" {
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
}
browser := &browser.Stub{}
tt.opts.Browser = browser
err := listRun(&tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
if tt.wantBrowse != "" {
browser.Verify(t, tt.wantBrowse)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/list/list.go | pkg/cmd/ruleset/list/list.go | package list
import (
"fmt"
"net/http"
"strconv"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/ruleset/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
"github.com/spf13/cobra"
)
type ListOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Browser browser.Browser
Limit int
IncludeParents bool
WebMode bool
Organization string
}
func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
opts := &ListOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Browser: f.Browser,
}
cmd := &cobra.Command{
Use: "list",
Short: "List rulesets for a repository or organization",
Long: heredoc.Docf(`
List GitHub rulesets for a repository or organization.
If no options are provided, the current repository's rulesets are listed. You can query a different
repository's rulesets by using the %[1]s--repo%[1]s flag. You can also use the %[1]s--org%[1]s flag to list rulesets
configured for the provided organization.
Use the %[1]s--parents%[1]s flag to control whether rulesets configured at higher levels that also apply to the provided
repository or organization should be returned. The default is %[1]strue%[1]s.
Your access token must have the %[1]sadmin:org%[1]s scope to use the %[1]s--org%[1]s flag, which can be granted by running %[1]sgh auth refresh -s admin:org%[1]s.
`, "`"),
Example: heredoc.Doc(`
# List rulesets in the current repository
$ gh ruleset list
# List rulesets in a different repository, including those configured at higher levels
$ gh ruleset list --repo owner/repo --parents
# List rulesets in an organization
$ gh ruleset list --org org-name
`),
Aliases: []string{"ls"},
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && opts.Organization != "" {
return cmdutil.FlagErrorf("only one of --repo and --org may be specified")
}
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if opts.Limit < 1 {
return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
}
if runF != nil {
return runF(opts)
}
return listRun(opts)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum number of rulesets to list")
cmd.Flags().StringVarP(&opts.Organization, "org", "o", "", "List organization-wide rulesets for the provided organization")
cmd.Flags().BoolVarP(&opts.IncludeParents, "parents", "p", true, "Whether to include rulesets configured at higher levels that also apply")
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the list of rulesets in the web browser")
return cmd
}
func listRun(opts *ListOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
var repoI ghrepo.Interface
// only one of the repo or org context is necessary
if opts.Organization == "" {
var repoErr error
repoI, repoErr = opts.BaseRepo()
if repoErr != nil {
return repoErr
}
}
hostname, _ := ghauth.DefaultHost()
if opts.WebMode {
var rulesetURL string
if opts.Organization != "" {
rulesetURL = fmt.Sprintf("%sorganizations/%s/settings/rules", ghinstance.HostPrefix(hostname), opts.Organization)
} else {
rulesetURL = ghrepo.GenerateRepoURL(repoI, "rules")
}
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(rulesetURL))
}
return opts.Browser.Browse(rulesetURL)
}
var result *shared.RulesetList
if opts.Organization != "" {
result, err = shared.ListOrgRulesets(httpClient, opts.Organization, opts.Limit, hostname, opts.IncludeParents)
} else {
result, err = shared.ListRepoRulesets(httpClient, repoI, opts.Limit, opts.IncludeParents)
}
if err != nil {
return err
}
if result.TotalCount == 0 {
return shared.NoRulesetsFoundError(opts.Organization, repoI, opts.IncludeParents)
}
opts.IO.DetectTerminalTheme()
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
cs := opts.IO.ColorScheme()
if opts.IO.IsStdoutTTY() {
parentsMsg := ""
if opts.IncludeParents {
parentsMsg = " and its parents"
}
inMsg := fmt.Sprintf("%s%s", shared.EntityName(opts.Organization, repoI), parentsMsg)
fmt.Fprintf(opts.IO.Out, "\nShowing %d of %d rulesets in %s\n\n", len(result.Rulesets), result.TotalCount, inMsg)
}
tp := tableprinter.New(opts.IO, tableprinter.WithHeader("ID", "NAME", "SOURCE", "STATUS", "RULES"))
for _, rs := range result.Rulesets {
tp.AddField(strconv.Itoa(rs.DatabaseId), tableprinter.WithColor(cs.Cyan))
tp.AddField(rs.Name, tableprinter.WithColor(cs.Bold))
tp.AddField(shared.RulesetSource(rs))
tp.AddField(strings.ToLower(rs.Enforcement))
tp.AddField(strconv.Itoa(rs.Rules.TotalCount))
tp.EndRow()
}
return tp.Render()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/check/check.go | pkg/cmd/ruleset/check/check.go | package check
import (
"context"
"fmt"
"net/http"
"net/url"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/ruleset/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type CheckOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Config func() (gh.Config, error)
BaseRepo func() (ghrepo.Interface, error)
Git *git.Client
Browser browser.Browser
Branch string
Default bool
WebMode bool
}
func NewCmdCheck(f *cmdutil.Factory, runF func(*CheckOptions) error) *cobra.Command {
opts := &CheckOptions{
IO: f.IOStreams,
Config: f.Config,
HttpClient: f.HttpClient,
Browser: f.Browser,
Git: f.GitClient,
}
cmd := &cobra.Command{
Use: "check [<branch>]",
Short: "View rules that would apply to a given branch",
Long: heredoc.Docf(`
View information about GitHub rules that apply to a given branch.
The provided branch name does not need to exist; rules will be displayed that would apply
to a branch with that name. All rules are returned regardless of where they are configured.
If no branch name is provided, then the current branch will be used.
The %[1]s--default%[1]s flag can be used to view rules that apply to the default branch of the
repository.
`, "`"),
Example: heredoc.Doc(`
# View all rules that apply to the current branch
$ gh ruleset check
# View all rules that apply to a branch named "my-branch" in a different repository
$ gh ruleset check my-branch --repo owner/repo
# View all rules that apply to the default branch in a different repository
$ gh ruleset check --default --repo owner/repo
# View a ruleset configured in a different repository or any of its parents
$ gh ruleset view 23 --repo owner/repo
# View an organization-level ruleset
$ gh ruleset view 23 --org my-org
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if len(args) > 0 {
opts.Branch = args[0]
}
if err := cmdutil.MutuallyExclusive(
"specify only one of `--default` or a branch name",
opts.Branch != "",
opts.Default,
); err != nil {
return err
}
if runF != nil {
return runF(opts)
}
return checkRun(opts)
},
}
cmd.Flags().BoolVar(&opts.Default, "default", false, "Check rules on default branch")
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the branch rules page in a web browser")
return cmd
}
func checkRun(opts *CheckOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
client := api.NewClientFromHTTP(httpClient)
repoI, err := opts.BaseRepo()
if err != nil {
return fmt.Errorf("could not determine repo to use: %w", err)
}
git := opts.Git
if opts.Default {
repo, err := api.GitHubRepo(client, repoI)
if err != nil {
return fmt.Errorf("could not get repository information: %w", err)
}
opts.Branch = repo.DefaultBranchRef.Name
}
if opts.Branch == "" {
opts.Branch, err = git.CurrentBranch(context.Background())
if err != nil {
return fmt.Errorf("could not determine current branch: %w", err)
}
}
if opts.WebMode {
// the query string parameter may have % signs in it, so it must be carefully used with Printf functions
queryString := fmt.Sprintf("?ref=%s", url.QueryEscape("refs/heads/"+opts.Branch))
rawUrl := ghrepo.GenerateRepoURL(repoI, "rules")
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(rawUrl))
}
return opts.Browser.Browse(rawUrl + queryString)
}
var rules []shared.RulesetRule
endpoint := fmt.Sprintf("repos/%s/%s/rules/branches/%s", repoI.RepoOwner(), repoI.RepoName(), url.PathEscape(opts.Branch))
if err = client.REST(repoI.RepoHost(), "GET", endpoint, nil, &rules); err != nil {
return fmt.Errorf("GET %s failed: %w", endpoint, err)
}
w := opts.IO.Out
fmt.Fprintf(w, "%d rules apply to branch %s in repo %s/%s\n", len(rules), opts.Branch, repoI.RepoOwner(), repoI.RepoName())
if len(rules) > 0 {
fmt.Fprint(w, "\n")
fmt.Fprint(w, shared.ParseRulesForDisplay(rules))
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/check/check_test.go | pkg/cmd/ruleset/check/check_test.go | package check
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdCheck(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want CheckOptions
wantErr string
}{
{
name: "no arguments",
args: "",
isTTY: true,
want: CheckOptions{
Branch: "",
Default: false,
WebMode: false,
},
},
{
name: "branch name",
args: "my-branch",
isTTY: true,
want: CheckOptions{
Branch: "my-branch",
Default: false,
WebMode: false,
},
},
{
name: "default",
args: "--default=true",
isTTY: true,
want: CheckOptions{
Branch: "",
Default: true,
WebMode: false,
},
},
{
name: "web mode",
args: "--web",
isTTY: true,
want: CheckOptions{
Branch: "",
Default: false,
WebMode: true,
},
},
{
name: "both --default and branch name specified",
args: "--default asdf",
isTTY: true,
wantErr: "specify only one of `--default` or a branch name",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *CheckOptions
cmd := NewCmdCheck(f, func(o *CheckOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.Branch, opts.Branch)
assert.Equal(t, tt.want.Default, opts.Default)
assert.Equal(t, tt.want.WebMode, opts.WebMode)
})
}
}
func Test_checkRun(t *testing.T) {
tests := []struct {
name string
isTTY bool
opts CheckOptions
wantErr string
wantStdout string
wantStderr string
wantBrowse string
}{
{
name: "view rules for branch",
isTTY: true,
opts: CheckOptions{
Branch: "my-branch",
},
wantStdout: heredoc.Doc(`
6 rules apply to branch my-branch in repo my-org/repo-name
- commit_author_email_pattern: [name: ] [negate: false] [operator: ends_with] [pattern: @example.com]
(configured in ruleset 1234 from organization my-org)
- commit_author_email_pattern: [name: ] [negate: false] [operator: ends_with] [pattern: @example.com]
(configured in ruleset 5678 from repository my-org/repo-name)
- commit_message_pattern: [name: ] [negate: false] [operator: starts_with] [pattern: fff]
(configured in ruleset 1234 from organization my-org)
- commit_message_pattern: [name: ] [negate: false] [operator: contains] [pattern: asdf]
(configured in ruleset 5678 from repository my-org/repo-name)
- creation
(configured in ruleset 5678 from repository my-org/repo-name)
- required_signatures
(configured in ruleset 1234 from organization my-org)
`),
wantStderr: "",
wantBrowse: "",
},
{
name: "web mode, TTY",
isTTY: true,
opts: CheckOptions{
Branch: "my-branch",
WebMode: true,
},
wantStdout: "Opening https://github.com/my-org/repo-name/rules in your browser.\n",
wantStderr: "",
wantBrowse: "https://github.com/my-org/repo-name/rules?ref=refs%2Fheads%2Fmy-branch",
},
{
name: "web mode, TTY, special character in branch name",
isTTY: true,
opts: CheckOptions{
Branch: "my-feature/my-branch",
WebMode: true,
},
wantStdout: "Opening https://github.com/my-org/repo-name/rules in your browser.\n",
wantStderr: "",
wantBrowse: "https://github.com/my-org/repo-name/rules?ref=refs%2Fheads%2Fmy-feature%2Fmy-branch",
},
{
name: "web mode, non-TTY",
isTTY: false,
opts: CheckOptions{
Branch: "my-branch",
WebMode: true,
},
wantStdout: "",
wantStderr: "",
wantBrowse: "https://github.com/my-org/repo-name/rules?ref=refs%2Fheads%2Fmy-branch",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
fakeHTTP := &httpmock.Registry{}
fakeHTTP.Register(
httpmock.REST("GET", "repos/my-org/repo-name/rules/branches/my-branch"),
httpmock.FileResponse("./fixtures/rulesetCheck.json"),
)
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: fakeHTTP}, nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("my-org/repo-name")
}
browser := &browser.Stub{}
tt.opts.Browser = browser
err := checkRun(&tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
if tt.wantBrowse != "" {
browser.Verify(t, tt.wantBrowse)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/view/view.go | pkg/cmd/ruleset/view/view.go | package view
import (
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/ruleset/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
"github.com/spf13/cobra"
)
type ViewOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Browser browser.Browser
Prompter prompter.Prompter
ID string
WebMode bool
IncludeParents bool
InteractiveMode bool
Organization string
}
func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command {
opts := &ViewOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Browser: f.Browser,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "view [<ruleset-id>]",
Short: "View information about a ruleset",
Long: heredoc.Docf(`
View information about a GitHub ruleset.
If no ID is provided, an interactive prompt will be used to choose
the ruleset to view.
Use the %[1]s--parents%[1]s flag to control whether rulesets configured at higher
levels that also apply to the provided repository or organization should
be returned. The default is %[1]strue%[1]s.
`, "`"),
Example: heredoc.Doc(`
# Interactively choose a ruleset to view from all rulesets that apply to the current repository
$ gh ruleset view
# Interactively choose a ruleset to view from only rulesets configured in the current repository
$ gh ruleset view --no-parents
# View a ruleset configured in the current repository or any of its parents
$ gh ruleset view 43
# View a ruleset configured in a different repository or any of its parents
$ gh ruleset view 23 --repo owner/repo
# View an organization-level ruleset
$ gh ruleset view 23 --org my-org
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && opts.Organization != "" {
return cmdutil.FlagErrorf("only one of --repo and --org may be specified")
}
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if len(args) > 0 {
// a string is actually needed later on, so verify that it's numeric
// but use the string anyway
_, err := strconv.Atoi(args[0])
if err != nil {
return cmdutil.FlagErrorf("invalid value for ruleset ID: %v is not an integer", args[0])
}
opts.ID = args[0]
} else if !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("a ruleset ID must be provided when not running interactively")
} else {
opts.InteractiveMode = true
}
if runF != nil {
return runF(opts)
}
return viewRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the ruleset in the browser")
cmd.Flags().StringVarP(&opts.Organization, "org", "o", "", "Organization name if the provided ID is an organization-level ruleset")
cmd.Flags().BoolVarP(&opts.IncludeParents, "parents", "p", true, "Whether to include rulesets configured at higher levels that also apply")
return cmd
}
func viewRun(opts *ViewOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
var repoI ghrepo.Interface
// only one of the repo or org context is necessary
if opts.Organization == "" {
var repoErr error
repoI, repoErr = opts.BaseRepo()
if repoErr != nil {
return repoErr
}
}
hostname, _ := ghauth.DefaultHost()
cs := opts.IO.ColorScheme()
if opts.InteractiveMode {
var rsList *shared.RulesetList
limit := 30
if opts.Organization != "" {
rsList, err = shared.ListOrgRulesets(httpClient, opts.Organization, limit, hostname, opts.IncludeParents)
} else {
rsList, err = shared.ListRepoRulesets(httpClient, repoI, limit, opts.IncludeParents)
}
if err != nil {
return err
}
if rsList.TotalCount == 0 {
return shared.NoRulesetsFoundError(opts.Organization, repoI, opts.IncludeParents)
}
rs, err := selectRulesetID(rsList, opts.Prompter, cs)
if err != nil {
return err
}
if rs != nil {
opts.ID = strconv.Itoa(rs.DatabaseId)
// can't get a ruleset lower in the chain than what was queried, so no need to handle repos here
if rs.Source.TypeName == "Organization" {
opts.Organization = rs.Source.Owner
}
}
}
var rs *shared.RulesetREST
if opts.Organization != "" {
rs, err = viewOrgRuleset(httpClient, opts.Organization, opts.ID, hostname)
} else {
rs, err = viewRepoRuleset(httpClient, repoI, opts.ID)
}
if err != nil {
return err
}
w := opts.IO.Out
if opts.WebMode {
if rs != nil {
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(rs.Links.Html.Href))
}
return opts.Browser.Browse(rs.Links.Html.Href)
} else {
fmt.Fprintf(w, "ruleset not found\n")
}
}
fmt.Fprintf(w, "\n%s\n", cs.Bold(rs.Name))
fmt.Fprintf(w, "ID: %s\n", cs.Cyan(strconv.Itoa(rs.Id)))
fmt.Fprintf(w, "Source: %s (%s)\n", rs.Source, rs.SourceType)
fmt.Fprint(w, "Enforcement: ")
switch rs.Enforcement {
case "disabled":
fmt.Fprintf(w, "%s\n", cs.Red("Disabled"))
case "evaluate":
fmt.Fprintf(w, "%s\n", cs.Yellow("Evaluate Mode (not enforced)"))
case "active":
fmt.Fprintf(w, "%s\n", cs.Green("Active"))
default:
fmt.Fprintf(w, "%s\n", rs.Enforcement)
}
if rs.CurrentUserCanBypass != "" {
fmt.Fprintf(w, "You can bypass: %s\n", strings.ReplaceAll(rs.CurrentUserCanBypass, "_", " "))
}
fmt.Fprintf(w, "\n%s\n", cs.Bold("Bypass List"))
if len(rs.BypassActors) == 0 {
fmt.Fprintf(w, "This ruleset cannot be bypassed\n")
} else {
sort.Slice(rs.BypassActors, func(i, j int) bool {
return rs.BypassActors[i].ActorId < rs.BypassActors[j].ActorId
})
for _, t := range rs.BypassActors {
fmt.Fprintf(w, "- %s (ID: %d), mode: %s\n", t.ActorType, t.ActorId, t.BypassMode)
}
}
fmt.Fprintf(w, "\n%s\n", cs.Bold("Conditions"))
if len(rs.Conditions) == 0 {
fmt.Fprintf(w, "No conditions configured\n")
} else {
// sort keys for consistent responses
keys := make([]string, 0, len(rs.Conditions))
for key := range rs.Conditions {
keys = append(keys, key)
}
sort.Strings(keys)
for _, name := range keys {
condition := rs.Conditions[name]
fmt.Fprintf(w, "- %s: ", name)
// sort these keys too for consistency
subkeys := make([]string, 0, len(condition))
for subkey := range condition {
subkeys = append(subkeys, subkey)
}
sort.Strings(subkeys)
for _, n := range subkeys {
fmt.Fprintf(w, "[%s: %v] ", n, condition[n])
}
fmt.Fprint(w, "\n")
}
}
fmt.Fprintf(w, "\n%s\n", cs.Bold("Rules"))
if len(rs.Rules) == 0 {
fmt.Fprintf(w, "No rules configured\n")
} else {
fmt.Fprint(w, shared.ParseRulesForDisplay(rs.Rules))
}
return nil
}
func selectRulesetID(rsList *shared.RulesetList, p prompter.Prompter, cs *iostreams.ColorScheme) (*shared.RulesetGraphQL, error) {
rulesets := make([]string, len(rsList.Rulesets))
for i, rs := range rsList.Rulesets {
s := fmt.Sprintf(
"%s: %s | %s | contains %s | configured in %s",
cs.Cyan(strconv.Itoa(rs.DatabaseId)),
rs.Name,
strings.ToLower(rs.Enforcement),
text.Pluralize(rs.Rules.TotalCount, "rule"),
shared.RulesetSource(rs),
)
rulesets[i] = s
}
r, err := p.Select("Which ruleset would you like to view?", rulesets[0], rulesets)
if err != nil {
return nil, err
}
return &rsList.Rulesets[r], nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/view/http.go | pkg/cmd/ruleset/view/http.go | package view
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/ruleset/shared"
)
func viewRepoRuleset(httpClient *http.Client, repo ghrepo.Interface, databaseId string) (*shared.RulesetREST, error) {
path := fmt.Sprintf("repos/%s/%s/rulesets/%s", repo.RepoOwner(), repo.RepoName(), databaseId)
return viewRuleset(httpClient, repo.RepoHost(), path)
}
func viewOrgRuleset(httpClient *http.Client, orgLogin string, databaseId string, host string) (*shared.RulesetREST, error) {
path := fmt.Sprintf("orgs/%s/rulesets/%s", orgLogin, databaseId)
return viewRuleset(httpClient, host, path)
}
func viewRuleset(httpClient *http.Client, hostname string, path string) (*shared.RulesetREST, error) {
apiClient := api.NewClientFromHTTP(httpClient)
result := shared.RulesetREST{}
err := apiClient.REST(hostname, "GET", path, nil, &result)
if err != nil {
return nil, err
}
return &result, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.