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 |
|---|---|---|---|---|---|---|---|---|
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/ra/proto/ra.pb.go | third-party/github.com/letsencrypt/boulder/ra/proto/ra.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.5
// protoc v3.20.1
// source: ra.proto
package proto
import (
proto1 "github.com/letsencrypt/boulder/ca/proto"
proto "github.com/letsencrypt/boulder/core/proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
durationpb "google.golang.org/protobuf/types/known/durationpb"
emptypb "google.golang.org/protobuf/types/known/emptypb"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
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)
)
type SCTRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
PrecertDER []byte `protobuf:"bytes,1,opt,name=precertDER,proto3" json:"precertDER,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SCTRequest) Reset() {
*x = SCTRequest{}
mi := &file_ra_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SCTRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SCTRequest) ProtoMessage() {}
func (x *SCTRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SCTRequest.ProtoReflect.Descriptor instead.
func (*SCTRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{0}
}
func (x *SCTRequest) GetPrecertDER() []byte {
if x != nil {
return x.PrecertDER
}
return nil
}
type SCTResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SctDER [][]byte `protobuf:"bytes,1,rep,name=sctDER,proto3" json:"sctDER,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SCTResponse) Reset() {
*x = SCTResponse{}
mi := &file_ra_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SCTResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SCTResponse) ProtoMessage() {}
func (x *SCTResponse) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SCTResponse.ProtoReflect.Descriptor instead.
func (*SCTResponse) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{1}
}
func (x *SCTResponse) GetSctDER() [][]byte {
if x != nil {
return x.SctDER
}
return nil
}
type GenerateOCSPRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Serial string `protobuf:"bytes,1,opt,name=serial,proto3" json:"serial,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GenerateOCSPRequest) Reset() {
*x = GenerateOCSPRequest{}
mi := &file_ra_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GenerateOCSPRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GenerateOCSPRequest) ProtoMessage() {}
func (x *GenerateOCSPRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GenerateOCSPRequest.ProtoReflect.Descriptor instead.
func (*GenerateOCSPRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{2}
}
func (x *GenerateOCSPRequest) GetSerial() string {
if x != nil {
return x.Serial
}
return ""
}
type UpdateRegistrationContactRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
RegistrationID int64 `protobuf:"varint,1,opt,name=registrationID,proto3" json:"registrationID,omitempty"`
Contacts []string `protobuf:"bytes,2,rep,name=contacts,proto3" json:"contacts,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateRegistrationContactRequest) Reset() {
*x = UpdateRegistrationContactRequest{}
mi := &file_ra_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UpdateRegistrationContactRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateRegistrationContactRequest) ProtoMessage() {}
func (x *UpdateRegistrationContactRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UpdateRegistrationContactRequest.ProtoReflect.Descriptor instead.
func (*UpdateRegistrationContactRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{3}
}
func (x *UpdateRegistrationContactRequest) GetRegistrationID() int64 {
if x != nil {
return x.RegistrationID
}
return 0
}
func (x *UpdateRegistrationContactRequest) GetContacts() []string {
if x != nil {
return x.Contacts
}
return nil
}
type UpdateRegistrationKeyRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
RegistrationID int64 `protobuf:"varint,1,opt,name=registrationID,proto3" json:"registrationID,omitempty"`
Jwk []byte `protobuf:"bytes,2,opt,name=jwk,proto3" json:"jwk,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateRegistrationKeyRequest) Reset() {
*x = UpdateRegistrationKeyRequest{}
mi := &file_ra_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UpdateRegistrationKeyRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateRegistrationKeyRequest) ProtoMessage() {}
func (x *UpdateRegistrationKeyRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UpdateRegistrationKeyRequest.ProtoReflect.Descriptor instead.
func (*UpdateRegistrationKeyRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{4}
}
func (x *UpdateRegistrationKeyRequest) GetRegistrationID() int64 {
if x != nil {
return x.RegistrationID
}
return 0
}
func (x *UpdateRegistrationKeyRequest) GetJwk() []byte {
if x != nil {
return x.Jwk
}
return nil
}
type DeactivateRegistrationRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
RegistrationID int64 `protobuf:"varint,1,opt,name=registrationID,proto3" json:"registrationID,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DeactivateRegistrationRequest) Reset() {
*x = DeactivateRegistrationRequest{}
mi := &file_ra_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *DeactivateRegistrationRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DeactivateRegistrationRequest) ProtoMessage() {}
func (x *DeactivateRegistrationRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DeactivateRegistrationRequest.ProtoReflect.Descriptor instead.
func (*DeactivateRegistrationRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{5}
}
func (x *DeactivateRegistrationRequest) GetRegistrationID() int64 {
if x != nil {
return x.RegistrationID
}
return 0
}
type UpdateAuthorizationRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Authz *proto.Authorization `protobuf:"bytes,1,opt,name=authz,proto3" json:"authz,omitempty"`
ChallengeIndex int64 `protobuf:"varint,2,opt,name=challengeIndex,proto3" json:"challengeIndex,omitempty"`
Response *proto.Challenge `protobuf:"bytes,3,opt,name=response,proto3" json:"response,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateAuthorizationRequest) Reset() {
*x = UpdateAuthorizationRequest{}
mi := &file_ra_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UpdateAuthorizationRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateAuthorizationRequest) ProtoMessage() {}
func (x *UpdateAuthorizationRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UpdateAuthorizationRequest.ProtoReflect.Descriptor instead.
func (*UpdateAuthorizationRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{6}
}
func (x *UpdateAuthorizationRequest) GetAuthz() *proto.Authorization {
if x != nil {
return x.Authz
}
return nil
}
func (x *UpdateAuthorizationRequest) GetChallengeIndex() int64 {
if x != nil {
return x.ChallengeIndex
}
return 0
}
func (x *UpdateAuthorizationRequest) GetResponse() *proto.Challenge {
if x != nil {
return x.Response
}
return nil
}
type PerformValidationRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Authz *proto.Authorization `protobuf:"bytes,1,opt,name=authz,proto3" json:"authz,omitempty"`
ChallengeIndex int64 `protobuf:"varint,2,opt,name=challengeIndex,proto3" json:"challengeIndex,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *PerformValidationRequest) Reset() {
*x = PerformValidationRequest{}
mi := &file_ra_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *PerformValidationRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*PerformValidationRequest) ProtoMessage() {}
func (x *PerformValidationRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use PerformValidationRequest.ProtoReflect.Descriptor instead.
func (*PerformValidationRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{7}
}
func (x *PerformValidationRequest) GetAuthz() *proto.Authorization {
if x != nil {
return x.Authz
}
return nil
}
func (x *PerformValidationRequest) GetChallengeIndex() int64 {
if x != nil {
return x.ChallengeIndex
}
return 0
}
type RevokeCertByApplicantRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Cert []byte `protobuf:"bytes,1,opt,name=cert,proto3" json:"cert,omitempty"`
Code int64 `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"`
RegID int64 `protobuf:"varint,3,opt,name=regID,proto3" json:"regID,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RevokeCertByApplicantRequest) Reset() {
*x = RevokeCertByApplicantRequest{}
mi := &file_ra_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RevokeCertByApplicantRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RevokeCertByApplicantRequest) ProtoMessage() {}
func (x *RevokeCertByApplicantRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RevokeCertByApplicantRequest.ProtoReflect.Descriptor instead.
func (*RevokeCertByApplicantRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{8}
}
func (x *RevokeCertByApplicantRequest) GetCert() []byte {
if x != nil {
return x.Cert
}
return nil
}
func (x *RevokeCertByApplicantRequest) GetCode() int64 {
if x != nil {
return x.Code
}
return 0
}
func (x *RevokeCertByApplicantRequest) GetRegID() int64 {
if x != nil {
return x.RegID
}
return 0
}
type RevokeCertByKeyRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Cert []byte `protobuf:"bytes,1,opt,name=cert,proto3" json:"cert,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RevokeCertByKeyRequest) Reset() {
*x = RevokeCertByKeyRequest{}
mi := &file_ra_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RevokeCertByKeyRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RevokeCertByKeyRequest) ProtoMessage() {}
func (x *RevokeCertByKeyRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RevokeCertByKeyRequest.ProtoReflect.Descriptor instead.
func (*RevokeCertByKeyRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{9}
}
func (x *RevokeCertByKeyRequest) GetCert() []byte {
if x != nil {
return x.Cert
}
return nil
}
type AdministrativelyRevokeCertificateRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Deprecated: this field is ignored.
Cert []byte `protobuf:"bytes,1,opt,name=cert,proto3" json:"cert,omitempty"`
// The `serial` field is required.
Serial string `protobuf:"bytes,4,opt,name=serial,proto3" json:"serial,omitempty"`
Code int64 `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"`
AdminName string `protobuf:"bytes,3,opt,name=adminName,proto3" json:"adminName,omitempty"`
SkipBlockKey bool `protobuf:"varint,5,opt,name=skipBlockKey,proto3" json:"skipBlockKey,omitempty"`
// If the malformed flag is set, the RA will not attempt to parse the
// certificate in question. In this case, the keyCompromise reason cannot be
// specified, because the key cannot be blocked.
Malformed bool `protobuf:"varint,6,opt,name=malformed,proto3" json:"malformed,omitempty"`
// The CRL shard to store the revocation in.
//
// This is used when revoking malformed certificates, to allow human judgement
// in setting the CRL shard instead of automatically determining it by parsing
// the certificate.
//
// Passing a nonzero crlShard with malformed=false returns error.
CrlShard int64 `protobuf:"varint,7,opt,name=crlShard,proto3" json:"crlShard,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AdministrativelyRevokeCertificateRequest) Reset() {
*x = AdministrativelyRevokeCertificateRequest{}
mi := &file_ra_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AdministrativelyRevokeCertificateRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AdministrativelyRevokeCertificateRequest) ProtoMessage() {}
func (x *AdministrativelyRevokeCertificateRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AdministrativelyRevokeCertificateRequest.ProtoReflect.Descriptor instead.
func (*AdministrativelyRevokeCertificateRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{10}
}
func (x *AdministrativelyRevokeCertificateRequest) GetCert() []byte {
if x != nil {
return x.Cert
}
return nil
}
func (x *AdministrativelyRevokeCertificateRequest) GetSerial() string {
if x != nil {
return x.Serial
}
return ""
}
func (x *AdministrativelyRevokeCertificateRequest) GetCode() int64 {
if x != nil {
return x.Code
}
return 0
}
func (x *AdministrativelyRevokeCertificateRequest) GetAdminName() string {
if x != nil {
return x.AdminName
}
return ""
}
func (x *AdministrativelyRevokeCertificateRequest) GetSkipBlockKey() bool {
if x != nil {
return x.SkipBlockKey
}
return false
}
func (x *AdministrativelyRevokeCertificateRequest) GetMalformed() bool {
if x != nil {
return x.Malformed
}
return false
}
func (x *AdministrativelyRevokeCertificateRequest) GetCrlShard() int64 {
if x != nil {
return x.CrlShard
}
return 0
}
type NewOrderRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Next unused field number: 9
RegistrationID int64 `protobuf:"varint,1,opt,name=registrationID,proto3" json:"registrationID,omitempty"`
Identifiers []*proto.Identifier `protobuf:"bytes,8,rep,name=identifiers,proto3" json:"identifiers,omitempty"`
CertificateProfileName string `protobuf:"bytes,5,opt,name=certificateProfileName,proto3" json:"certificateProfileName,omitempty"`
// Replaces is the ARI certificate Id that this order replaces.
Replaces string `protobuf:"bytes,7,opt,name=replaces,proto3" json:"replaces,omitempty"`
// ReplacesSerial is the serial number of the certificate that this order replaces.
ReplacesSerial string `protobuf:"bytes,3,opt,name=replacesSerial,proto3" json:"replacesSerial,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *NewOrderRequest) Reset() {
*x = NewOrderRequest{}
mi := &file_ra_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *NewOrderRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*NewOrderRequest) ProtoMessage() {}
func (x *NewOrderRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use NewOrderRequest.ProtoReflect.Descriptor instead.
func (*NewOrderRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{11}
}
func (x *NewOrderRequest) GetRegistrationID() int64 {
if x != nil {
return x.RegistrationID
}
return 0
}
func (x *NewOrderRequest) GetIdentifiers() []*proto.Identifier {
if x != nil {
return x.Identifiers
}
return nil
}
func (x *NewOrderRequest) GetCertificateProfileName() string {
if x != nil {
return x.CertificateProfileName
}
return ""
}
func (x *NewOrderRequest) GetReplaces() string {
if x != nil {
return x.Replaces
}
return ""
}
func (x *NewOrderRequest) GetReplacesSerial() string {
if x != nil {
return x.ReplacesSerial
}
return ""
}
type GetAuthorizationRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetAuthorizationRequest) Reset() {
*x = GetAuthorizationRequest{}
mi := &file_ra_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetAuthorizationRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetAuthorizationRequest) ProtoMessage() {}
func (x *GetAuthorizationRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetAuthorizationRequest.ProtoReflect.Descriptor instead.
func (*GetAuthorizationRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{12}
}
func (x *GetAuthorizationRequest) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
type FinalizeOrderRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Order *proto.Order `protobuf:"bytes,1,opt,name=order,proto3" json:"order,omitempty"`
Csr []byte `protobuf:"bytes,2,opt,name=csr,proto3" json:"csr,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FinalizeOrderRequest) Reset() {
*x = FinalizeOrderRequest{}
mi := &file_ra_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FinalizeOrderRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FinalizeOrderRequest) ProtoMessage() {}
func (x *FinalizeOrderRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FinalizeOrderRequest.ProtoReflect.Descriptor instead.
func (*FinalizeOrderRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{13}
}
func (x *FinalizeOrderRequest) GetOrder() *proto.Order {
if x != nil {
return x.Order
}
return nil
}
func (x *FinalizeOrderRequest) GetCsr() []byte {
if x != nil {
return x.Csr
}
return nil
}
type UnpauseAccountRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The registrationID to be unpaused so issuance can be resumed.
RegistrationID int64 `protobuf:"varint,1,opt,name=registrationID,proto3" json:"registrationID,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UnpauseAccountRequest) Reset() {
*x = UnpauseAccountRequest{}
mi := &file_ra_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UnpauseAccountRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UnpauseAccountRequest) ProtoMessage() {}
func (x *UnpauseAccountRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UnpauseAccountRequest.ProtoReflect.Descriptor instead.
func (*UnpauseAccountRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{14}
}
func (x *UnpauseAccountRequest) GetRegistrationID() int64 {
if x != nil {
return x.RegistrationID
}
return 0
}
type UnpauseAccountResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Count is the number of identifiers which were unpaused for the input regid.
Count int64 `protobuf:"varint,1,opt,name=count,proto3" json:"count,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UnpauseAccountResponse) Reset() {
*x = UnpauseAccountResponse{}
mi := &file_ra_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UnpauseAccountResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UnpauseAccountResponse) ProtoMessage() {}
func (x *UnpauseAccountResponse) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UnpauseAccountResponse.ProtoReflect.Descriptor instead.
func (*UnpauseAccountResponse) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{15}
}
func (x *UnpauseAccountResponse) GetCount() int64 {
if x != nil {
return x.Count
}
return 0
}
type AddRateLimitOverrideRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
LimitEnum int64 `protobuf:"varint,1,opt,name=limitEnum,proto3" json:"limitEnum,omitempty"`
BucketKey string `protobuf:"bytes,2,opt,name=bucketKey,proto3" json:"bucketKey,omitempty"`
Comment string `protobuf:"bytes,3,opt,name=comment,proto3" json:"comment,omitempty"`
Period *durationpb.Duration `protobuf:"bytes,4,opt,name=period,proto3" json:"period,omitempty"`
Count int64 `protobuf:"varint,5,opt,name=count,proto3" json:"count,omitempty"`
Burst int64 `protobuf:"varint,6,opt,name=burst,proto3" json:"burst,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddRateLimitOverrideRequest) Reset() {
*x = AddRateLimitOverrideRequest{}
mi := &file_ra_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddRateLimitOverrideRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddRateLimitOverrideRequest) ProtoMessage() {}
func (x *AddRateLimitOverrideRequest) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddRateLimitOverrideRequest.ProtoReflect.Descriptor instead.
func (*AddRateLimitOverrideRequest) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{16}
}
func (x *AddRateLimitOverrideRequest) GetLimitEnum() int64 {
if x != nil {
return x.LimitEnum
}
return 0
}
func (x *AddRateLimitOverrideRequest) GetBucketKey() string {
if x != nil {
return x.BucketKey
}
return ""
}
func (x *AddRateLimitOverrideRequest) GetComment() string {
if x != nil {
return x.Comment
}
return ""
}
func (x *AddRateLimitOverrideRequest) GetPeriod() *durationpb.Duration {
if x != nil {
return x.Period
}
return nil
}
func (x *AddRateLimitOverrideRequest) GetCount() int64 {
if x != nil {
return x.Count
}
return 0
}
func (x *AddRateLimitOverrideRequest) GetBurst() int64 {
if x != nil {
return x.Burst
}
return 0
}
type AddRateLimitOverrideResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Inserted bool `protobuf:"varint,1,opt,name=inserted,proto3" json:"inserted,omitempty"`
Enabled bool `protobuf:"varint,2,opt,name=enabled,proto3" json:"enabled,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddRateLimitOverrideResponse) Reset() {
*x = AddRateLimitOverrideResponse{}
mi := &file_ra_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddRateLimitOverrideResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddRateLimitOverrideResponse) ProtoMessage() {}
func (x *AddRateLimitOverrideResponse) ProtoReflect() protoreflect.Message {
mi := &file_ra_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddRateLimitOverrideResponse.ProtoReflect.Descriptor instead.
func (*AddRateLimitOverrideResponse) Descriptor() ([]byte, []int) {
return file_ra_proto_rawDescGZIP(), []int{17}
}
func (x *AddRateLimitOverrideResponse) GetInserted() bool {
if x != nil {
return x.Inserted
}
return false
}
func (x *AddRateLimitOverrideResponse) GetEnabled() bool {
if x != nil {
return x.Enabled
}
return false
}
var File_ra_proto protoreflect.FileDescriptor
var file_ra_proto_rawDesc = string([]byte{
0x0a, 0x08, 0x72, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02, 0x72, 0x61, 0x1a, 0x15,
0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x11, 0x63, 0x61, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f,
0x63, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2c, 0x0a, 0x0a, 0x53, 0x43, 0x54, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x72, 0x65, 0x63, 0x65, 0x72, 0x74, 0x44, 0x45,
0x52, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x70, 0x72, 0x65, 0x63, 0x65, 0x72, 0x74,
0x44, 0x45, 0x52, 0x22, 0x25, 0x0a, 0x0b, 0x53, 0x43, 0x54, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x63, 0x74, 0x44, 0x45, 0x52, 0x18, 0x01, 0x20, 0x03,
0x28, 0x0c, 0x52, 0x06, 0x73, 0x63, 0x74, 0x44, 0x45, 0x52, 0x22, 0x2d, 0x0a, 0x13, 0x47, 0x65,
0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x4f, 0x43, 0x53, 0x50, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28,
0x09, 0x52, 0x06, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x22, 0x66, 0x0a, 0x20, 0x55, 0x70, 0x64,
0x61, 0x74, 0x65, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43,
0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x26, 0x0a,
0x0e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x18,
0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x49, 0x44, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74,
0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74,
0x73, 0x22, 0x58, 0x0a, 0x1c, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x67, 0x69, 0x73,
0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x26, 0x0a, 0x0e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x72, 0x65, 0x67, 0x69, 0x73,
0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x12, 0x10, 0x0a, 0x03, 0x6a, 0x77, 0x6b,
0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6a, 0x77, 0x6b, 0x22, 0x47, 0x0a, 0x1d, 0x44,
0x65, 0x61, 0x63, 0x74, 0x69, 0x76, 0x61, 0x74, 0x65, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x26, 0x0a, 0x0e,
0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x18, 0x01,
0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x49, 0x44, 0x22, 0x9c, 0x01, 0x0a, 0x1a, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41,
0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x12, 0x29, 0x0a, 0x05, 0x61, 0x75, 0x74, 0x68, 0x7a, 0x18, 0x01, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x13, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x05, 0x61, 0x75, 0x74, 0x68, 0x7a, 0x12, 0x26,
0x0a, 0x0e, 0x63, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67, 0x65, 0x49, 0x6e, 0x64, 0x65, 0x78,
0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x63, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67,
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/policy/pa_test.go | third-party/github.com/letsencrypt/boulder/policy/pa_test.go | package policy
import (
"fmt"
"net/netip"
"os"
"strings"
"testing"
"gopkg.in/yaml.v3"
"github.com/letsencrypt/boulder/core"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/features"
"github.com/letsencrypt/boulder/identifier"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/test"
)
func paImpl(t *testing.T) *AuthorityImpl {
enabledChallenges := map[core.AcmeChallenge]bool{
core.ChallengeTypeHTTP01: true,
core.ChallengeTypeDNS01: true,
core.ChallengeTypeTLSALPN01: true,
}
enabledIdentifiers := map[identifier.IdentifierType]bool{
identifier.TypeDNS: true,
identifier.TypeIP: true,
}
pa, err := New(enabledIdentifiers, enabledChallenges, blog.NewMock())
if err != nil {
t.Fatalf("Couldn't create policy implementation: %s", err)
}
return pa
}
func TestWellFormedIdentifiers(t *testing.T) {
testCases := []struct {
ident identifier.ACMEIdentifier
err error
}{
// Invalid identifier types
{identifier.ACMEIdentifier{}, errUnsupportedIdent}, // Empty identifier type
{identifier.ACMEIdentifier{Type: "fnord", Value: "uh-oh, Spaghetti-Os[tm]"}, errUnsupportedIdent},
// Empty identifier values
{identifier.NewDNS(``), errEmptyIdentifier}, // Empty DNS identifier
{identifier.ACMEIdentifier{Type: "ip"}, errEmptyIdentifier}, // Empty IP identifier
// DNS follies
{identifier.NewDNS(`zomb!.com`), errInvalidDNSCharacter}, // ASCII character out of range
{identifier.NewDNS(`emailaddress@myseriously.present.com`), errInvalidDNSCharacter},
{identifier.NewDNS(`user:pass@myseriously.present.com`), errInvalidDNSCharacter},
{identifier.NewDNS(`zömbo.com`), errInvalidDNSCharacter}, // non-ASCII character
{identifier.NewDNS(`127.0.0.1`), errIPAddressInDNS}, // IPv4 address
{identifier.NewDNS(`fe80::1:1`), errInvalidDNSCharacter}, // IPv6 address
{identifier.NewDNS(`[2001:db8:85a3:8d3:1319:8a2e:370:7348]`), errInvalidDNSCharacter}, // unexpected IPv6 variants
{identifier.NewDNS(`[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443`), errInvalidDNSCharacter},
{identifier.NewDNS(`2001:db8::/32`), errInvalidDNSCharacter},
{identifier.NewDNS(`a.b.c.d.e.f.g.h.i.j.k`), errTooManyLabels}, // Too many labels (>10)
{identifier.NewDNS(`www.0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef012345.com`), errNameTooLong}, // Too long (254 characters)
{identifier.NewDNS(`www.ef0123456789abcdef013456789abcdef012345.789abcdef012345679abcdef0123456789abcdef01234.6789abcdef0123456789abcdef0.23456789abcdef0123456789a.cdef0123456789abcdef0123456789ab.def0123456789abcdef0123456789.bcdef0123456789abcdef012345.com`), nil}, // OK, not too long (240 characters)
{identifier.NewDNS(`www.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz.com`), errLabelTooLong}, // Label too long (>63 characters)
{identifier.NewDNS(`www.-ombo.com`), errInvalidDNSCharacter}, // Label starts with '-'
{identifier.NewDNS(`www.zomb-.com`), errInvalidDNSCharacter}, // Label ends with '-'
{identifier.NewDNS(`xn--.net`), errInvalidDNSCharacter}, // Label ends with '-'
{identifier.NewDNS(`-0b.net`), errInvalidDNSCharacter}, // First label begins with '-'
{identifier.NewDNS(`-0.net`), errInvalidDNSCharacter}, // First label begins with '-'
{identifier.NewDNS(`-.net`), errInvalidDNSCharacter}, // First label is only '-'
{identifier.NewDNS(`---.net`), errInvalidDNSCharacter}, // First label is only hyphens
{identifier.NewDNS(`0`), errTooFewLabels},
{identifier.NewDNS(`1`), errTooFewLabels},
{identifier.NewDNS(`*`), errMalformedWildcard},
{identifier.NewDNS(`**`), errTooManyWildcards},
{identifier.NewDNS(`*.*`), errTooManyWildcards},
{identifier.NewDNS(`zombo*com`), errMalformedWildcard},
{identifier.NewDNS(`*.com`), errICANNTLDWildcard},
{identifier.NewDNS(`..a`), errLabelTooShort},
{identifier.NewDNS(`a..a`), errLabelTooShort},
{identifier.NewDNS(`.a..a`), errLabelTooShort},
{identifier.NewDNS(`..foo.com`), errLabelTooShort},
{identifier.NewDNS(`.`), errNameEndsInDot},
{identifier.NewDNS(`..`), errNameEndsInDot},
{identifier.NewDNS(`a..`), errNameEndsInDot},
{identifier.NewDNS(`.....`), errNameEndsInDot},
{identifier.NewDNS(`.a.`), errNameEndsInDot},
{identifier.NewDNS(`www.zombo.com.`), errNameEndsInDot},
{identifier.NewDNS(`www.zombo_com.com`), errInvalidDNSCharacter},
{identifier.NewDNS(`\uFEFF`), errInvalidDNSCharacter}, // Byte order mark
{identifier.NewDNS(`\uFEFFwww.zombo.com`), errInvalidDNSCharacter},
{identifier.NewDNS(`www.zom\u202Ebo.com`), errInvalidDNSCharacter}, // Right-to-Left Override
{identifier.NewDNS(`\u202Ewww.zombo.com`), errInvalidDNSCharacter},
{identifier.NewDNS(`www.zom\u200Fbo.com`), errInvalidDNSCharacter}, // Right-to-Left Mark
{identifier.NewDNS(`\u200Fwww.zombo.com`), errInvalidDNSCharacter},
// Underscores are technically disallowed in DNS. Some DNS
// implementations accept them but we will be conservative.
{identifier.NewDNS(`www.zom_bo.com`), errInvalidDNSCharacter},
{identifier.NewDNS(`zombocom`), errTooFewLabels},
{identifier.NewDNS(`localhost`), errTooFewLabels},
{identifier.NewDNS(`mail`), errTooFewLabels},
// disallow capitalized letters for #927
{identifier.NewDNS(`CapitalizedLetters.com`), errInvalidDNSCharacter},
{identifier.NewDNS(`example.acting`), errNonPublic},
{identifier.NewDNS(`example.internal`), errNonPublic},
// All-numeric final label not okay.
{identifier.NewDNS(`www.zombo.163`), errNonPublic},
{identifier.NewDNS(`xn--109-3veba6djs1bfxlfmx6c9g.xn--f1awi.xn--p1ai`), errMalformedIDN}, // Not in Unicode NFC
{identifier.NewDNS(`bq--abwhky3f6fxq.jakacomo.com`), errInvalidRLDH},
// Three hyphens starting at third second char of first label.
{identifier.NewDNS(`bq---abwhky3f6fxq.jakacomo.com`), errInvalidRLDH},
// Three hyphens starting at second char of first label.
{identifier.NewDNS(`h---test.hk2yz.org`), errInvalidRLDH},
{identifier.NewDNS(`co.uk`), errICANNTLD},
{identifier.NewDNS(`foo.bd`), errICANNTLD},
// IP oopsies
{identifier.ACMEIdentifier{Type: "ip", Value: `zombo.com`}, errIPInvalid}, // That's DNS!
// Unexpected IPv4 variants
{identifier.ACMEIdentifier{Type: "ip", Value: `192.168.1.1.1`}, errIPInvalid}, // extra octet
{identifier.ACMEIdentifier{Type: "ip", Value: `192.168.1.256`}, errIPInvalid}, // octet out of range
{identifier.ACMEIdentifier{Type: "ip", Value: `192.168.1.a1`}, errIPInvalid}, // character out of range
{identifier.ACMEIdentifier{Type: "ip", Value: `192.168.1.0/24`}, errIPInvalid}, // with CIDR
{identifier.ACMEIdentifier{Type: "ip", Value: `192.168.1.1:443`}, errIPInvalid}, // with port
{identifier.ACMEIdentifier{Type: "ip", Value: `0xc0a80101`}, errIPInvalid}, // as hex
{identifier.ACMEIdentifier{Type: "ip", Value: `1.1.168.192.in-addr.arpa`}, errIPInvalid}, // reverse DNS
// Unexpected IPv6 variants
{identifier.ACMEIdentifier{Type: "ip", Value: `3fff:aaa:a:c0ff:ee:a:bad:deed:ffff`}, errIPInvalid}, // extra octet
{identifier.ACMEIdentifier{Type: "ip", Value: `3fff:aaa:a:c0ff:ee:a:bad:mead`}, errIPInvalid}, // character out of range
{identifier.ACMEIdentifier{Type: "ip", Value: `2001:db8::/32`}, errIPInvalid}, // with CIDR
{identifier.ACMEIdentifier{Type: "ip", Value: `[3fff:aaa:a:c0ff:ee:a:bad:deed]`}, errIPInvalid}, // in brackets
{identifier.ACMEIdentifier{Type: "ip", Value: `[3fff:aaa:a:c0ff:ee:a:bad:deed]:443`}, errIPInvalid}, // in brackets, with port
{identifier.ACMEIdentifier{Type: "ip", Value: `0x3fff0aaa000ac0ff00ee000a0baddeed`}, errIPInvalid}, // as hex
{identifier.ACMEIdentifier{Type: "ip", Value: `d.e.e.d.d.a.b.0.a.0.0.0.e.e.0.0.f.f.0.c.a.0.0.0.a.a.a.0.f.f.f.3.ip6.arpa`}, errIPInvalid}, // reverse DNS
{identifier.ACMEIdentifier{Type: "ip", Value: `3fff:0aaa:a:c0ff:ee:a:bad:deed`}, errIPInvalid}, // leading 0 in 2nd octet (RFC 5952, Sec. 4.1)
{identifier.ACMEIdentifier{Type: "ip", Value: `3fff:aaa:0:0:0:a:bad:deed`}, errIPInvalid}, // lone 0s in 3rd-5th octets, :: not used (RFC 5952, Sec. 4.2.1)
{identifier.ACMEIdentifier{Type: "ip", Value: `3fff:aaa::c0ff:ee:a:bad:deed`}, errIPInvalid}, // :: used for just one empty octet (RFC 5952, Sec. 4.2.2)
{identifier.ACMEIdentifier{Type: "ip", Value: `3fff:aaa::ee:0:0:0`}, errIPInvalid}, // :: used for the shorter of two possible collapses (RFC 5952, Sec. 4.2.3)
{identifier.ACMEIdentifier{Type: "ip", Value: `fe80:0:0:0:a::`}, errIPInvalid}, // :: used for the last of two possible equal-length collapses (RFC 5952, Sec. 4.2.3)
{identifier.ACMEIdentifier{Type: "ip", Value: `3fff:aaa:a:C0FF:EE:a:bad:deed`}, errIPInvalid}, // alpha characters capitalized (RFC 5952, Sec. 4.3)
{identifier.ACMEIdentifier{Type: "ip", Value: `::ffff:192.168.1.1`}, berrors.MalformedError("IP address is in a reserved address block")}, // IPv6-encapsulated IPv4
// IANA special-purpose address blocks
{identifier.NewIP(netip.MustParseAddr("192.0.2.129")), berrors.MalformedError("IP address is in a reserved address block")}, // Documentation (TEST-NET-1)
{identifier.NewIP(netip.MustParseAddr("2001:db8:eee:eeee:eeee:eeee:d01:f1")), berrors.MalformedError("IP address is in a reserved address block")}, // Documentation
}
// Test syntax errors
for _, tc := range testCases {
err := WellFormedIdentifiers(identifier.ACMEIdentifiers{tc.ident})
if tc.err == nil {
test.AssertNil(t, err, fmt.Sprintf("Unexpected error for %q identifier %q, got %s", tc.ident.Type, tc.ident.Value, err))
} else {
test.AssertError(t, err, fmt.Sprintf("Expected error for %q identifier %q, but got none", tc.ident.Type, tc.ident.Value))
var berr *berrors.BoulderError
test.AssertErrorWraps(t, err, &berr)
test.AssertContains(t, berr.Error(), tc.err.Error())
}
}
}
func TestWillingToIssue(t *testing.T) {
shouldBeBlocked := identifier.ACMEIdentifiers{
identifier.NewDNS(`highvalue.website1.org`),
identifier.NewDNS(`website2.co.uk`),
identifier.NewDNS(`www.website3.com`),
identifier.NewDNS(`lots.of.labels.website4.com`),
identifier.NewDNS(`banned.in.dc.com`),
identifier.NewDNS(`bad.brains.banned.in.dc.com`),
}
blocklistContents := []string{
`website2.com`,
`website2.org`,
`website2.co.uk`,
`website3.com`,
`website4.com`,
}
exactBlocklistContents := []string{
`www.website1.org`,
`highvalue.website1.org`,
`dl.website1.org`,
}
adminBlockedContents := []string{
`banned.in.dc.com`,
}
shouldBeAccepted := identifier.ACMEIdentifiers{
identifier.NewDNS(`lowvalue.website1.org`),
identifier.NewDNS(`website4.sucks`),
identifier.NewDNS(`www.unrelated.com`),
identifier.NewDNS(`unrelated.com`),
identifier.NewDNS(`www.8675309.com`),
identifier.NewDNS(`8675309.com`),
identifier.NewDNS(`web5ite2.com`),
identifier.NewDNS(`www.web-site2.com`),
identifier.NewIP(netip.MustParseAddr(`9.9.9.9`)),
identifier.NewIP(netip.MustParseAddr(`2620:fe::fe`)),
}
policy := blockedNamesPolicy{
HighRiskBlockedNames: blocklistContents,
ExactBlockedNames: exactBlocklistContents,
AdminBlockedNames: adminBlockedContents,
}
yamlPolicyBytes, err := yaml.Marshal(policy)
test.AssertNotError(t, err, "Couldn't YAML serialize blocklist")
yamlPolicyFile, _ := os.CreateTemp("", "test-blocklist.*.yaml")
defer os.Remove(yamlPolicyFile.Name())
err = os.WriteFile(yamlPolicyFile.Name(), yamlPolicyBytes, 0640)
test.AssertNotError(t, err, "Couldn't write YAML blocklist")
pa := paImpl(t)
err = pa.LoadHostnamePolicyFile(yamlPolicyFile.Name())
test.AssertNotError(t, err, "Couldn't load rules")
// Invalid encoding
err = pa.WillingToIssue(identifier.ACMEIdentifiers{identifier.NewDNS("www.xn--m.com")})
test.AssertError(t, err, "WillingToIssue didn't fail on a malformed IDN")
// Invalid identifier type
err = pa.WillingToIssue(identifier.ACMEIdentifiers{identifier.ACMEIdentifier{Type: "fnord", Value: "uh-oh, Spaghetti-Os[tm]"}})
test.AssertError(t, err, "WillingToIssue didn't fail on an invalid identifier type")
// Valid encoding
err = pa.WillingToIssue(identifier.ACMEIdentifiers{identifier.NewDNS("www.xn--mnich-kva.com")})
test.AssertNotError(t, err, "WillingToIssue failed on a properly formed IDN")
// IDN TLD
err = pa.WillingToIssue(identifier.ACMEIdentifiers{identifier.NewDNS("xn--example--3bhk5a.xn--p1ai")})
test.AssertNotError(t, err, "WillingToIssue failed on a properly formed domain with IDN TLD")
features.Reset()
// Test expected blocked domains
for _, ident := range shouldBeBlocked {
err := pa.WillingToIssue(identifier.ACMEIdentifiers{ident})
test.AssertError(t, err, "identifier was not correctly forbidden")
var berr *berrors.BoulderError
test.AssertErrorWraps(t, err, &berr)
test.AssertContains(t, berr.Detail, errPolicyForbidden.Error())
}
// Test acceptance of good names
for _, ident := range shouldBeAccepted {
err := pa.WillingToIssue(identifier.ACMEIdentifiers{ident})
test.AssertNotError(t, err, "identifier was incorrectly forbidden")
}
}
func TestWillingToIssue_Wildcards(t *testing.T) {
bannedDomains := []string{
"zombo.gov.us",
}
exactBannedDomains := []string{
"highvalue.letsdecrypt.org",
}
pa := paImpl(t)
bannedBytes, err := yaml.Marshal(blockedNamesPolicy{
HighRiskBlockedNames: bannedDomains,
ExactBlockedNames: exactBannedDomains,
})
test.AssertNotError(t, err, "Couldn't serialize banned list")
f, _ := os.CreateTemp("", "test-wildcard-banlist.*.yaml")
defer os.Remove(f.Name())
err = os.WriteFile(f.Name(), bannedBytes, 0640)
test.AssertNotError(t, err, "Couldn't write serialized banned list to file")
err = pa.LoadHostnamePolicyFile(f.Name())
test.AssertNotError(t, err, "Couldn't load policy contents from file")
testCases := []struct {
Name string
Domain string
ExpectedErr error
}{
{
Name: "Too many wildcards",
Domain: "ok.*.whatever.*.example.com",
ExpectedErr: errTooManyWildcards,
},
{
Name: "Misplaced wildcard",
Domain: "ok.*.whatever.example.com",
ExpectedErr: errMalformedWildcard,
},
{
Name: "Missing ICANN TLD",
Domain: "*.ok.madeup",
ExpectedErr: errNonPublic,
},
{
Name: "Wildcard for ICANN TLD",
Domain: "*.com",
ExpectedErr: errICANNTLDWildcard,
},
{
Name: "Forbidden base domain",
Domain: "*.zombo.gov.us",
ExpectedErr: errPolicyForbidden,
},
// We should not allow getting a wildcard for that would cover an exact
// blocklist domain
{
Name: "Wildcard for ExactBlocklist base domain",
Domain: "*.letsdecrypt.org",
ExpectedErr: errPolicyForbidden,
},
// We should allow a wildcard for a domain that doesn't match the exact
// blocklist domain
{
Name: "Wildcard for non-matching subdomain of ExactBlocklist domain",
Domain: "*.lowvalue.letsdecrypt.org",
ExpectedErr: nil,
},
// We should allow getting a wildcard for an exact blocklist domain since it
// only covers subdomains, not the exact name.
{
Name: "Wildcard for ExactBlocklist domain",
Domain: "*.highvalue.letsdecrypt.org",
ExpectedErr: nil,
},
{
Name: "Valid wildcard domain",
Domain: "*.everything.is.possible.at.zombo.com",
ExpectedErr: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
err := pa.WillingToIssue(identifier.ACMEIdentifiers{identifier.NewDNS(tc.Domain)})
if tc.ExpectedErr == nil {
test.AssertNil(t, err, fmt.Sprintf("Unexpected error for domain %q, got %s", tc.Domain, err))
} else {
test.AssertError(t, err, fmt.Sprintf("Expected error for domain %q, but got none", tc.Domain))
var berr *berrors.BoulderError
test.AssertErrorWraps(t, err, &berr)
test.AssertContains(t, berr.Error(), tc.ExpectedErr.Error())
}
})
}
}
// TestWillingToIssue_SubErrors tests that more than one rejected identifier
// results in an error with suberrors.
func TestWillingToIssue_SubErrors(t *testing.T) {
banned := []string{
"letsdecrypt.org",
"example.com",
}
pa := paImpl(t)
bannedBytes, err := yaml.Marshal(blockedNamesPolicy{
HighRiskBlockedNames: banned,
ExactBlockedNames: banned,
})
test.AssertNotError(t, err, "Couldn't serialize banned list")
f, _ := os.CreateTemp("", "test-wildcard-banlist.*.yaml")
defer os.Remove(f.Name())
err = os.WriteFile(f.Name(), bannedBytes, 0640)
test.AssertNotError(t, err, "Couldn't write serialized banned list to file")
err = pa.LoadHostnamePolicyFile(f.Name())
test.AssertNotError(t, err, "Couldn't load policy contents from file")
// Test multiple malformed domains and one banned domain; only the malformed ones will generate errors
err = pa.WillingToIssue(identifier.ACMEIdentifiers{
identifier.NewDNS("perfectly-fine.com"), // fine
identifier.NewDNS("letsdecrypt_org"), // malformed
identifier.NewDNS("example.comm"), // malformed
identifier.NewDNS("letsdecrypt.org"), // banned
identifier.NewDNS("also-perfectly-fine.com"), // fine
})
test.AssertDeepEquals(t, err,
&berrors.BoulderError{
Type: berrors.RejectedIdentifier,
Detail: "Cannot issue for \"letsdecrypt_org\": Domain name contains an invalid character (and 1 more problems. Refer to sub-problems for more information.)",
SubErrors: []berrors.SubBoulderError{
{
BoulderError: &berrors.BoulderError{
Type: berrors.Malformed,
Detail: "Domain name contains an invalid character",
},
Identifier: identifier.NewDNS("letsdecrypt_org"),
},
{
BoulderError: &berrors.BoulderError{
Type: berrors.Malformed,
Detail: "Domain name does not end with a valid public suffix (TLD)",
},
Identifier: identifier.NewDNS("example.comm"),
},
},
})
// Test multiple banned domains.
err = pa.WillingToIssue(identifier.ACMEIdentifiers{
identifier.NewDNS("perfectly-fine.com"), // fine
identifier.NewDNS("letsdecrypt.org"), // banned
identifier.NewDNS("example.com"), // banned
identifier.NewDNS("also-perfectly-fine.com"), // fine
})
test.AssertError(t, err, "Expected err from WillingToIssueWildcards")
test.AssertDeepEquals(t, err,
&berrors.BoulderError{
Type: berrors.RejectedIdentifier,
Detail: "Cannot issue for \"letsdecrypt.org\": The ACME server refuses to issue a certificate for this domain name, because it is forbidden by policy (and 1 more problems. Refer to sub-problems for more information.)",
SubErrors: []berrors.SubBoulderError{
{
BoulderError: &berrors.BoulderError{
Type: berrors.RejectedIdentifier,
Detail: "The ACME server refuses to issue a certificate for this domain name, because it is forbidden by policy",
},
Identifier: identifier.NewDNS("letsdecrypt.org"),
},
{
BoulderError: &berrors.BoulderError{
Type: berrors.RejectedIdentifier,
Detail: "The ACME server refuses to issue a certificate for this domain name, because it is forbidden by policy",
},
Identifier: identifier.NewDNS("example.com"),
},
},
})
// Test willing to issue with only *one* bad identifier.
err = pa.WillingToIssue(identifier.ACMEIdentifiers{identifier.NewDNS("letsdecrypt.org")})
test.AssertDeepEquals(t, err,
&berrors.BoulderError{
Type: berrors.RejectedIdentifier,
Detail: "Cannot issue for \"letsdecrypt.org\": The ACME server refuses to issue a certificate for this domain name, because it is forbidden by policy",
})
}
func TestChallengeTypesFor(t *testing.T) {
t.Parallel()
pa := paImpl(t)
testCases := []struct {
name string
ident identifier.ACMEIdentifier
wantChalls []core.AcmeChallenge
wantErr string
}{
{
name: "dns",
ident: identifier.NewDNS("example.com"),
wantChalls: []core.AcmeChallenge{
core.ChallengeTypeHTTP01, core.ChallengeTypeDNS01, core.ChallengeTypeTLSALPN01,
},
},
{
name: "dns wildcard",
ident: identifier.NewDNS("*.example.com"),
wantChalls: []core.AcmeChallenge{
core.ChallengeTypeDNS01,
},
},
{
name: "ip",
ident: identifier.NewIP(netip.MustParseAddr("1.2.3.4")),
wantChalls: []core.AcmeChallenge{
core.ChallengeTypeHTTP01, core.ChallengeTypeTLSALPN01,
},
},
{
name: "invalid",
ident: identifier.ACMEIdentifier{Type: "fnord", Value: "uh-oh, Spaghetti-Os[tm]"},
wantErr: "unrecognized identifier type",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
challs, err := pa.ChallengeTypesFor(tc.ident)
if len(tc.wantChalls) != 0 {
test.AssertNotError(t, err, "should have succeeded")
test.AssertDeepEquals(t, challs, tc.wantChalls)
}
if tc.wantErr != "" {
test.AssertError(t, err, "should have errored")
test.AssertContains(t, err.Error(), tc.wantErr)
}
})
}
}
// TestMalformedExactBlocklist tests that loading a YAML policy file with an
// invalid exact blocklist entry will fail as expected.
func TestMalformedExactBlocklist(t *testing.T) {
pa := paImpl(t)
exactBannedDomains := []string{
// Only one label - not valid
"com",
}
bannedDomains := []string{
"placeholder.domain.not.important.for.this.test.com",
}
// Create YAML for the exactBannedDomains
bannedBytes, err := yaml.Marshal(blockedNamesPolicy{
HighRiskBlockedNames: bannedDomains,
ExactBlockedNames: exactBannedDomains,
})
test.AssertNotError(t, err, "Couldn't serialize banned list")
// Create a temp file for the YAML contents
f, _ := os.CreateTemp("", "test-invalid-exactblocklist.*.yaml")
defer os.Remove(f.Name())
// Write the YAML to the temp file
err = os.WriteFile(f.Name(), bannedBytes, 0640)
test.AssertNotError(t, err, "Couldn't write serialized banned list to file")
// Try to use the YAML tempfile as the hostname policy. It should produce an
// error since the exact blocklist contents are malformed.
err = pa.LoadHostnamePolicyFile(f.Name())
test.AssertError(t, err, "Loaded invalid exact blocklist content without error")
test.AssertEquals(t, err.Error(), "Malformed ExactBlockedNames entry, only one label: \"com\"")
}
func TestValidEmailError(t *testing.T) {
err := ValidEmail("(๑•́ ω •̀๑)")
test.AssertEquals(t, err.Error(), "unable to parse email address")
err = ValidEmail("john.smith@gmail.com #replace with real email")
test.AssertEquals(t, err.Error(), "unable to parse email address")
err = ValidEmail("example@example.com")
test.AssertEquals(t, err.Error(), "contact email has forbidden domain \"example.com\"")
err = ValidEmail("example@-foobar.com")
test.AssertEquals(t, err.Error(), "contact email has invalid domain: Domain name contains an invalid character")
}
func TestCheckAuthzChallenges(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
authz core.Authorization
enabled map[core.AcmeChallenge]bool
wantErr string
}{
{
name: "unrecognized identifier",
authz: core.Authorization{
Identifier: identifier.ACMEIdentifier{Type: "oops", Value: "example.com"},
Challenges: []core.Challenge{{Type: core.ChallengeTypeDNS01, Status: core.StatusValid}},
},
wantErr: "unrecognized identifier type",
},
{
name: "no challenges",
authz: core.Authorization{
Identifier: identifier.NewDNS("example.com"),
Challenges: []core.Challenge{},
},
wantErr: "has no challenges",
},
{
name: "no valid challenges",
authz: core.Authorization{
Identifier: identifier.NewDNS("example.com"),
Challenges: []core.Challenge{{Type: core.ChallengeTypeDNS01, Status: core.StatusPending}},
},
wantErr: "not solved by any challenge",
},
{
name: "solved by disabled challenge",
authz: core.Authorization{
Identifier: identifier.NewDNS("example.com"),
Challenges: []core.Challenge{{Type: core.ChallengeTypeDNS01, Status: core.StatusValid}},
},
enabled: map[core.AcmeChallenge]bool{core.ChallengeTypeHTTP01: true},
wantErr: "disabled challenge type",
},
{
name: "solved by wrong kind of challenge",
authz: core.Authorization{
Identifier: identifier.NewDNS("*.example.com"),
Challenges: []core.Challenge{{Type: core.ChallengeTypeHTTP01, Status: core.StatusValid}},
},
wantErr: "inapplicable challenge type",
},
{
name: "valid authz",
authz: core.Authorization{
Identifier: identifier.NewDNS("example.com"),
Challenges: []core.Challenge{{Type: core.ChallengeTypeTLSALPN01, Status: core.StatusValid}},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
pa := paImpl(t)
if tc.enabled != nil {
pa.enabledChallenges = tc.enabled
}
err := pa.CheckAuthzChallenges(&tc.authz)
if tc.wantErr == "" {
test.AssertNotError(t, err, "should have succeeded")
} else {
test.AssertError(t, err, "should have errored")
test.AssertContains(t, err.Error(), tc.wantErr)
}
})
}
}
func TestWillingToIssue_IdentifierType(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
ident identifier.ACMEIdentifier
enabled map[identifier.IdentifierType]bool
wantErr string
}{
{
name: "DNS identifier, none enabled",
ident: identifier.NewDNS("example.com"),
enabled: nil,
wantErr: "The ACME server has disabled this identifier type",
},
{
name: "DNS identifier, DNS enabled",
ident: identifier.NewDNS("example.com"),
enabled: map[identifier.IdentifierType]bool{identifier.TypeDNS: true},
wantErr: "",
},
{
name: "DNS identifier, DNS & IP enabled",
ident: identifier.NewDNS("example.com"),
enabled: map[identifier.IdentifierType]bool{identifier.TypeDNS: true, identifier.TypeIP: true},
wantErr: "",
},
{
name: "DNS identifier, IP enabled",
ident: identifier.NewDNS("example.com"),
enabled: map[identifier.IdentifierType]bool{identifier.TypeIP: true},
wantErr: "The ACME server has disabled this identifier type",
},
{
name: "IP identifier, none enabled",
ident: identifier.NewIP(netip.MustParseAddr("9.9.9.9")),
enabled: nil,
wantErr: "The ACME server has disabled this identifier type",
},
{
name: "IP identifier, DNS enabled",
ident: identifier.NewIP(netip.MustParseAddr("9.9.9.9")),
enabled: map[identifier.IdentifierType]bool{identifier.TypeDNS: true},
wantErr: "The ACME server has disabled this identifier type",
},
{
name: "IP identifier, DNS & IP enabled",
ident: identifier.NewIP(netip.MustParseAddr("9.9.9.9")),
enabled: map[identifier.IdentifierType]bool{identifier.TypeDNS: true, identifier.TypeIP: true},
wantErr: "",
},
{
name: "IP identifier, IP enabled",
ident: identifier.NewIP(netip.MustParseAddr("9.9.9.9")),
enabled: map[identifier.IdentifierType]bool{identifier.TypeIP: true},
wantErr: "",
},
{
name: "invalid identifier type",
ident: identifier.ACMEIdentifier{Type: "drywall", Value: "oh yeah!"},
enabled: map[identifier.IdentifierType]bool{"drywall": true},
wantErr: "Invalid identifier type",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
policy := blockedNamesPolicy{
HighRiskBlockedNames: []string{"zombo.gov.us"},
ExactBlockedNames: []string{`highvalue.website1.org`},
AdminBlockedNames: []string{`banned.in.dc.com`},
}
yamlPolicyBytes, err := yaml.Marshal(policy)
test.AssertNotError(t, err, "Couldn't YAML serialize blocklist")
yamlPolicyFile, _ := os.CreateTemp("", "test-blocklist.*.yaml")
defer os.Remove(yamlPolicyFile.Name())
err = os.WriteFile(yamlPolicyFile.Name(), yamlPolicyBytes, 0640)
test.AssertNotError(t, err, "Couldn't write YAML blocklist")
pa := paImpl(t)
err = pa.LoadHostnamePolicyFile(yamlPolicyFile.Name())
test.AssertNotError(t, err, "Couldn't load rules")
pa.enabledIdentifiers = tc.enabled
err = pa.WillingToIssue(identifier.ACMEIdentifiers{tc.ident})
if tc.wantErr == "" {
if err != nil {
t.Errorf("should have succeeded, but got error: %s", err.Error())
}
} else {
if err == nil {
t.Errorf("should have failed")
} else if !strings.Contains(err.Error(), tc.wantErr) {
t.Errorf("wrong error; wanted '%s', but got '%s'", tc.wantErr, err.Error())
}
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/third-party/github.com/letsencrypt/boulder/policy/pa.go | third-party/github.com/letsencrypt/boulder/policy/pa.go | package policy
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net/mail"
"net/netip"
"os"
"regexp"
"slices"
"strings"
"sync"
"golang.org/x/net/idna"
"golang.org/x/text/unicode/norm"
"github.com/letsencrypt/boulder/core"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/iana"
"github.com/letsencrypt/boulder/identifier"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/strictyaml"
)
// AuthorityImpl enforces CA policy decisions.
type AuthorityImpl struct {
log blog.Logger
blocklist map[string]bool
exactBlocklist map[string]bool
wildcardExactBlocklist map[string]bool
blocklistMu sync.RWMutex
enabledChallenges map[core.AcmeChallenge]bool
enabledIdentifiers map[identifier.IdentifierType]bool
}
// New constructs a Policy Authority.
func New(identifierTypes map[identifier.IdentifierType]bool, challengeTypes map[core.AcmeChallenge]bool, log blog.Logger) (*AuthorityImpl, error) {
return &AuthorityImpl{
log: log,
enabledChallenges: challengeTypes,
enabledIdentifiers: identifierTypes,
}, nil
}
// blockedNamesPolicy is a struct holding lists of blocked domain names. One for
// exact blocks and one for blocks including all subdomains.
type blockedNamesPolicy struct {
// ExactBlockedNames is a list of domain names. Issuance for names exactly
// matching an entry in the list will be forbidden. (e.g. `ExactBlockedNames`
// containing `www.example.com` will not block `example.com` or
// `mail.example.com`).
ExactBlockedNames []string `yaml:"ExactBlockedNames"`
// HighRiskBlockedNames is like ExactBlockedNames except that issuance is
// blocked for subdomains as well. (e.g. BlockedNames containing `example.com`
// will block `www.example.com`).
//
// This list typically doesn't change with much regularity.
HighRiskBlockedNames []string `yaml:"HighRiskBlockedNames"`
// AdminBlockedNames operates the same as BlockedNames but is changed with more
// frequency based on administrative blocks/revocations that are added over
// time above and beyond the high-risk domains. Managing these entries separately
// from HighRiskBlockedNames makes it easier to vet changes accurately.
AdminBlockedNames []string `yaml:"AdminBlockedNames"`
}
// LoadHostnamePolicyFile will load the given policy file, returning an error if
// it fails.
func (pa *AuthorityImpl) LoadHostnamePolicyFile(f string) error {
configBytes, err := os.ReadFile(f)
if err != nil {
return err
}
hash := sha256.Sum256(configBytes)
pa.log.Infof("loading hostname policy, sha256: %s", hex.EncodeToString(hash[:]))
var policy blockedNamesPolicy
err = strictyaml.Unmarshal(configBytes, &policy)
if err != nil {
return err
}
if len(policy.HighRiskBlockedNames) == 0 {
return fmt.Errorf("No entries in HighRiskBlockedNames.")
}
if len(policy.ExactBlockedNames) == 0 {
return fmt.Errorf("No entries in ExactBlockedNames.")
}
return pa.processHostnamePolicy(policy)
}
// processHostnamePolicy handles loading a new blockedNamesPolicy into the PA.
// All of the policy.ExactBlockedNames will be added to the
// wildcardExactBlocklist by processHostnamePolicy to ensure that wildcards for
// exact blocked names entries are forbidden.
func (pa *AuthorityImpl) processHostnamePolicy(policy blockedNamesPolicy) error {
nameMap := make(map[string]bool)
for _, v := range policy.HighRiskBlockedNames {
nameMap[v] = true
}
for _, v := range policy.AdminBlockedNames {
nameMap[v] = true
}
exactNameMap := make(map[string]bool)
wildcardNameMap := make(map[string]bool)
for _, v := range policy.ExactBlockedNames {
exactNameMap[v] = true
// Remove the leftmost label of the exact blocked names entry to make an exact
// wildcard block list entry that will prevent issuing a wildcard that would
// include the exact blocklist entry. e.g. if "highvalue.example.com" is on
// the exact blocklist we want "example.com" to be in the
// wildcardExactBlocklist so that "*.example.com" cannot be issued.
//
// First, split the domain into two parts: the first label and the rest of the domain.
parts := strings.SplitN(v, ".", 2)
// if there are less than 2 parts then this entry is malformed! There should
// at least be a "something." and a TLD like "com"
if len(parts) < 2 {
return fmt.Errorf(
"Malformed ExactBlockedNames entry, only one label: %q", v)
}
// Add the second part, the domain minus the first label, to the
// wildcardNameMap to block issuance for `*.`+parts[1]
wildcardNameMap[parts[1]] = true
}
pa.blocklistMu.Lock()
pa.blocklist = nameMap
pa.exactBlocklist = exactNameMap
pa.wildcardExactBlocklist = wildcardNameMap
pa.blocklistMu.Unlock()
return nil
}
// The values of maxDNSIdentifierLength, maxLabelLength and maxLabels are hard coded
// into the error messages errNameTooLong, errLabelTooLong and errTooManyLabels.
// If their values change, the related error messages should be updated.
const (
maxLabels = 10
// RFC 1034 says DNS labels have a max of 63 octets, and names have a max of 255
// octets: https://tools.ietf.org/html/rfc1035#page-10. Since two of those octets
// are taken up by the leading length byte and the trailing root period the actual
// max length becomes 253.
maxLabelLength = 63
maxDNSIdentifierLength = 253
)
var dnsLabelCharacterRegexp = regexp.MustCompile("^[a-z0-9-]+$")
func isDNSCharacter(ch byte) bool {
return ('a' <= ch && ch <= 'z') ||
('A' <= ch && ch <= 'Z') ||
('0' <= ch && ch <= '9') ||
ch == '.' || ch == '-'
}
// In these error messages:
// 253 is the value of maxDNSIdentifierLength
// 63 is the value of maxLabelLength
// 10 is the value of maxLabels
// If these values change, the related error messages should be updated.
var (
errNonPublic = berrors.MalformedError("Domain name does not end with a valid public suffix (TLD)")
errICANNTLD = berrors.MalformedError("Domain name is an ICANN TLD")
errPolicyForbidden = berrors.RejectedIdentifierError("The ACME server refuses to issue a certificate for this domain name, because it is forbidden by policy")
errInvalidDNSCharacter = berrors.MalformedError("Domain name contains an invalid character")
errNameTooLong = berrors.MalformedError("Domain name is longer than 253 bytes")
errIPAddressInDNS = berrors.MalformedError("Identifier type is DNS but value is an IP address")
errIPInvalid = berrors.MalformedError("IP address is invalid")
errTooManyLabels = berrors.MalformedError("Domain name has more than 10 labels (parts)")
errEmptyIdentifier = berrors.MalformedError("Identifier value (name) is empty")
errNameEndsInDot = berrors.MalformedError("Domain name ends in a dot")
errTooFewLabels = berrors.MalformedError("Domain name needs at least one dot")
errLabelTooShort = berrors.MalformedError("Domain name can not have two dots in a row")
errLabelTooLong = berrors.MalformedError("Domain has a label (component between dots) longer than 63 bytes")
errMalformedIDN = berrors.MalformedError("Domain name contains malformed punycode")
errInvalidRLDH = berrors.RejectedIdentifierError("Domain name contains an invalid label in a reserved format (R-LDH: '??--')")
errTooManyWildcards = berrors.MalformedError("Domain name has more than one wildcard")
errMalformedWildcard = berrors.MalformedError("Domain name contains an invalid wildcard. A wildcard is only permitted before the first dot in a domain name")
errICANNTLDWildcard = berrors.MalformedError("Domain name is a wildcard for an ICANN TLD")
errWildcardNotSupported = berrors.MalformedError("Wildcard domain names are not supported")
errUnsupportedIdent = berrors.MalformedError("Invalid identifier type")
)
// validNonWildcardDomain checks that a domain isn't:
// - empty
// - prefixed with the wildcard label `*.`
// - made of invalid DNS characters
// - longer than the maxDNSIdentifierLength
// - an IPv4 or IPv6 address
// - suffixed with just "."
// - made of too many DNS labels
// - made of any invalid DNS labels
// - suffixed with something other than an IANA registered TLD
// - exactly equal to an IANA registered TLD
//
// It does NOT ensure that the domain is absent from any PA blocked lists.
func validNonWildcardDomain(domain string) error {
if domain == "" {
return errEmptyIdentifier
}
if strings.HasPrefix(domain, "*.") {
return errWildcardNotSupported
}
for _, ch := range []byte(domain) {
if !isDNSCharacter(ch) {
return errInvalidDNSCharacter
}
}
if len(domain) > maxDNSIdentifierLength {
return errNameTooLong
}
_, err := netip.ParseAddr(domain)
if err == nil {
return errIPAddressInDNS
}
if strings.HasSuffix(domain, ".") {
return errNameEndsInDot
}
labels := strings.Split(domain, ".")
if len(labels) > maxLabels {
return errTooManyLabels
}
if len(labels) < 2 {
return errTooFewLabels
}
for _, label := range labels {
// Check that this is a valid LDH Label: "A string consisting of ASCII
// letters, digits, and the hyphen with the further restriction that the
// hyphen cannot appear at the beginning or end of the string. Like all DNS
// labels, its total length must not exceed 63 octets." (RFC 5890, 2.3.1)
if len(label) < 1 {
return errLabelTooShort
}
if len(label) > maxLabelLength {
return errLabelTooLong
}
if !dnsLabelCharacterRegexp.MatchString(label) {
return errInvalidDNSCharacter
}
if label[0] == '-' || label[len(label)-1] == '-' {
return errInvalidDNSCharacter
}
// Check if this is a Reserved LDH Label: "[has] the property that they
// contain "--" in the third and fourth characters but which otherwise
// conform to LDH label rules." (RFC 5890, 2.3.1)
if len(label) >= 4 && label[2:4] == "--" {
// Check if this is an XN-Label: "labels that begin with the prefix "xn--"
// (case independent), but otherwise conform to the rules for LDH labels."
// (RFC 5890, 2.3.1)
if label[0:2] != "xn" {
return errInvalidRLDH
}
// Check if this is a P-Label: "A XN-Label that contains valid output of
// the Punycode algorithm (as defined in RFC 3492, Section 6.3) from the
// fifth and subsequent positions." (Baseline Requirements, 1.6.1)
ulabel, err := idna.ToUnicode(label)
if err != nil {
return errMalformedIDN
}
if !norm.NFC.IsNormalString(ulabel) {
return errMalformedIDN
}
}
}
// Names must end in an ICANN TLD, but they must not be equal to an ICANN TLD.
icannTLD, err := iana.ExtractSuffix(domain)
if err != nil {
return errNonPublic
}
if icannTLD == domain {
return errICANNTLD
}
return nil
}
// ValidDomain checks that a domain is valid and that it doesn't contain any
// invalid wildcard characters. It does NOT ensure that the domain is absent
// from any PA blocked lists.
func ValidDomain(domain string) error {
if strings.Count(domain, "*") <= 0 {
return validNonWildcardDomain(domain)
}
// Names containing more than one wildcard are invalid.
if strings.Count(domain, "*") > 1 {
return errTooManyWildcards
}
// If the domain has a wildcard character, but it isn't the first most
// label of the domain name then the wildcard domain is malformed
if !strings.HasPrefix(domain, "*.") {
return errMalformedWildcard
}
// The base domain is the wildcard request with the `*.` prefix removed
baseDomain := strings.TrimPrefix(domain, "*.")
// Names must end in an ICANN TLD, but they must not be equal to an ICANN TLD.
icannTLD, err := iana.ExtractSuffix(baseDomain)
if err != nil {
return errNonPublic
}
// Names must have a non-wildcard label immediately adjacent to the ICANN
// TLD. No `*.com`!
if baseDomain == icannTLD {
return errICANNTLDWildcard
}
return validNonWildcardDomain(baseDomain)
}
// ValidIP checks that an IP address:
// - isn't empty
// - is an IPv4 or IPv6 address
// - isn't in an IANA special-purpose address registry
//
// It does NOT ensure that the IP address is absent from any PA blocked lists.
func ValidIP(ip string) error {
if ip == "" {
return errEmptyIdentifier
}
// Check the output of netip.Addr.String(), to ensure the input complied
// with RFC 8738, Sec. 3. ("The identifier value MUST contain the textual
// form of the address as defined in RFC 1123, Sec. 2.1 for IPv4 and in RFC
// 5952, Sec. 4 for IPv6.") ParseAddr() will accept a non-compliant but
// otherwise valid string; String() will output a compliant string.
parsedIP, err := netip.ParseAddr(ip)
if err != nil || parsedIP.String() != ip {
return errIPInvalid
}
return iana.IsReservedAddr(parsedIP)
}
// forbiddenMailDomains is a map of domain names we do not allow after the
// @ symbol in contact mailto addresses. These are frequently used when
// copy-pasting example configurations and would not result in expiration
// messages and subscriber communications reaching the user that created the
// registration if allowed.
var forbiddenMailDomains = map[string]bool{
// https://tools.ietf.org/html/rfc2606#section-3
"example.com": true,
"example.net": true,
"example.org": true,
}
// ValidEmail returns an error if the input doesn't parse as an email address,
// the domain isn't a valid hostname in Preferred Name Syntax, or its on the
// list of domains forbidden for mail (because they are often used in examples).
func ValidEmail(address string) error {
email, err := mail.ParseAddress(address)
if err != nil {
return berrors.InvalidEmailError("unable to parse email address")
}
splitEmail := strings.SplitN(email.Address, "@", -1)
domain := strings.ToLower(splitEmail[len(splitEmail)-1])
err = validNonWildcardDomain(domain)
if err != nil {
return berrors.InvalidEmailError("contact email has invalid domain: %s", err)
}
if forbiddenMailDomains[domain] {
// We're okay including the domain in the error message here because this
// case occurs only for a small block-list of domains listed above.
return berrors.InvalidEmailError("contact email has forbidden domain %q", domain)
}
return nil
}
// subError returns an appropriately typed error based on the input error
func subError(ident identifier.ACMEIdentifier, err error) berrors.SubBoulderError {
var bErr *berrors.BoulderError
if errors.As(err, &bErr) {
return berrors.SubBoulderError{
Identifier: ident,
BoulderError: bErr,
}
} else {
return berrors.SubBoulderError{
Identifier: ident,
BoulderError: &berrors.BoulderError{
Type: berrors.RejectedIdentifier,
Detail: err.Error(),
},
}
}
}
// WillingToIssue determines whether the CA is willing to issue for the provided
// identifiers.
//
// It checks the criteria checked by `WellFormedIdentifiers`, and additionally
// checks whether any identifier is on a blocklist.
//
// If multiple identifiers are invalid, the error will contain suberrors
// specific to each identifier.
//
// Precondition: all input identifier values must be in lowercase.
func (pa *AuthorityImpl) WillingToIssue(idents identifier.ACMEIdentifiers) error {
err := WellFormedIdentifiers(idents)
if err != nil {
return err
}
var subErrors []berrors.SubBoulderError
for _, ident := range idents {
if !pa.IdentifierTypeEnabled(ident.Type) {
subErrors = append(subErrors, subError(ident, berrors.RejectedIdentifierError("The ACME server has disabled this identifier type")))
continue
}
// Only DNS identifiers are subject to wildcard and blocklist checks.
// Unsupported identifier types will have been caught by
// WellFormedIdentifiers().
//
// TODO(#8237): We may want to implement IP address blocklists too.
if ident.Type == identifier.TypeDNS {
if strings.Count(ident.Value, "*") > 0 {
// The base domain is the wildcard request with the `*.` prefix removed
baseDomain := strings.TrimPrefix(ident.Value, "*.")
// The base domain can't be in the wildcard exact blocklist
err = pa.checkWildcardHostList(baseDomain)
if err != nil {
subErrors = append(subErrors, subError(ident, err))
continue
}
}
// For both wildcard and non-wildcard domains, check whether any parent domain
// name is on the regular blocklist.
err := pa.checkHostLists(ident.Value)
if err != nil {
subErrors = append(subErrors, subError(ident, err))
continue
}
}
}
return combineSubErrors(subErrors)
}
// WellFormedIdentifiers returns an error if any of the provided identifiers do
// not meet these criteria:
//
// For DNS identifiers:
// - MUST contains only lowercase characters, numbers, hyphens, and dots
// - MUST NOT have more than maxLabels labels
// - MUST follow the DNS hostname syntax rules in RFC 1035 and RFC 2181
//
// In particular, DNS identifiers:
// - MUST NOT contain underscores
// - MUST NOT match the syntax of an IP address
// - MUST end in a public suffix
// - MUST have at least one label in addition to the public suffix
// - MUST NOT be a label-wise suffix match for a name on the block list,
// where comparison is case-independent (normalized to lower case)
//
// If a DNS identifier contains a *, we additionally require:
// - There is at most one `*` wildcard character
// - That the wildcard character is the leftmost label
// - That the wildcard label is not immediately adjacent to a top level ICANN
// TLD
//
// For IP identifiers:
// - MUST match the syntax of an IP address
// - MUST NOT be in an IANA special-purpose address registry
//
// If multiple identifiers are invalid, the error will contain suberrors
// specific to each identifier.
func WellFormedIdentifiers(idents identifier.ACMEIdentifiers) error {
var subErrors []berrors.SubBoulderError
for _, ident := range idents {
switch ident.Type {
case identifier.TypeDNS:
err := ValidDomain(ident.Value)
if err != nil {
subErrors = append(subErrors, subError(ident, err))
}
case identifier.TypeIP:
err := ValidIP(ident.Value)
if err != nil {
subErrors = append(subErrors, subError(ident, err))
}
default:
subErrors = append(subErrors, subError(ident, errUnsupportedIdent))
}
}
return combineSubErrors(subErrors)
}
func combineSubErrors(subErrors []berrors.SubBoulderError) error {
if len(subErrors) > 0 {
// If there was only one error, then use it as the top level error that is
// returned.
if len(subErrors) == 1 {
return berrors.RejectedIdentifierError(
"Cannot issue for %q: %s",
subErrors[0].Identifier.Value,
subErrors[0].BoulderError.Detail,
)
}
detail := fmt.Sprintf(
"Cannot issue for %q: %s (and %d more problems. Refer to sub-problems for more information.)",
subErrors[0].Identifier.Value,
subErrors[0].BoulderError.Detail,
len(subErrors)-1,
)
return (&berrors.BoulderError{
Type: berrors.RejectedIdentifier,
Detail: detail,
}).WithSubErrors(subErrors)
}
return nil
}
// checkWildcardHostList checks the wildcardExactBlocklist for a given domain.
// If the domain is not present on the list nil is returned, otherwise
// errPolicyForbidden is returned.
func (pa *AuthorityImpl) checkWildcardHostList(domain string) error {
pa.blocklistMu.RLock()
defer pa.blocklistMu.RUnlock()
if pa.wildcardExactBlocklist == nil {
return fmt.Errorf("Hostname policy not yet loaded.")
}
if pa.wildcardExactBlocklist[domain] {
return errPolicyForbidden
}
return nil
}
func (pa *AuthorityImpl) checkHostLists(domain string) error {
pa.blocklistMu.RLock()
defer pa.blocklistMu.RUnlock()
if pa.blocklist == nil {
return fmt.Errorf("Hostname policy not yet loaded.")
}
labels := strings.Split(domain, ".")
for i := range labels {
joined := strings.Join(labels[i:], ".")
if pa.blocklist[joined] {
return errPolicyForbidden
}
}
if pa.exactBlocklist[domain] {
return errPolicyForbidden
}
return nil
}
// ChallengeTypesFor determines which challenge types are acceptable for the
// given identifier. This determination is made purely based on the identifier,
// and not based on which challenge types are enabled, so that challenge type
// filtering can happen dynamically at request rather than being set in stone
// at creation time.
func (pa *AuthorityImpl) ChallengeTypesFor(ident identifier.ACMEIdentifier) ([]core.AcmeChallenge, error) {
switch ident.Type {
case identifier.TypeDNS:
// If the identifier is for a DNS wildcard name we only provide a DNS-01
// challenge, to comply with the BRs Sections 3.2.2.4.19 and 3.2.2.4.20
// stating that ACME HTTP-01 and TLS-ALPN-01 are not suitable for validating
// Wildcard Domains.
if strings.HasPrefix(ident.Value, "*.") {
return []core.AcmeChallenge{core.ChallengeTypeDNS01}, nil
}
// Return all challenge types we support for non-wildcard DNS identifiers.
return []core.AcmeChallenge{
core.ChallengeTypeHTTP01,
core.ChallengeTypeDNS01,
core.ChallengeTypeTLSALPN01,
}, nil
case identifier.TypeIP:
// Only HTTP-01 and TLS-ALPN-01 are suitable for IP address identifiers
// per RFC 8738, Sec. 4.
return []core.AcmeChallenge{
core.ChallengeTypeHTTP01,
core.ChallengeTypeTLSALPN01,
}, nil
default:
// Otherwise return an error because we don't support any challenges for this
// identifier type.
return nil, fmt.Errorf("unrecognized identifier type %q", ident.Type)
}
}
// ChallengeTypeEnabled returns whether the specified challenge type is enabled
func (pa *AuthorityImpl) ChallengeTypeEnabled(t core.AcmeChallenge) bool {
pa.blocklistMu.RLock()
defer pa.blocklistMu.RUnlock()
return pa.enabledChallenges[t]
}
// CheckAuthzChallenges determines that an authorization was fulfilled by a
// challenge that is currently enabled and was appropriate for the kind of
// identifier in the authorization.
func (pa *AuthorityImpl) CheckAuthzChallenges(authz *core.Authorization) error {
chall, err := authz.SolvedBy()
if err != nil {
return err
}
if !pa.ChallengeTypeEnabled(chall) {
return errors.New("authorization fulfilled by disabled challenge type")
}
challTypes, err := pa.ChallengeTypesFor(authz.Identifier)
if err != nil {
return err
}
if !slices.Contains(challTypes, chall) {
return errors.New("authorization fulfilled by inapplicable challenge type")
}
return nil
}
// IdentifierTypeEnabled returns whether the specified identifier type is enabled
func (pa *AuthorityImpl) IdentifierTypeEnabled(t identifier.IdentifierType) bool {
pa.blocklistMu.RLock()
defer pa.blocklistMu.RUnlock()
return pa.enabledIdentifiers[t]
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/gh/projects.go | internal/gh/projects.go | package gh
// ProjectsV1Support provides type safety and readability around whether or not Projects v1 is supported
// by the targeted host.
//
// It is a sealed type to ensure that consumers must use the exported ProjectsV1Supported and ProjectsV1Unsupported
// variables to get an instance of the type.
type ProjectsV1Support interface {
sealed()
}
type projectsV1Supported struct{}
func (projectsV1Supported) sealed() {}
type projectsV1Unsupported struct{}
func (projectsV1Unsupported) sealed() {}
var (
ProjectsV1Supported ProjectsV1Support = projectsV1Supported{}
ProjectsV1Unsupported ProjectsV1Support = projectsV1Unsupported{}
)
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/gh/gh.go | internal/gh/gh.go | // Package gh provides types that represent the domain of the CLI application.
//
// For example, the CLI expects to be able to get and set user configuration in order to perform its functionality,
// so the Config interface is defined here, though the concrete implementation lives elsewhere. Though the current
// implementation of config writes to certain files on disk, that is an implementation detail compared to the contract
// laid out in the interface here.
//
// Currently this package is in an early state but we could imagine other domain concepts living here for interacting
// with git or GitHub.
package gh
import (
o "github.com/cli/cli/v2/pkg/option"
ghConfig "github.com/cli/go-gh/v2/pkg/config"
)
type ConfigSource string
const (
ConfigDefaultProvided ConfigSource = "default"
ConfigUserProvided ConfigSource = "user"
)
type ConfigEntry struct {
Value string
Source ConfigSource
}
// A Config implements persistent storage and modification of application configuration.
//
//go:generate moq -rm -pkg ghmock -out mock/config.go . Config
type Config interface {
// GetOrDefault provides primitive access for fetching configuration values, optionally scoped by host.
GetOrDefault(hostname string, key string) o.Option[ConfigEntry]
// Set provides primitive access for setting configuration values, optionally scoped by host.
Set(hostname string, key string, value string)
// AccessibleColors returns the configured accessible_colors setting, optionally scoped by host.
AccessibleColors(hostname string) ConfigEntry
// AccessiblePrompter returns the configured accessible_prompter setting, optionally scoped by host.
AccessiblePrompter(hostname string) ConfigEntry
// Browser returns the configured browser, optionally scoped by host.
Browser(hostname string) ConfigEntry
// ColorLabels returns the configured color_label setting, optionally scoped by host.
ColorLabels(hostname string) ConfigEntry
// Editor returns the configured editor, optionally scoped by host.
Editor(hostname string) ConfigEntry
// GitProtocol returns the configured git protocol, optionally scoped by host.
GitProtocol(hostname string) ConfigEntry
// HTTPUnixSocket returns the configured HTTP unix socket, optionally scoped by host.
HTTPUnixSocket(hostname string) ConfigEntry
// Pager returns the configured Pager, optionally scoped by host.
Pager(hostname string) ConfigEntry
// Prompt returns the configured prompt, optionally scoped by host.
Prompt(hostname string) ConfigEntry
// PreferEditorPrompt returns the configured editor-based prompt, optionally scoped by host.
PreferEditorPrompt(hostname string) ConfigEntry
// Spinner returns the configured spinner setting, optionally scoped by host.
Spinner(hostname string) ConfigEntry
// Aliases provides persistent storage and modification of command aliases.
Aliases() AliasConfig
// Authentication provides persistent storage and modification of authentication configuration.
Authentication() AuthConfig
// CacheDir returns the directory where the cacheable artifacts can be persisted.
CacheDir() string
// Migrate applies a migration to the configuration.
Migrate(Migration) error
// Version returns the current schema version of the configuration.
Version() o.Option[string]
// Write persists modifications to the configuration.
Write() error
}
// Migration is the interface that config migrations must implement.
//
// Migrations will receive a copy of the config, and should modify that copy
// as necessary. After migration has completed, the modified config contents
// will be used.
//
// The calling code is expected to verify that the current version of the config
// matches the PreVersion of the migration before calling Do, and will set the
// config version to the PostVersion after the migration has completed successfully.
//
//go:generate moq -rm -pkg ghmock -out mock/migration.go . Migration
type Migration interface {
// PreVersion is the required config version for this to be applied
PreVersion() string
// PostVersion is the config version that must be applied after migration
PostVersion() string
// Do is expected to apply any necessary changes to the config in place
Do(*ghConfig.Config) error
}
// AuthConfig is used for interacting with some persistent configuration for gh,
// with knowledge on how to access encrypted storage when necessary.
// Behavior is scoped to authentication specific tasks.
type AuthConfig interface {
// HasActiveToken returns true when a token for the hostname is present.
HasActiveToken(hostname string) bool
// ActiveToken will retrieve the active auth token for the given hostname, searching environment variables,
// general configuration, and finally encrypted storage.
ActiveToken(hostname string) (token string, source string)
// HasEnvToken returns true when a token has been specified in an environment variable, else returns false.
HasEnvToken() bool
// TokenFromKeyring will retrieve the auth token for the given hostname, only searching in encrypted storage.
TokenFromKeyring(hostname string) (token string, err error)
// TokenFromKeyringForUser will retrieve the auth token for the given hostname and username, only searching
// in encrypted storage.
//
// An empty username will return an error because the potential to return the currently active token under
// surprising cases is just too high to risk compared to the utility of having the function being smart.
TokenFromKeyringForUser(hostname, username string) (token string, err error)
// ActiveUser will retrieve the username for the active user at the given hostname.
//
// This will not be accurate if the oauth token is set from an environment variable.
ActiveUser(hostname string) (username string, err error)
// Hosts retrieves a list of known hosts.
Hosts() []string
// DefaultHost retrieves the default host.
DefaultHost() (host string, source string)
// Login will set user, git protocol, and auth token for the given hostname.
//
// If the encrypt option is specified it will first try to store the auth token
// in encrypted storage and will fall back to the general insecure configuration.
Login(hostname, username, token, gitProtocol string, secureStorage bool) (insecureStorageUsed bool, err error)
// SwitchUser switches the active user for a given hostname.
SwitchUser(hostname, user string) error
// Logout will remove user, git protocol, and auth token for the given hostname.
// It will remove the auth token from the encrypted storage if it exists there.
Logout(hostname, username string) error
// UsersForHost retrieves a list of users configured for a specific host.
UsersForHost(hostname string) []string
// TokenForUser retrieves the authentication token and its source for a specified user and hostname.
TokenForUser(hostname, user string) (token string, source string, err error)
// The following methods are only for testing and that is a design smell we should consider fixing.
// SetActiveToken will override any token resolution and return the given token and source for all calls to
// ActiveToken.
// Use for testing purposes only.
SetActiveToken(token, source string)
// SetHosts will override any hosts resolution and return the given hosts for all calls to Hosts.
// Use for testing purposes only.
SetHosts(hosts []string)
// SetDefaultHost will override any host resolution and return the given host and source for all calls to
// DefaultHost.
// Use for testing purposes only.
SetDefaultHost(host, source string)
}
// AliasConfig defines an interface for managing command aliases.
type AliasConfig interface {
// Get retrieves the expansion for a specified alias.
Get(alias string) (expansion string, err error)
// Add adds a new alias with the specified expansion.
Add(alias, expansion string)
// Delete removes an alias.
Delete(alias string) error
// All returns a map of all aliases to their corresponding expansions.
All() map[string]string
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/gh/mock/config.go | internal/gh/mock/config.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package ghmock
import (
"github.com/cli/cli/v2/internal/gh"
o "github.com/cli/cli/v2/pkg/option"
"sync"
)
// Ensure, that ConfigMock does implement gh.Config.
// If this is not the case, regenerate this file with moq.
var _ gh.Config = &ConfigMock{}
// ConfigMock is a mock implementation of gh.Config.
//
// func TestSomethingThatUsesConfig(t *testing.T) {
//
// // make and configure a mocked gh.Config
// mockedConfig := &ConfigMock{
// AccessibleColorsFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the AccessibleColors method")
// },
// AccessiblePrompterFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the AccessiblePrompter method")
// },
// AliasesFunc: func() gh.AliasConfig {
// panic("mock out the Aliases method")
// },
// AuthenticationFunc: func() gh.AuthConfig {
// panic("mock out the Authentication method")
// },
// BrowserFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the Browser method")
// },
// CacheDirFunc: func() string {
// panic("mock out the CacheDir method")
// },
// ColorLabelsFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the ColorLabels method")
// },
// EditorFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the Editor method")
// },
// GetOrDefaultFunc: func(hostname string, key string) o.Option[gh.ConfigEntry] {
// panic("mock out the GetOrDefault method")
// },
// GitProtocolFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the GitProtocol method")
// },
// HTTPUnixSocketFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the HTTPUnixSocket method")
// },
// MigrateFunc: func(migration gh.Migration) error {
// panic("mock out the Migrate method")
// },
// PagerFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the Pager method")
// },
// PreferEditorPromptFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the PreferEditorPrompt method")
// },
// PromptFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the Prompt method")
// },
// SetFunc: func(hostname string, key string, value string) {
// panic("mock out the Set method")
// },
// SpinnerFunc: func(hostname string) gh.ConfigEntry {
// panic("mock out the Spinner method")
// },
// VersionFunc: func() o.Option[string] {
// panic("mock out the Version method")
// },
// WriteFunc: func() error {
// panic("mock out the Write method")
// },
// }
//
// // use mockedConfig in code that requires gh.Config
// // and then make assertions.
//
// }
type ConfigMock struct {
// AccessibleColorsFunc mocks the AccessibleColors method.
AccessibleColorsFunc func(hostname string) gh.ConfigEntry
// AccessiblePrompterFunc mocks the AccessiblePrompter method.
AccessiblePrompterFunc func(hostname string) gh.ConfigEntry
// AliasesFunc mocks the Aliases method.
AliasesFunc func() gh.AliasConfig
// AuthenticationFunc mocks the Authentication method.
AuthenticationFunc func() gh.AuthConfig
// BrowserFunc mocks the Browser method.
BrowserFunc func(hostname string) gh.ConfigEntry
// CacheDirFunc mocks the CacheDir method.
CacheDirFunc func() string
// ColorLabelsFunc mocks the ColorLabels method.
ColorLabelsFunc func(hostname string) gh.ConfigEntry
// EditorFunc mocks the Editor method.
EditorFunc func(hostname string) gh.ConfigEntry
// GetOrDefaultFunc mocks the GetOrDefault method.
GetOrDefaultFunc func(hostname string, key string) o.Option[gh.ConfigEntry]
// GitProtocolFunc mocks the GitProtocol method.
GitProtocolFunc func(hostname string) gh.ConfigEntry
// HTTPUnixSocketFunc mocks the HTTPUnixSocket method.
HTTPUnixSocketFunc func(hostname string) gh.ConfigEntry
// MigrateFunc mocks the Migrate method.
MigrateFunc func(migration gh.Migration) error
// PagerFunc mocks the Pager method.
PagerFunc func(hostname string) gh.ConfigEntry
// PreferEditorPromptFunc mocks the PreferEditorPrompt method.
PreferEditorPromptFunc func(hostname string) gh.ConfigEntry
// PromptFunc mocks the Prompt method.
PromptFunc func(hostname string) gh.ConfigEntry
// SetFunc mocks the Set method.
SetFunc func(hostname string, key string, value string)
// SpinnerFunc mocks the Spinner method.
SpinnerFunc func(hostname string) gh.ConfigEntry
// VersionFunc mocks the Version method.
VersionFunc func() o.Option[string]
// WriteFunc mocks the Write method.
WriteFunc func() error
// calls tracks calls to the methods.
calls struct {
// AccessibleColors holds details about calls to the AccessibleColors method.
AccessibleColors []struct {
// Hostname is the hostname argument value.
Hostname string
}
// AccessiblePrompter holds details about calls to the AccessiblePrompter method.
AccessiblePrompter []struct {
// Hostname is the hostname argument value.
Hostname string
}
// Aliases holds details about calls to the Aliases method.
Aliases []struct {
}
// Authentication holds details about calls to the Authentication method.
Authentication []struct {
}
// Browser holds details about calls to the Browser method.
Browser []struct {
// Hostname is the hostname argument value.
Hostname string
}
// CacheDir holds details about calls to the CacheDir method.
CacheDir []struct {
}
// ColorLabels holds details about calls to the ColorLabels method.
ColorLabels []struct {
// Hostname is the hostname argument value.
Hostname string
}
// Editor holds details about calls to the Editor method.
Editor []struct {
// Hostname is the hostname argument value.
Hostname string
}
// GetOrDefault holds details about calls to the GetOrDefault method.
GetOrDefault []struct {
// Hostname is the hostname argument value.
Hostname string
// Key is the key argument value.
Key string
}
// GitProtocol holds details about calls to the GitProtocol method.
GitProtocol []struct {
// Hostname is the hostname argument value.
Hostname string
}
// HTTPUnixSocket holds details about calls to the HTTPUnixSocket method.
HTTPUnixSocket []struct {
// Hostname is the hostname argument value.
Hostname string
}
// Migrate holds details about calls to the Migrate method.
Migrate []struct {
// Migration is the migration argument value.
Migration gh.Migration
}
// Pager holds details about calls to the Pager method.
Pager []struct {
// Hostname is the hostname argument value.
Hostname string
}
// PreferEditorPrompt holds details about calls to the PreferEditorPrompt method.
PreferEditorPrompt []struct {
// Hostname is the hostname argument value.
Hostname string
}
// Prompt holds details about calls to the Prompt method.
Prompt []struct {
// Hostname is the hostname argument value.
Hostname string
}
// Set holds details about calls to the Set method.
Set []struct {
// Hostname is the hostname argument value.
Hostname string
// Key is the key argument value.
Key string
// Value is the value argument value.
Value string
}
// Spinner holds details about calls to the Spinner method.
Spinner []struct {
// Hostname is the hostname argument value.
Hostname string
}
// Version holds details about calls to the Version method.
Version []struct {
}
// Write holds details about calls to the Write method.
Write []struct {
}
}
lockAccessibleColors sync.RWMutex
lockAccessiblePrompter sync.RWMutex
lockAliases sync.RWMutex
lockAuthentication sync.RWMutex
lockBrowser sync.RWMutex
lockCacheDir sync.RWMutex
lockColorLabels sync.RWMutex
lockEditor sync.RWMutex
lockGetOrDefault sync.RWMutex
lockGitProtocol sync.RWMutex
lockHTTPUnixSocket sync.RWMutex
lockMigrate sync.RWMutex
lockPager sync.RWMutex
lockPreferEditorPrompt sync.RWMutex
lockPrompt sync.RWMutex
lockSet sync.RWMutex
lockSpinner sync.RWMutex
lockVersion sync.RWMutex
lockWrite sync.RWMutex
}
// AccessibleColors calls AccessibleColorsFunc.
func (mock *ConfigMock) AccessibleColors(hostname string) gh.ConfigEntry {
if mock.AccessibleColorsFunc == nil {
panic("ConfigMock.AccessibleColorsFunc: method is nil but Config.AccessibleColors was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockAccessibleColors.Lock()
mock.calls.AccessibleColors = append(mock.calls.AccessibleColors, callInfo)
mock.lockAccessibleColors.Unlock()
return mock.AccessibleColorsFunc(hostname)
}
// AccessibleColorsCalls gets all the calls that were made to AccessibleColors.
// Check the length with:
//
// len(mockedConfig.AccessibleColorsCalls())
func (mock *ConfigMock) AccessibleColorsCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockAccessibleColors.RLock()
calls = mock.calls.AccessibleColors
mock.lockAccessibleColors.RUnlock()
return calls
}
// AccessiblePrompter calls AccessiblePrompterFunc.
func (mock *ConfigMock) AccessiblePrompter(hostname string) gh.ConfigEntry {
if mock.AccessiblePrompterFunc == nil {
panic("ConfigMock.AccessiblePrompterFunc: method is nil but Config.AccessiblePrompter was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockAccessiblePrompter.Lock()
mock.calls.AccessiblePrompter = append(mock.calls.AccessiblePrompter, callInfo)
mock.lockAccessiblePrompter.Unlock()
return mock.AccessiblePrompterFunc(hostname)
}
// AccessiblePrompterCalls gets all the calls that were made to AccessiblePrompter.
// Check the length with:
//
// len(mockedConfig.AccessiblePrompterCalls())
func (mock *ConfigMock) AccessiblePrompterCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockAccessiblePrompter.RLock()
calls = mock.calls.AccessiblePrompter
mock.lockAccessiblePrompter.RUnlock()
return calls
}
// Aliases calls AliasesFunc.
func (mock *ConfigMock) Aliases() gh.AliasConfig {
if mock.AliasesFunc == nil {
panic("ConfigMock.AliasesFunc: method is nil but Config.Aliases was just called")
}
callInfo := struct {
}{}
mock.lockAliases.Lock()
mock.calls.Aliases = append(mock.calls.Aliases, callInfo)
mock.lockAliases.Unlock()
return mock.AliasesFunc()
}
// AliasesCalls gets all the calls that were made to Aliases.
// Check the length with:
//
// len(mockedConfig.AliasesCalls())
func (mock *ConfigMock) AliasesCalls() []struct {
} {
var calls []struct {
}
mock.lockAliases.RLock()
calls = mock.calls.Aliases
mock.lockAliases.RUnlock()
return calls
}
// Authentication calls AuthenticationFunc.
func (mock *ConfigMock) Authentication() gh.AuthConfig {
if mock.AuthenticationFunc == nil {
panic("ConfigMock.AuthenticationFunc: method is nil but Config.Authentication was just called")
}
callInfo := struct {
}{}
mock.lockAuthentication.Lock()
mock.calls.Authentication = append(mock.calls.Authentication, callInfo)
mock.lockAuthentication.Unlock()
return mock.AuthenticationFunc()
}
// AuthenticationCalls gets all the calls that were made to Authentication.
// Check the length with:
//
// len(mockedConfig.AuthenticationCalls())
func (mock *ConfigMock) AuthenticationCalls() []struct {
} {
var calls []struct {
}
mock.lockAuthentication.RLock()
calls = mock.calls.Authentication
mock.lockAuthentication.RUnlock()
return calls
}
// Browser calls BrowserFunc.
func (mock *ConfigMock) Browser(hostname string) gh.ConfigEntry {
if mock.BrowserFunc == nil {
panic("ConfigMock.BrowserFunc: method is nil but Config.Browser was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockBrowser.Lock()
mock.calls.Browser = append(mock.calls.Browser, callInfo)
mock.lockBrowser.Unlock()
return mock.BrowserFunc(hostname)
}
// BrowserCalls gets all the calls that were made to Browser.
// Check the length with:
//
// len(mockedConfig.BrowserCalls())
func (mock *ConfigMock) BrowserCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockBrowser.RLock()
calls = mock.calls.Browser
mock.lockBrowser.RUnlock()
return calls
}
// CacheDir calls CacheDirFunc.
func (mock *ConfigMock) CacheDir() string {
if mock.CacheDirFunc == nil {
panic("ConfigMock.CacheDirFunc: method is nil but Config.CacheDir was just called")
}
callInfo := struct {
}{}
mock.lockCacheDir.Lock()
mock.calls.CacheDir = append(mock.calls.CacheDir, callInfo)
mock.lockCacheDir.Unlock()
return mock.CacheDirFunc()
}
// CacheDirCalls gets all the calls that were made to CacheDir.
// Check the length with:
//
// len(mockedConfig.CacheDirCalls())
func (mock *ConfigMock) CacheDirCalls() []struct {
} {
var calls []struct {
}
mock.lockCacheDir.RLock()
calls = mock.calls.CacheDir
mock.lockCacheDir.RUnlock()
return calls
}
// ColorLabels calls ColorLabelsFunc.
func (mock *ConfigMock) ColorLabels(hostname string) gh.ConfigEntry {
if mock.ColorLabelsFunc == nil {
panic("ConfigMock.ColorLabelsFunc: method is nil but Config.ColorLabels was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockColorLabels.Lock()
mock.calls.ColorLabels = append(mock.calls.ColorLabels, callInfo)
mock.lockColorLabels.Unlock()
return mock.ColorLabelsFunc(hostname)
}
// ColorLabelsCalls gets all the calls that were made to ColorLabels.
// Check the length with:
//
// len(mockedConfig.ColorLabelsCalls())
func (mock *ConfigMock) ColorLabelsCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockColorLabels.RLock()
calls = mock.calls.ColorLabels
mock.lockColorLabels.RUnlock()
return calls
}
// Editor calls EditorFunc.
func (mock *ConfigMock) Editor(hostname string) gh.ConfigEntry {
if mock.EditorFunc == nil {
panic("ConfigMock.EditorFunc: method is nil but Config.Editor was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockEditor.Lock()
mock.calls.Editor = append(mock.calls.Editor, callInfo)
mock.lockEditor.Unlock()
return mock.EditorFunc(hostname)
}
// EditorCalls gets all the calls that were made to Editor.
// Check the length with:
//
// len(mockedConfig.EditorCalls())
func (mock *ConfigMock) EditorCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockEditor.RLock()
calls = mock.calls.Editor
mock.lockEditor.RUnlock()
return calls
}
// GetOrDefault calls GetOrDefaultFunc.
func (mock *ConfigMock) GetOrDefault(hostname string, key string) o.Option[gh.ConfigEntry] {
if mock.GetOrDefaultFunc == nil {
panic("ConfigMock.GetOrDefaultFunc: method is nil but Config.GetOrDefault was just called")
}
callInfo := struct {
Hostname string
Key string
}{
Hostname: hostname,
Key: key,
}
mock.lockGetOrDefault.Lock()
mock.calls.GetOrDefault = append(mock.calls.GetOrDefault, callInfo)
mock.lockGetOrDefault.Unlock()
return mock.GetOrDefaultFunc(hostname, key)
}
// GetOrDefaultCalls gets all the calls that were made to GetOrDefault.
// Check the length with:
//
// len(mockedConfig.GetOrDefaultCalls())
func (mock *ConfigMock) GetOrDefaultCalls() []struct {
Hostname string
Key string
} {
var calls []struct {
Hostname string
Key string
}
mock.lockGetOrDefault.RLock()
calls = mock.calls.GetOrDefault
mock.lockGetOrDefault.RUnlock()
return calls
}
// GitProtocol calls GitProtocolFunc.
func (mock *ConfigMock) GitProtocol(hostname string) gh.ConfigEntry {
if mock.GitProtocolFunc == nil {
panic("ConfigMock.GitProtocolFunc: method is nil but Config.GitProtocol was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockGitProtocol.Lock()
mock.calls.GitProtocol = append(mock.calls.GitProtocol, callInfo)
mock.lockGitProtocol.Unlock()
return mock.GitProtocolFunc(hostname)
}
// GitProtocolCalls gets all the calls that were made to GitProtocol.
// Check the length with:
//
// len(mockedConfig.GitProtocolCalls())
func (mock *ConfigMock) GitProtocolCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockGitProtocol.RLock()
calls = mock.calls.GitProtocol
mock.lockGitProtocol.RUnlock()
return calls
}
// HTTPUnixSocket calls HTTPUnixSocketFunc.
func (mock *ConfigMock) HTTPUnixSocket(hostname string) gh.ConfigEntry {
if mock.HTTPUnixSocketFunc == nil {
panic("ConfigMock.HTTPUnixSocketFunc: method is nil but Config.HTTPUnixSocket was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockHTTPUnixSocket.Lock()
mock.calls.HTTPUnixSocket = append(mock.calls.HTTPUnixSocket, callInfo)
mock.lockHTTPUnixSocket.Unlock()
return mock.HTTPUnixSocketFunc(hostname)
}
// HTTPUnixSocketCalls gets all the calls that were made to HTTPUnixSocket.
// Check the length with:
//
// len(mockedConfig.HTTPUnixSocketCalls())
func (mock *ConfigMock) HTTPUnixSocketCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockHTTPUnixSocket.RLock()
calls = mock.calls.HTTPUnixSocket
mock.lockHTTPUnixSocket.RUnlock()
return calls
}
// Migrate calls MigrateFunc.
func (mock *ConfigMock) Migrate(migration gh.Migration) error {
if mock.MigrateFunc == nil {
panic("ConfigMock.MigrateFunc: method is nil but Config.Migrate was just called")
}
callInfo := struct {
Migration gh.Migration
}{
Migration: migration,
}
mock.lockMigrate.Lock()
mock.calls.Migrate = append(mock.calls.Migrate, callInfo)
mock.lockMigrate.Unlock()
return mock.MigrateFunc(migration)
}
// MigrateCalls gets all the calls that were made to Migrate.
// Check the length with:
//
// len(mockedConfig.MigrateCalls())
func (mock *ConfigMock) MigrateCalls() []struct {
Migration gh.Migration
} {
var calls []struct {
Migration gh.Migration
}
mock.lockMigrate.RLock()
calls = mock.calls.Migrate
mock.lockMigrate.RUnlock()
return calls
}
// Pager calls PagerFunc.
func (mock *ConfigMock) Pager(hostname string) gh.ConfigEntry {
if mock.PagerFunc == nil {
panic("ConfigMock.PagerFunc: method is nil but Config.Pager was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockPager.Lock()
mock.calls.Pager = append(mock.calls.Pager, callInfo)
mock.lockPager.Unlock()
return mock.PagerFunc(hostname)
}
// PagerCalls gets all the calls that were made to Pager.
// Check the length with:
//
// len(mockedConfig.PagerCalls())
func (mock *ConfigMock) PagerCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockPager.RLock()
calls = mock.calls.Pager
mock.lockPager.RUnlock()
return calls
}
// PreferEditorPrompt calls PreferEditorPromptFunc.
func (mock *ConfigMock) PreferEditorPrompt(hostname string) gh.ConfigEntry {
if mock.PreferEditorPromptFunc == nil {
panic("ConfigMock.PreferEditorPromptFunc: method is nil but Config.PreferEditorPrompt was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockPreferEditorPrompt.Lock()
mock.calls.PreferEditorPrompt = append(mock.calls.PreferEditorPrompt, callInfo)
mock.lockPreferEditorPrompt.Unlock()
return mock.PreferEditorPromptFunc(hostname)
}
// PreferEditorPromptCalls gets all the calls that were made to PreferEditorPrompt.
// Check the length with:
//
// len(mockedConfig.PreferEditorPromptCalls())
func (mock *ConfigMock) PreferEditorPromptCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockPreferEditorPrompt.RLock()
calls = mock.calls.PreferEditorPrompt
mock.lockPreferEditorPrompt.RUnlock()
return calls
}
// Prompt calls PromptFunc.
func (mock *ConfigMock) Prompt(hostname string) gh.ConfigEntry {
if mock.PromptFunc == nil {
panic("ConfigMock.PromptFunc: method is nil but Config.Prompt was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockPrompt.Lock()
mock.calls.Prompt = append(mock.calls.Prompt, callInfo)
mock.lockPrompt.Unlock()
return mock.PromptFunc(hostname)
}
// PromptCalls gets all the calls that were made to Prompt.
// Check the length with:
//
// len(mockedConfig.PromptCalls())
func (mock *ConfigMock) PromptCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockPrompt.RLock()
calls = mock.calls.Prompt
mock.lockPrompt.RUnlock()
return calls
}
// Set calls SetFunc.
func (mock *ConfigMock) Set(hostname string, key string, value string) {
if mock.SetFunc == nil {
panic("ConfigMock.SetFunc: method is nil but Config.Set was just called")
}
callInfo := struct {
Hostname string
Key string
Value string
}{
Hostname: hostname,
Key: key,
Value: value,
}
mock.lockSet.Lock()
mock.calls.Set = append(mock.calls.Set, callInfo)
mock.lockSet.Unlock()
mock.SetFunc(hostname, key, value)
}
// SetCalls gets all the calls that were made to Set.
// Check the length with:
//
// len(mockedConfig.SetCalls())
func (mock *ConfigMock) SetCalls() []struct {
Hostname string
Key string
Value string
} {
var calls []struct {
Hostname string
Key string
Value string
}
mock.lockSet.RLock()
calls = mock.calls.Set
mock.lockSet.RUnlock()
return calls
}
// Spinner calls SpinnerFunc.
func (mock *ConfigMock) Spinner(hostname string) gh.ConfigEntry {
if mock.SpinnerFunc == nil {
panic("ConfigMock.SpinnerFunc: method is nil but Config.Spinner was just called")
}
callInfo := struct {
Hostname string
}{
Hostname: hostname,
}
mock.lockSpinner.Lock()
mock.calls.Spinner = append(mock.calls.Spinner, callInfo)
mock.lockSpinner.Unlock()
return mock.SpinnerFunc(hostname)
}
// SpinnerCalls gets all the calls that were made to Spinner.
// Check the length with:
//
// len(mockedConfig.SpinnerCalls())
func (mock *ConfigMock) SpinnerCalls() []struct {
Hostname string
} {
var calls []struct {
Hostname string
}
mock.lockSpinner.RLock()
calls = mock.calls.Spinner
mock.lockSpinner.RUnlock()
return calls
}
// Version calls VersionFunc.
func (mock *ConfigMock) Version() o.Option[string] {
if mock.VersionFunc == nil {
panic("ConfigMock.VersionFunc: method is nil but Config.Version was just called")
}
callInfo := struct {
}{}
mock.lockVersion.Lock()
mock.calls.Version = append(mock.calls.Version, callInfo)
mock.lockVersion.Unlock()
return mock.VersionFunc()
}
// VersionCalls gets all the calls that were made to Version.
// Check the length with:
//
// len(mockedConfig.VersionCalls())
func (mock *ConfigMock) VersionCalls() []struct {
} {
var calls []struct {
}
mock.lockVersion.RLock()
calls = mock.calls.Version
mock.lockVersion.RUnlock()
return calls
}
// Write calls WriteFunc.
func (mock *ConfigMock) Write() error {
if mock.WriteFunc == nil {
panic("ConfigMock.WriteFunc: method is nil but Config.Write was just called")
}
callInfo := struct {
}{}
mock.lockWrite.Lock()
mock.calls.Write = append(mock.calls.Write, callInfo)
mock.lockWrite.Unlock()
return mock.WriteFunc()
}
// WriteCalls gets all the calls that were made to Write.
// Check the length with:
//
// len(mockedConfig.WriteCalls())
func (mock *ConfigMock) WriteCalls() []struct {
} {
var calls []struct {
}
mock.lockWrite.RLock()
calls = mock.calls.Write
mock.lockWrite.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/gh/mock/migration.go | internal/gh/mock/migration.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package ghmock
import (
"github.com/cli/cli/v2/internal/gh"
ghConfig "github.com/cli/go-gh/v2/pkg/config"
"sync"
)
// Ensure, that MigrationMock does implement gh.Migration.
// If this is not the case, regenerate this file with moq.
var _ gh.Migration = &MigrationMock{}
// MigrationMock is a mock implementation of gh.Migration.
//
// func TestSomethingThatUsesMigration(t *testing.T) {
//
// // make and configure a mocked gh.Migration
// mockedMigration := &MigrationMock{
// DoFunc: func(config *ghConfig.Config) error {
// panic("mock out the Do method")
// },
// PostVersionFunc: func() string {
// panic("mock out the PostVersion method")
// },
// PreVersionFunc: func() string {
// panic("mock out the PreVersion method")
// },
// }
//
// // use mockedMigration in code that requires gh.Migration
// // and then make assertions.
//
// }
type MigrationMock struct {
// DoFunc mocks the Do method.
DoFunc func(config *ghConfig.Config) error
// PostVersionFunc mocks the PostVersion method.
PostVersionFunc func() string
// PreVersionFunc mocks the PreVersion method.
PreVersionFunc func() string
// calls tracks calls to the methods.
calls struct {
// Do holds details about calls to the Do method.
Do []struct {
// Config is the config argument value.
Config *ghConfig.Config
}
// PostVersion holds details about calls to the PostVersion method.
PostVersion []struct {
}
// PreVersion holds details about calls to the PreVersion method.
PreVersion []struct {
}
}
lockDo sync.RWMutex
lockPostVersion sync.RWMutex
lockPreVersion sync.RWMutex
}
// Do calls DoFunc.
func (mock *MigrationMock) Do(config *ghConfig.Config) error {
if mock.DoFunc == nil {
panic("MigrationMock.DoFunc: method is nil but Migration.Do was just called")
}
callInfo := struct {
Config *ghConfig.Config
}{
Config: config,
}
mock.lockDo.Lock()
mock.calls.Do = append(mock.calls.Do, callInfo)
mock.lockDo.Unlock()
return mock.DoFunc(config)
}
// DoCalls gets all the calls that were made to Do.
// Check the length with:
//
// len(mockedMigration.DoCalls())
func (mock *MigrationMock) DoCalls() []struct {
Config *ghConfig.Config
} {
var calls []struct {
Config *ghConfig.Config
}
mock.lockDo.RLock()
calls = mock.calls.Do
mock.lockDo.RUnlock()
return calls
}
// PostVersion calls PostVersionFunc.
func (mock *MigrationMock) PostVersion() string {
if mock.PostVersionFunc == nil {
panic("MigrationMock.PostVersionFunc: method is nil but Migration.PostVersion was just called")
}
callInfo := struct {
}{}
mock.lockPostVersion.Lock()
mock.calls.PostVersion = append(mock.calls.PostVersion, callInfo)
mock.lockPostVersion.Unlock()
return mock.PostVersionFunc()
}
// PostVersionCalls gets all the calls that were made to PostVersion.
// Check the length with:
//
// len(mockedMigration.PostVersionCalls())
func (mock *MigrationMock) PostVersionCalls() []struct {
} {
var calls []struct {
}
mock.lockPostVersion.RLock()
calls = mock.calls.PostVersion
mock.lockPostVersion.RUnlock()
return calls
}
// PreVersion calls PreVersionFunc.
func (mock *MigrationMock) PreVersion() string {
if mock.PreVersionFunc == nil {
panic("MigrationMock.PreVersionFunc: method is nil but Migration.PreVersion was just called")
}
callInfo := struct {
}{}
mock.lockPreVersion.Lock()
mock.calls.PreVersion = append(mock.calls.PreVersion, callInfo)
mock.lockPreVersion.Unlock()
return mock.PreVersionFunc()
}
// PreVersionCalls gets all the calls that were made to PreVersion.
// Check the length with:
//
// len(mockedMigration.PreVersionCalls())
func (mock *MigrationMock) PreVersionCalls() []struct {
} {
var calls []struct {
}
mock.lockPreVersion.RLock()
calls = mock.calls.PreVersion
mock.lockPreVersion.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/safepaths/absolute_test.go | internal/safepaths/absolute_test.go | package safepaths_test
import (
"fmt"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/cli/cli/v2/internal/safepaths"
"github.com/stretchr/testify/require"
)
func TestParseAbsolutePath(t *testing.T) {
t.Parallel()
absolutePath, err := safepaths.ParseAbsolute("/base")
require.NoError(t, err)
require.Equal(t, filepath.Join(rootDir(), "base"), absolutePath.String())
}
func TestAbsoluteEmptyPathStringPanic(t *testing.T) {
t.Parallel()
absolutePath := safepaths.Absolute{}
require.Panics(t, func() {
_ = absolutePath.String()
})
}
func TestJoin(t *testing.T) {
t.Parallel()
tests := []struct {
name string
base safepaths.Absolute
elems []string
want safepaths.Absolute
wantPathTraversalError bool
}{
{
name: "child of base",
base: mustParseAbsolute("/base"),
elems: []string{"child"},
want: mustParseAbsolute("/base/child"),
},
{
name: "grandchild of base",
base: mustParseAbsolute("/base"),
elems: []string{"child", "grandchild"},
want: mustParseAbsolute("/base/child/grandchild"),
},
{
name: "relative parent of base",
base: mustParseAbsolute("/base"),
elems: []string{".."},
wantPathTraversalError: true,
},
{
name: "relative grandparent of base",
base: mustParseAbsolute("/base"),
elems: []string{"..", ".."},
wantPathTraversalError: true,
},
{
name: "relative current dir",
base: mustParseAbsolute("/base"),
elems: []string{"."},
want: mustParseAbsolute("/base"),
},
{
name: "subpath via relative parent",
base: mustParseAbsolute("/child"),
elems: []string{"..", "child"},
want: mustParseAbsolute("/child"),
},
{
name: "empty string",
base: mustParseAbsolute("/base"),
elems: []string{""},
want: mustParseAbsolute("/base"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
joinedPath, err := tt.base.Join(tt.elems...)
if tt.wantPathTraversalError {
var pathTraversalError safepaths.PathTraversalError
require.ErrorAs(t, err, &pathTraversalError)
require.Equal(t, tt.base, pathTraversalError.Base)
require.Equal(t, tt.elems, pathTraversalError.Elems)
return
}
require.NoError(t, err)
require.Equal(t, tt.want, joinedPath)
})
}
}
func TestPathTraversalErrorMessage(t *testing.T) {
t.Parallel()
pathTraversalError := safepaths.PathTraversalError{
Base: mustParseAbsolute("/base"),
Elems: []string{".."},
}
expectedMsg := fmt.Sprintf("joining %s and %s would be a traversal", filepath.Join(rootDir(), "base"), "..")
require.EqualError(t, pathTraversalError, expectedMsg)
}
func mustParseAbsolute(s string) safepaths.Absolute {
t, err := safepaths.ParseAbsolute(s)
if err != nil {
panic(err)
}
return t
}
func rootDir() string {
// Get the current working directory
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
// For Windows, extract the volume and add back the root
if runtime.GOOS == "windows" {
volume := filepath.VolumeName(cwd)
return volume + "\\"
}
// For Unix-based systems, the root is always "/"
return "/"
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/safepaths/absolute.go | internal/safepaths/absolute.go | package safepaths
import (
"fmt"
"path/filepath"
"strings"
)
// Absolute must be constructed via ParseAbsolute, or other methods in this package.
// The zero value of Absolute will panic when String is called.
type Absolute struct {
path string
}
// ParseAbsolute takes a string path that may be relative and returns
// an Absolute that is guaranteed to be absolute, or an error.
func ParseAbsolute(path string) (Absolute, error) {
path, err := filepath.Abs(path)
if err != nil {
return Absolute{}, fmt.Errorf("failed to get absolute path: %w", err)
}
return Absolute{path: path}, nil
}
// String returns a string representation of the absolute path, or panics
// if the absolute path is empty. This guards against programmer error.
func (a Absolute) String() string {
if a.path == "" {
panic("empty absolute path")
}
return a.path
}
// Join an absolute path with elements to create a new Absolute path, or error.
// A PathTraversalError will be returned if the joined path would traverse outside of
// the base Absolute path. Note that this does not handle symlinks.
func (a Absolute) Join(elem ...string) (Absolute, error) {
joinedAbsolutePath, err := ParseAbsolute(filepath.Join(append([]string{a.path}, elem...)...))
if err != nil {
return Absolute{}, fmt.Errorf("failed to parse joined path: %w", err)
}
isSubpath, err := joinedAbsolutePath.isSubpathOf(a)
if err != nil {
return Absolute{}, err
}
if !isSubpath {
return Absolute{}, PathTraversalError{
Base: a,
Elems: elem,
}
}
return joinedAbsolutePath, nil
}
func (a Absolute) isSubpathOf(dir Absolute) (bool, error) {
relativePath, err := filepath.Rel(dir.path, a.path)
if err != nil {
return false, err
}
return !strings.HasPrefix(relativePath, ".."), nil
}
type PathTraversalError struct {
Base Absolute
Elems []string
}
func (e PathTraversalError) Error() string {
return fmt.Sprintf("joining %s and %s would be a traversal", e.Base, filepath.Join(e.Elems...))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghcmd/update_disabled.go | internal/ghcmd/update_disabled.go | //go:build !updateable
package ghcmd
// See update_enabled.go comment for more information.
var updaterEnabled = ""
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghcmd/cmd_test.go | internal/ghcmd/cmd_test.go | package ghcmd
import (
"bytes"
"errors"
"fmt"
"net"
"testing"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func Test_printError(t *testing.T) {
cmd := &cobra.Command{}
type args struct {
err error
cmd *cobra.Command
debug bool
}
tests := []struct {
name string
args args
wantOut string
}{
{
name: "generic error",
args: args{
err: errors.New("the app exploded"),
cmd: nil,
debug: false,
},
wantOut: "the app exploded\n",
},
{
name: "DNS error",
args: args{
err: fmt.Errorf("DNS oopsie: %w", &net.DNSError{
Name: "api.github.com",
}),
cmd: nil,
debug: false,
},
wantOut: `error connecting to api.github.com
check your internet connection or https://githubstatus.com
`,
},
{
name: "Cobra flag error",
args: args{
err: cmdutil.FlagErrorf("unknown flag --foo"),
cmd: cmd,
debug: false,
},
wantOut: "unknown flag --foo\n\nUsage:\n\n",
},
{
name: "unknown Cobra command error",
args: args{
err: errors.New("unknown command foo"),
cmd: cmd,
debug: false,
},
wantOut: "unknown command foo\n\nUsage:\n\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out := &bytes.Buffer{}
printError(out, tt.args.err, tt.args.cmd, tt.args.debug)
if gotOut := out.String(); gotOut != tt.wantOut {
t.Errorf("printError() = %q, want %q", gotOut, tt.wantOut)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghcmd/update_enabled.go | internal/ghcmd/update_enabled.go | //go:build updateable
package ghcmd
// `updateable` is a build tag set in the gh formula within homebrew/homebrew-core
// and is used to control whether users are notified of newer GitHub CLI releases.
//
// Currently, updaterEnabled needs to be set to 'cli/cli' as it affects where
// update.CheckForUpdate() checks for releases. It is unclear to what extent
// this updaterEnabled is being used by unofficial forks or builds, so we decided
// to leave it available for injection as a string variable for now.
//
// Development builds do not generate update messages by default.
//
// For more information, see:
// - the Homebrew formula for gh: <https://github.com/Homebrew/homebrew-core/blob/master/Formula/g/gh.rb>.
// - a discussion about adding this build tag: <https://github.com/cli/cli/pull/11024#discussion_r2107597618>.
var updaterEnabled = "cli/cli"
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghcmd/cmd.go | internal/ghcmd/cmd.go | package ghcmd
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
surveyCore "github.com/AlecAivazis/survey/v2/core"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/build"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/config/migration"
"github.com/cli/cli/v2/internal/update"
"github.com/cli/cli/v2/pkg/cmd/factory"
"github.com/cli/cli/v2/pkg/cmd/root"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/utils"
"github.com/cli/safeexec"
"github.com/mgutz/ansi"
"github.com/spf13/cobra"
)
type exitCode int
const (
exitOK exitCode = 0
exitError exitCode = 1
exitCancel exitCode = 2
exitAuth exitCode = 4
exitPending exitCode = 8
)
func Main() exitCode {
buildDate := build.Date
buildVersion := build.Version
hasDebug, _ := utils.IsDebugEnabled()
cmdFactory := factory.New(buildVersion)
stderr := cmdFactory.IOStreams.ErrOut
ctx := context.Background()
if cfg, err := cmdFactory.Config(); err == nil {
var m migration.MultiAccount
if err := cfg.Migrate(m); err != nil {
fmt.Fprintln(stderr, err)
return exitError
}
}
updateCtx, updateCancel := context.WithCancel(ctx)
defer updateCancel()
updateMessageChan := make(chan *update.ReleaseInfo)
go func() {
rel, err := checkForUpdate(updateCtx, cmdFactory, buildVersion)
if err != nil && hasDebug {
fmt.Fprintf(stderr, "warning: checking for update failed: %v", err)
}
updateMessageChan <- rel
}()
if !cmdFactory.IOStreams.ColorEnabled() {
surveyCore.DisableColor = true
ansi.DisableColors(true)
} else {
// override survey's poor choice of color
surveyCore.TemplateFuncsWithColor["color"] = func(style string) string {
switch style {
case "white":
return ansi.ColorCode("default")
default:
return ansi.ColorCode(style)
}
}
}
// Enable running gh from Windows File Explorer's address bar. Without this, the user is told to stop and run from a
// terminal. With this, a user can clone a repo (or take other actions) directly from explorer.
if len(os.Args) > 1 && os.Args[1] != "" {
cobra.MousetrapHelpText = ""
}
rootCmd, err := root.NewCmdRoot(cmdFactory, buildVersion, buildDate)
if err != nil {
fmt.Fprintf(stderr, "failed to create root command: %s\n", err)
return exitError
}
expandedArgs := []string{}
if len(os.Args) > 0 {
expandedArgs = os.Args[1:]
}
// translate `gh help <command>` to `gh <command> --help` for extensions.
if len(expandedArgs) >= 2 && expandedArgs[0] == "help" && isExtensionCommand(rootCmd, expandedArgs[1:]) {
expandedArgs = expandedArgs[1:]
expandedArgs = append(expandedArgs, "--help")
}
rootCmd.SetArgs(expandedArgs)
if cmd, err := rootCmd.ExecuteContextC(ctx); err != nil {
var pagerPipeError *iostreams.ErrClosedPagerPipe
var noResultsError cmdutil.NoResultsError
var extError *root.ExternalCommandExitError
var authError *root.AuthError
if err == cmdutil.SilentError {
return exitError
} else if err == cmdutil.PendingError {
return exitPending
} else if cmdutil.IsUserCancellation(err) {
if errors.Is(err, terminal.InterruptErr) {
// ensure the next shell prompt will start on its own line
fmt.Fprint(stderr, "\n")
}
return exitCancel
} else if errors.As(err, &authError) {
return exitAuth
} else if errors.As(err, &pagerPipeError) {
// ignore the error raised when piping to a closed pager
return exitOK
} else if errors.As(err, &noResultsError) {
if cmdFactory.IOStreams.IsStdoutTTY() {
fmt.Fprintln(stderr, noResultsError.Error())
}
// no results is not a command failure
return exitOK
} else if errors.As(err, &extError) {
// pass on exit codes from extensions and shell aliases
return exitCode(extError.ExitCode())
}
printError(stderr, err, cmd, hasDebug)
if strings.Contains(err.Error(), "Incorrect function") {
fmt.Fprintln(stderr, "You appear to be running in MinTTY without pseudo terminal support.")
fmt.Fprintln(stderr, "To learn about workarounds for this error, run: gh help mintty")
return exitError
}
var httpErr api.HTTPError
if errors.As(err, &httpErr) && httpErr.StatusCode == 401 {
fmt.Fprintln(stderr, "Try authenticating with: gh auth login")
} else if u := factory.SSOURL(); u != "" {
// handles organization SAML enforcement error
fmt.Fprintf(stderr, "Authorize in your web browser: %s\n", u)
} else if msg := httpErr.ScopesSuggestion(); msg != "" {
fmt.Fprintln(stderr, msg)
}
return exitError
}
if root.HasFailed() {
return exitError
}
updateCancel() // if the update checker hasn't completed by now, abort it
newRelease := <-updateMessageChan
if newRelease != nil {
isHomebrew := isUnderHomebrew(cmdFactory.Executable())
if isHomebrew && isRecentRelease(newRelease.PublishedAt) {
// do not notify Homebrew users before the version bump had a chance to get merged into homebrew-core
return exitOK
}
fmt.Fprintf(stderr, "\n\n%s %s → %s\n",
ansi.Color("A new release of gh is available:", "yellow"),
ansi.Color(strings.TrimPrefix(buildVersion, "v"), "cyan"),
ansi.Color(strings.TrimPrefix(newRelease.Version, "v"), "cyan"))
if isHomebrew {
fmt.Fprintf(stderr, "To upgrade, run: %s\n", "brew upgrade gh")
}
fmt.Fprintf(stderr, "%s\n\n",
ansi.Color(newRelease.URL, "yellow"))
}
return exitOK
}
// isExtensionCommand returns true if args resolve to an extension command.
func isExtensionCommand(rootCmd *cobra.Command, args []string) bool {
c, _, err := rootCmd.Find(args)
return err == nil && c != nil && c.GroupID == "extension"
}
func printError(out io.Writer, err error, cmd *cobra.Command, debug bool) {
var dnsError *net.DNSError
if errors.As(err, &dnsError) {
fmt.Fprintf(out, "error connecting to %s\n", dnsError.Name)
if debug {
fmt.Fprintln(out, dnsError)
}
fmt.Fprintln(out, "check your internet connection or https://githubstatus.com")
return
}
fmt.Fprintln(out, err)
var flagError *cmdutil.FlagError
if errors.As(err, &flagError) || strings.HasPrefix(err.Error(), "unknown command ") {
if !strings.HasSuffix(err.Error(), "\n") {
fmt.Fprintln(out)
}
fmt.Fprintln(out, cmd.UsageString())
}
}
func checkForUpdate(ctx context.Context, f *cmdutil.Factory, currentVersion string) (*update.ReleaseInfo, error) {
if updaterEnabled == "" || !update.ShouldCheckForUpdate() {
return nil, nil
}
httpClient, err := f.HttpClient()
if err != nil {
return nil, err
}
stateFilePath := filepath.Join(config.StateDir(), "state.yml")
return update.CheckForUpdate(ctx, httpClient, stateFilePath, updaterEnabled, currentVersion)
}
func isRecentRelease(publishedAt time.Time) bool {
return !publishedAt.IsZero() && time.Since(publishedAt) < time.Hour*24
}
// Check whether the gh binary was found under the Homebrew prefix
func isUnderHomebrew(ghBinary string) bool {
brewExe, err := safeexec.LookPath("brew")
if err != nil {
return false
}
brewPrefixBytes, err := exec.Command(brewExe, "--prefix").Output()
if err != nil {
return false
}
brewBinPrefix := filepath.Join(strings.TrimSpace(string(brewPrefixBytes)), "bin") + string(filepath.Separator)
return strings.HasPrefix(ghBinary, brewBinPrefix)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/tableprinter/table_printer_test.go | internal/tableprinter/table_printer_test.go | package tableprinter_test
import (
"testing"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/require"
)
func TestHeadersAreNotMutated(t *testing.T) {
// Given a TTY environment so that headers are included in the table
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(true)
// When creating a new table printer
headers := []string{"one", "two", "three"}
_ = tableprinter.New(ios, tableprinter.WithHeader(headers...))
// The provided headers should not be mutated
require.Equal(t, []string{"one", "two", "three"}, headers)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/tableprinter/table_printer.go | internal/tableprinter/table_printer.go | package tableprinter
import (
"io"
"strings"
"time"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/go-gh/v2/pkg/tableprinter"
)
type TablePrinter struct {
tableprinter.TablePrinter
isTTY bool
cs *iostreams.ColorScheme
}
// IsTTY gets whether the TablePrinter will render to a terminal.
func (t *TablePrinter) IsTTY() bool {
return t.isTTY
}
// AddTimeField in TTY mode displays the fuzzy time difference between now and t.
// In non-TTY mode it just displays t with the time.RFC3339 format.
func (tp *TablePrinter) AddTimeField(now, t time.Time, c func(string) string) {
var tf string
if tp.isTTY {
tf = text.FuzzyAgo(now, t)
} else {
tf = t.Format(time.RFC3339)
}
tp.AddField(tf, WithColor(c))
}
var (
WithColor = tableprinter.WithColor
WithPadding = tableprinter.WithPadding
WithTruncate = tableprinter.WithTruncate
)
type headerOption struct {
columns []string
}
// New creates a TablePrinter from an IOStreams.
func New(ios *iostreams.IOStreams, headers headerOption) *TablePrinter {
maxWidth := 80
isTTY := ios.IsStdoutTTY()
if isTTY {
maxWidth = ios.TerminalWidth()
}
return NewWithWriter(ios.Out, isTTY, maxWidth, ios.ColorScheme(), headers)
}
// NewWithWriter creates a TablePrinter from a Writer, whether the output is a terminal, the terminal width, and more.
func NewWithWriter(w io.Writer, isTTY bool, maxWidth int, cs *iostreams.ColorScheme, headers headerOption) *TablePrinter {
tp := &TablePrinter{
TablePrinter: tableprinter.New(w, isTTY, maxWidth),
isTTY: isTTY,
cs: cs,
}
if isTTY && len(headers.columns) > 0 {
// Make sure all headers are uppercase, taking a copy of the headers to avoid modifying the original slice.
upperCasedHeaders := make([]string, len(headers.columns))
for i := range headers.columns {
upperCasedHeaders[i] = strings.ToUpper(headers.columns[i])
}
// Make sure all header columns are padded - even the last one. Previously, the last header column
// was not padded. In tests cs.Enabled() is false which allows us to avoid having to fix up
// numerous tests that verify header padding.
var paddingFunc func(int, string) string
if cs.Enabled {
paddingFunc = text.PadRight
}
tp.AddHeader(
upperCasedHeaders,
WithPadding(paddingFunc),
WithColor(cs.TableHeader),
)
}
return tp
}
// WithHeader defines the column names for a table.
// Panics if columns is nil or empty.
func WithHeader(columns ...string) headerOption {
if len(columns) == 0 {
panic("must define header columns")
}
return headerOption{columns}
}
// NoHeader disable printing or checking for a table header.
//
// Deprecated: use WithHeader unless required otherwise.
var NoHeader = headerOption{}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/keyring/keyring.go | internal/keyring/keyring.go | // Package keyring is a simple wrapper that adds timeouts to the zalando/go-keyring package.
package keyring
import (
"errors"
"time"
"github.com/zalando/go-keyring"
)
var ErrNotFound = errors.New("secret not found in keyring")
type TimeoutError struct {
message string
}
func (e *TimeoutError) Error() string {
return e.message
}
// Set secret in keyring for user.
func Set(service, user, secret string) error {
ch := make(chan error, 1)
go func() {
defer close(ch)
ch <- keyring.Set(service, user, secret)
}()
select {
case err := <-ch:
return err
case <-time.After(3 * time.Second):
return &TimeoutError{"timeout while trying to set secret in keyring"}
}
}
// Get secret from keyring given service and user name.
func Get(service, user string) (string, error) {
ch := make(chan struct {
val string
err error
}, 1)
go func() {
defer close(ch)
val, err := keyring.Get(service, user)
ch <- struct {
val string
err error
}{val, err}
}()
select {
case res := <-ch:
if errors.Is(res.err, keyring.ErrNotFound) {
return "", ErrNotFound
}
return res.val, res.err
case <-time.After(3 * time.Second):
return "", &TimeoutError{"timeout while trying to get secret from keyring"}
}
}
// Delete secret from keyring.
func Delete(service, user string) error {
ch := make(chan error, 1)
go func() {
defer close(ch)
ch <- keyring.Delete(service, user)
}()
select {
case err := <-ch:
return err
case <-time.After(3 * time.Second):
return &TimeoutError{"timeout while trying to delete secret from keyring"}
}
}
func MockInit() {
keyring.MockInit()
}
func MockInitWithError(err error) {
keyring.MockInitWithError(err)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/prompter/prompter_mock.go | internal/prompter/prompter_mock.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package prompter
import (
"sync"
)
// Ensure, that PrompterMock does implement Prompter.
// If this is not the case, regenerate this file with moq.
var _ Prompter = &PrompterMock{}
// PrompterMock is a mock implementation of Prompter.
//
// func TestSomethingThatUsesPrompter(t *testing.T) {
//
// // make and configure a mocked Prompter
// mockedPrompter := &PrompterMock{
// AuthTokenFunc: func() (string, error) {
// panic("mock out the AuthToken method")
// },
// ConfirmFunc: func(prompt string, defaultValue bool) (bool, error) {
// panic("mock out the Confirm method")
// },
// ConfirmDeletionFunc: func(requiredValue string) error {
// panic("mock out the ConfirmDeletion method")
// },
// InputFunc: func(prompt string, defaultValue string) (string, error) {
// panic("mock out the Input method")
// },
// InputHostnameFunc: func() (string, error) {
// panic("mock out the InputHostname method")
// },
// MarkdownEditorFunc: func(prompt string, defaultValue string, blankAllowed bool) (string, error) {
// panic("mock out the MarkdownEditor method")
// },
// MultiSelectFunc: func(prompt string, defaults []string, options []string) ([]int, error) {
// panic("mock out the MultiSelect method")
// },
// PasswordFunc: func(prompt string) (string, error) {
// panic("mock out the Password method")
// },
// SelectFunc: func(prompt string, defaultValue string, options []string) (int, error) {
// panic("mock out the Select method")
// },
// }
//
// // use mockedPrompter in code that requires Prompter
// // and then make assertions.
//
// }
type PrompterMock struct {
// AuthTokenFunc mocks the AuthToken method.
AuthTokenFunc func() (string, error)
// ConfirmFunc mocks the Confirm method.
ConfirmFunc func(prompt string, defaultValue bool) (bool, error)
// ConfirmDeletionFunc mocks the ConfirmDeletion method.
ConfirmDeletionFunc func(requiredValue string) error
// InputFunc mocks the Input method.
InputFunc func(prompt string, defaultValue string) (string, error)
// InputHostnameFunc mocks the InputHostname method.
InputHostnameFunc func() (string, error)
// MarkdownEditorFunc mocks the MarkdownEditor method.
MarkdownEditorFunc func(prompt string, defaultValue string, blankAllowed bool) (string, error)
// MultiSelectFunc mocks the MultiSelect method.
MultiSelectFunc func(prompt string, defaults []string, options []string) ([]int, error)
// PasswordFunc mocks the Password method.
PasswordFunc func(prompt string) (string, error)
// SelectFunc mocks the Select method.
SelectFunc func(prompt string, defaultValue string, options []string) (int, error)
// calls tracks calls to the methods.
calls struct {
// AuthToken holds details about calls to the AuthToken method.
AuthToken []struct {
}
// Confirm holds details about calls to the Confirm method.
Confirm []struct {
// Prompt is the prompt argument value.
Prompt string
// DefaultValue is the defaultValue argument value.
DefaultValue bool
}
// ConfirmDeletion holds details about calls to the ConfirmDeletion method.
ConfirmDeletion []struct {
// RequiredValue is the requiredValue argument value.
RequiredValue string
}
// Input holds details about calls to the Input method.
Input []struct {
// Prompt is the prompt argument value.
Prompt string
// DefaultValue is the defaultValue argument value.
DefaultValue string
}
// InputHostname holds details about calls to the InputHostname method.
InputHostname []struct {
}
// MarkdownEditor holds details about calls to the MarkdownEditor method.
MarkdownEditor []struct {
// Prompt is the prompt argument value.
Prompt string
// DefaultValue is the defaultValue argument value.
DefaultValue string
// BlankAllowed is the blankAllowed argument value.
BlankAllowed bool
}
// MultiSelect holds details about calls to the MultiSelect method.
MultiSelect []struct {
// Prompt is the prompt argument value.
Prompt string
// Defaults is the defaults argument value.
Defaults []string
// Options is the options argument value.
Options []string
}
// Password holds details about calls to the Password method.
Password []struct {
// Prompt is the prompt argument value.
Prompt string
}
// Select holds details about calls to the Select method.
Select []struct {
// Prompt is the prompt argument value.
Prompt string
// DefaultValue is the defaultValue argument value.
DefaultValue string
// Options is the options argument value.
Options []string
}
}
lockAuthToken sync.RWMutex
lockConfirm sync.RWMutex
lockConfirmDeletion sync.RWMutex
lockInput sync.RWMutex
lockInputHostname sync.RWMutex
lockMarkdownEditor sync.RWMutex
lockMultiSelect sync.RWMutex
lockPassword sync.RWMutex
lockSelect sync.RWMutex
}
// AuthToken calls AuthTokenFunc.
func (mock *PrompterMock) AuthToken() (string, error) {
if mock.AuthTokenFunc == nil {
panic("PrompterMock.AuthTokenFunc: method is nil but Prompter.AuthToken was just called")
}
callInfo := struct {
}{}
mock.lockAuthToken.Lock()
mock.calls.AuthToken = append(mock.calls.AuthToken, callInfo)
mock.lockAuthToken.Unlock()
return mock.AuthTokenFunc()
}
// AuthTokenCalls gets all the calls that were made to AuthToken.
// Check the length with:
//
// len(mockedPrompter.AuthTokenCalls())
func (mock *PrompterMock) AuthTokenCalls() []struct {
} {
var calls []struct {
}
mock.lockAuthToken.RLock()
calls = mock.calls.AuthToken
mock.lockAuthToken.RUnlock()
return calls
}
// Confirm calls ConfirmFunc.
func (mock *PrompterMock) Confirm(prompt string, defaultValue bool) (bool, error) {
if mock.ConfirmFunc == nil {
panic("PrompterMock.ConfirmFunc: method is nil but Prompter.Confirm was just called")
}
callInfo := struct {
Prompt string
DefaultValue bool
}{
Prompt: prompt,
DefaultValue: defaultValue,
}
mock.lockConfirm.Lock()
mock.calls.Confirm = append(mock.calls.Confirm, callInfo)
mock.lockConfirm.Unlock()
return mock.ConfirmFunc(prompt, defaultValue)
}
// ConfirmCalls gets all the calls that were made to Confirm.
// Check the length with:
//
// len(mockedPrompter.ConfirmCalls())
func (mock *PrompterMock) ConfirmCalls() []struct {
Prompt string
DefaultValue bool
} {
var calls []struct {
Prompt string
DefaultValue bool
}
mock.lockConfirm.RLock()
calls = mock.calls.Confirm
mock.lockConfirm.RUnlock()
return calls
}
// ConfirmDeletion calls ConfirmDeletionFunc.
func (mock *PrompterMock) ConfirmDeletion(requiredValue string) error {
if mock.ConfirmDeletionFunc == nil {
panic("PrompterMock.ConfirmDeletionFunc: method is nil but Prompter.ConfirmDeletion was just called")
}
callInfo := struct {
RequiredValue string
}{
RequiredValue: requiredValue,
}
mock.lockConfirmDeletion.Lock()
mock.calls.ConfirmDeletion = append(mock.calls.ConfirmDeletion, callInfo)
mock.lockConfirmDeletion.Unlock()
return mock.ConfirmDeletionFunc(requiredValue)
}
// ConfirmDeletionCalls gets all the calls that were made to ConfirmDeletion.
// Check the length with:
//
// len(mockedPrompter.ConfirmDeletionCalls())
func (mock *PrompterMock) ConfirmDeletionCalls() []struct {
RequiredValue string
} {
var calls []struct {
RequiredValue string
}
mock.lockConfirmDeletion.RLock()
calls = mock.calls.ConfirmDeletion
mock.lockConfirmDeletion.RUnlock()
return calls
}
// Input calls InputFunc.
func (mock *PrompterMock) Input(prompt string, defaultValue string) (string, error) {
if mock.InputFunc == nil {
panic("PrompterMock.InputFunc: method is nil but Prompter.Input was just called")
}
callInfo := struct {
Prompt string
DefaultValue string
}{
Prompt: prompt,
DefaultValue: defaultValue,
}
mock.lockInput.Lock()
mock.calls.Input = append(mock.calls.Input, callInfo)
mock.lockInput.Unlock()
return mock.InputFunc(prompt, defaultValue)
}
// InputCalls gets all the calls that were made to Input.
// Check the length with:
//
// len(mockedPrompter.InputCalls())
func (mock *PrompterMock) InputCalls() []struct {
Prompt string
DefaultValue string
} {
var calls []struct {
Prompt string
DefaultValue string
}
mock.lockInput.RLock()
calls = mock.calls.Input
mock.lockInput.RUnlock()
return calls
}
// InputHostname calls InputHostnameFunc.
func (mock *PrompterMock) InputHostname() (string, error) {
if mock.InputHostnameFunc == nil {
panic("PrompterMock.InputHostnameFunc: method is nil but Prompter.InputHostname was just called")
}
callInfo := struct {
}{}
mock.lockInputHostname.Lock()
mock.calls.InputHostname = append(mock.calls.InputHostname, callInfo)
mock.lockInputHostname.Unlock()
return mock.InputHostnameFunc()
}
// InputHostnameCalls gets all the calls that were made to InputHostname.
// Check the length with:
//
// len(mockedPrompter.InputHostnameCalls())
func (mock *PrompterMock) InputHostnameCalls() []struct {
} {
var calls []struct {
}
mock.lockInputHostname.RLock()
calls = mock.calls.InputHostname
mock.lockInputHostname.RUnlock()
return calls
}
// MarkdownEditor calls MarkdownEditorFunc.
func (mock *PrompterMock) MarkdownEditor(prompt string, defaultValue string, blankAllowed bool) (string, error) {
if mock.MarkdownEditorFunc == nil {
panic("PrompterMock.MarkdownEditorFunc: method is nil but Prompter.MarkdownEditor was just called")
}
callInfo := struct {
Prompt string
DefaultValue string
BlankAllowed bool
}{
Prompt: prompt,
DefaultValue: defaultValue,
BlankAllowed: blankAllowed,
}
mock.lockMarkdownEditor.Lock()
mock.calls.MarkdownEditor = append(mock.calls.MarkdownEditor, callInfo)
mock.lockMarkdownEditor.Unlock()
return mock.MarkdownEditorFunc(prompt, defaultValue, blankAllowed)
}
// MarkdownEditorCalls gets all the calls that were made to MarkdownEditor.
// Check the length with:
//
// len(mockedPrompter.MarkdownEditorCalls())
func (mock *PrompterMock) MarkdownEditorCalls() []struct {
Prompt string
DefaultValue string
BlankAllowed bool
} {
var calls []struct {
Prompt string
DefaultValue string
BlankAllowed bool
}
mock.lockMarkdownEditor.RLock()
calls = mock.calls.MarkdownEditor
mock.lockMarkdownEditor.RUnlock()
return calls
}
// MultiSelect calls MultiSelectFunc.
func (mock *PrompterMock) MultiSelect(prompt string, defaults []string, options []string) ([]int, error) {
if mock.MultiSelectFunc == nil {
panic("PrompterMock.MultiSelectFunc: method is nil but Prompter.MultiSelect was just called")
}
callInfo := struct {
Prompt string
Defaults []string
Options []string
}{
Prompt: prompt,
Defaults: defaults,
Options: options,
}
mock.lockMultiSelect.Lock()
mock.calls.MultiSelect = append(mock.calls.MultiSelect, callInfo)
mock.lockMultiSelect.Unlock()
return mock.MultiSelectFunc(prompt, defaults, options)
}
// MultiSelectCalls gets all the calls that were made to MultiSelect.
// Check the length with:
//
// len(mockedPrompter.MultiSelectCalls())
func (mock *PrompterMock) MultiSelectCalls() []struct {
Prompt string
Defaults []string
Options []string
} {
var calls []struct {
Prompt string
Defaults []string
Options []string
}
mock.lockMultiSelect.RLock()
calls = mock.calls.MultiSelect
mock.lockMultiSelect.RUnlock()
return calls
}
// Password calls PasswordFunc.
func (mock *PrompterMock) Password(prompt string) (string, error) {
if mock.PasswordFunc == nil {
panic("PrompterMock.PasswordFunc: method is nil but Prompter.Password was just called")
}
callInfo := struct {
Prompt string
}{
Prompt: prompt,
}
mock.lockPassword.Lock()
mock.calls.Password = append(mock.calls.Password, callInfo)
mock.lockPassword.Unlock()
return mock.PasswordFunc(prompt)
}
// PasswordCalls gets all the calls that were made to Password.
// Check the length with:
//
// len(mockedPrompter.PasswordCalls())
func (mock *PrompterMock) PasswordCalls() []struct {
Prompt string
} {
var calls []struct {
Prompt string
}
mock.lockPassword.RLock()
calls = mock.calls.Password
mock.lockPassword.RUnlock()
return calls
}
// Select calls SelectFunc.
func (mock *PrompterMock) Select(prompt string, defaultValue string, options []string) (int, error) {
if mock.SelectFunc == nil {
panic("PrompterMock.SelectFunc: method is nil but Prompter.Select was just called")
}
callInfo := struct {
Prompt string
DefaultValue string
Options []string
}{
Prompt: prompt,
DefaultValue: defaultValue,
Options: options,
}
mock.lockSelect.Lock()
mock.calls.Select = append(mock.calls.Select, callInfo)
mock.lockSelect.Unlock()
return mock.SelectFunc(prompt, defaultValue, options)
}
// SelectCalls gets all the calls that were made to Select.
// Check the length with:
//
// len(mockedPrompter.SelectCalls())
func (mock *PrompterMock) SelectCalls() []struct {
Prompt string
DefaultValue string
Options []string
} {
var calls []struct {
Prompt string
DefaultValue string
Options []string
}
mock.lockSelect.RLock()
calls = mock.calls.Select
mock.lockSelect.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/prompter/test.go | internal/prompter/test.go | package prompter
import (
"fmt"
"strings"
"testing"
ghPrompter "github.com/cli/go-gh/v2/pkg/prompter"
"github.com/stretchr/testify/assert"
)
func NewMockPrompter(t *testing.T) *MockPrompter {
m := &MockPrompter{
t: t,
PrompterMock: *ghPrompter.NewMock(t),
authTokenStubs: []authTokenStub{},
confirmDeletionStubs: []confirmDeletionStub{},
inputHostnameStubs: []inputHostnameStub{},
markdownEditorStubs: []markdownEditorStub{},
}
t.Cleanup(m.Verify)
return m
}
type MockPrompter struct {
t *testing.T
ghPrompter.PrompterMock
authTokenStubs []authTokenStub
confirmDeletionStubs []confirmDeletionStub
inputHostnameStubs []inputHostnameStub
markdownEditorStubs []markdownEditorStub
}
type authTokenStub struct {
fn func() (string, error)
}
type confirmDeletionStub struct {
prompt string
fn func(string) error
}
type inputHostnameStub struct {
fn func() (string, error)
}
type markdownEditorStub struct {
prompt string
fn func(string, string, bool) (string, error)
}
func (m *MockPrompter) AuthToken() (string, error) {
var s authTokenStub
if len(m.authTokenStubs) == 0 {
return "", NoSuchPromptErr("AuthToken")
}
s = m.authTokenStubs[0]
m.authTokenStubs = m.authTokenStubs[1:len(m.authTokenStubs)]
return s.fn()
}
func (m *MockPrompter) ConfirmDeletion(prompt string) error {
var s confirmDeletionStub
if len(m.confirmDeletionStubs) == 0 {
return NoSuchPromptErr("ConfirmDeletion")
}
s = m.confirmDeletionStubs[0]
m.confirmDeletionStubs = m.confirmDeletionStubs[1:len(m.confirmDeletionStubs)]
return s.fn(prompt)
}
func (m *MockPrompter) InputHostname() (string, error) {
var s inputHostnameStub
if len(m.inputHostnameStubs) == 0 {
return "", NoSuchPromptErr("InputHostname")
}
s = m.inputHostnameStubs[0]
m.inputHostnameStubs = m.inputHostnameStubs[1:len(m.inputHostnameStubs)]
return s.fn()
}
func (m *MockPrompter) MarkdownEditor(prompt, defaultValue string, blankAllowed bool) (string, error) {
var s markdownEditorStub
if len(m.markdownEditorStubs) == 0 {
return "", NoSuchPromptErr(prompt)
}
s = m.markdownEditorStubs[0]
m.markdownEditorStubs = m.markdownEditorStubs[1:len(m.markdownEditorStubs)]
if s.prompt != prompt {
return "", NoSuchPromptErr(prompt)
}
return s.fn(prompt, defaultValue, blankAllowed)
}
func (m *MockPrompter) RegisterAuthToken(stub func() (string, error)) {
m.authTokenStubs = append(m.authTokenStubs, authTokenStub{fn: stub})
}
func (m *MockPrompter) RegisterConfirmDeletion(prompt string, stub func(string) error) {
m.confirmDeletionStubs = append(m.confirmDeletionStubs, confirmDeletionStub{prompt: prompt, fn: stub})
}
func (m *MockPrompter) RegisterInputHostname(stub func() (string, error)) {
m.inputHostnameStubs = append(m.inputHostnameStubs, inputHostnameStub{fn: stub})
}
func (m *MockPrompter) RegisterMarkdownEditor(prompt string, stub func(string, string, bool) (string, error)) {
m.markdownEditorStubs = append(m.markdownEditorStubs, markdownEditorStub{prompt: prompt, fn: stub})
}
func (m *MockPrompter) Verify() {
errs := []string{}
if len(m.authTokenStubs) > 0 {
errs = append(errs, "AuthToken")
}
if len(m.confirmDeletionStubs) > 0 {
errs = append(errs, "ConfirmDeletion")
}
if len(m.inputHostnameStubs) > 0 {
errs = append(errs, "inputHostname")
}
if len(m.markdownEditorStubs) > 0 {
errs = append(errs, "markdownEditorStubs")
}
if len(errs) > 0 {
m.t.Helper()
m.t.Errorf("%d unmatched calls to %s", len(errs), strings.Join(errs, ","))
}
}
func AssertOptions(t *testing.T, expected, actual []string) {
assert.Equal(t, expected, actual)
}
func IndexFor(options []string, answer string) (int, error) {
for ix, a := range options {
if a == answer {
return ix, nil
}
}
return -1, NoSuchAnswerErr(answer, options)
}
func IndexesFor(options []string, answers ...string) ([]int, error) {
indexes := make([]int, len(answers))
for i, answer := range answers {
index, err := IndexFor(options, answer)
if err != nil {
return nil, err
}
indexes[i] = index
}
return indexes, nil
}
func NoSuchPromptErr(prompt string) error {
return fmt.Errorf("no such prompt '%s'", prompt)
}
func NoSuchAnswerErr(answer string, options []string) error {
return fmt.Errorf("no such answer '%s' in [%s]", answer, strings.Join(options, ", "))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/prompter/prompter.go | internal/prompter/prompter.go | package prompter
import (
"fmt"
"slices"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/charmbracelet/huh"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/surveyext"
ghPrompter "github.com/cli/go-gh/v2/pkg/prompter"
)
//go:generate moq -rm -out prompter_mock.go . Prompter
type Prompter interface {
// generic prompts from go-gh
// Select prompts the user to select an option from a list of options.
Select(prompt string, defaultValue string, options []string) (int, error)
// MultiSelect prompts the user to select one or more options from a list of options.
MultiSelect(prompt string, defaults []string, options []string) ([]int, error)
// Input prompts the user to enter a string value.
Input(prompt string, defaultValue string) (string, error)
// Password prompts the user to enter a password.
Password(prompt string) (string, error)
// Confirm prompts the user to confirm an action.
Confirm(prompt string, defaultValue bool) (bool, error)
// gh specific prompts
// AuthToken prompts the user to enter an authentication token.
AuthToken() (string, error)
// ConfirmDeletion prompts the user to confirm deletion of a resource by
// typing the requiredValue.
ConfirmDeletion(requiredValue string) error
// InputHostname prompts the user to enter a hostname.
InputHostname() (string, error)
// MarkdownEditor prompts the user to edit a markdown document in an editor.
// If blankAllowed is true, the user can skip the editor and an empty string
// will be returned.
MarkdownEditor(prompt string, defaultValue string, blankAllowed bool) (string, error)
}
func New(editorCmd string, io *iostreams.IOStreams) Prompter {
if io.AccessiblePrompterEnabled() {
return &accessiblePrompter{
stdin: io.In,
stdout: io.Out,
stderr: io.ErrOut,
editorCmd: editorCmd,
}
}
return &surveyPrompter{
prompter: ghPrompter.New(io.In, io.Out, io.ErrOut),
stdin: io.In,
stdout: io.Out,
stderr: io.ErrOut,
editorCmd: editorCmd,
}
}
type accessiblePrompter struct {
stdin ghPrompter.FileReader
stdout ghPrompter.FileWriter
stderr ghPrompter.FileWriter
editorCmd string
}
func (p *accessiblePrompter) newForm(groups ...*huh.Group) *huh.Form {
return huh.NewForm(groups...).
WithTheme(huh.ThemeBase16()).
WithAccessible(true).
WithInput(p.stdin).
WithOutput(p.stdout)
}
// addDefaultsToPrompt adds default values to the prompt string.
func (p *accessiblePrompter) addDefaultsToPrompt(prompt string, defaultValues []string) string {
// Removing empty defaults from the slice.
defaultValues = slices.DeleteFunc(defaultValues, func(s string) bool {
return s == ""
})
// Pluralizing the prompt if there are multiple default values.
if len(defaultValues) == 1 {
prompt = fmt.Sprintf("%s (default: %s)", prompt, defaultValues[0])
} else if len(defaultValues) > 1 {
prompt = fmt.Sprintf("%s (defaults: %s)", prompt, strings.Join(defaultValues, ", "))
}
// Zero-length defaultValues means return prompt unchanged.
return prompt
}
func (p *accessiblePrompter) Select(prompt, defaultValue string, options []string) (int, error) {
var result int
// Remove invalid default values from the defaults slice.
if !slices.Contains(options, defaultValue) {
defaultValue = ""
}
prompt = p.addDefaultsToPrompt(prompt, []string{defaultValue})
formOptions := []huh.Option[int]{}
for i, o := range options {
// If this option is the default value, assign its index
// to the result variable. huh will treat it as a default selection.
if defaultValue == o {
result = i
}
formOptions = append(formOptions, huh.NewOption(o, i))
}
form := p.newForm(
huh.NewGroup(
huh.NewSelect[int]().
Title(prompt).
Value(&result).
Options(formOptions...),
),
)
err := form.Run()
return result, err
}
func (p *accessiblePrompter) MultiSelect(prompt string, defaults []string, options []string) ([]int, error) {
var result []int
// Remove invalid default values from the defaults slice.
defaults = slices.DeleteFunc(defaults, func(s string) bool {
return !slices.Contains(options, s)
})
prompt = p.addDefaultsToPrompt(prompt, defaults)
formOptions := make([]huh.Option[int], len(options))
for i, o := range options {
// If this option is in the defaults slice,
// let's add its index to the result slice and huh
// will treat it as a default selection.
if slices.Contains(defaults, o) {
result = append(result, i)
}
formOptions[i] = huh.NewOption(o, i)
}
form := p.newForm(
huh.NewGroup(
huh.NewMultiSelect[int]().
Title(prompt).
Value(&result).
Limit(len(options)).
Options(formOptions...),
),
)
if err := form.Run(); err != nil {
return nil, err
}
return result, nil
}
func (p *accessiblePrompter) Input(prompt, defaultValue string) (string, error) {
result := defaultValue
prompt = p.addDefaultsToPrompt(prompt, []string{defaultValue})
form := p.newForm(
huh.NewGroup(
huh.NewInput().
Title(prompt).
Value(&result),
),
)
err := form.Run()
return result, err
}
func (p *accessiblePrompter) Password(prompt string) (string, error) {
var result string
// EchoModePassword is not used as password masking is unsupported in huh.
// EchoModeNone and EchoModePassword have the same effect of hiding user input.
form := p.newForm(
huh.NewGroup(
huh.NewInput().
EchoMode(huh.EchoModeNone).
Title(prompt).
Value(&result),
),
)
err := form.Run()
if err != nil {
return "", err
}
return result, nil
}
func (p *accessiblePrompter) Confirm(prompt string, defaultValue bool) (bool, error) {
result := defaultValue
if defaultValue {
prompt = p.addDefaultsToPrompt(prompt, []string{"yes"})
} else {
prompt = p.addDefaultsToPrompt(prompt, []string{"no"})
}
form := p.newForm(
huh.NewGroup(
huh.NewConfirm().
Title(prompt).
Value(&result),
),
)
if err := form.Run(); err != nil {
return false, err
}
return result, nil
}
func (p *accessiblePrompter) AuthToken() (string, error) {
var result string
// EchoModeNone and EchoModePassword both result in disabling echo mode
// as password masking is outside of VT100 spec.
form := p.newForm(
huh.NewGroup(
huh.NewInput().
EchoMode(huh.EchoModeNone).
Title("Paste your authentication token:").
// Note: if this validation fails, the prompt loops.
Validate(func(input string) error {
if input == "" {
return fmt.Errorf("token is required")
}
return nil
}).
Value(&result),
),
)
err := form.Run()
return result, err
}
func (p *accessiblePrompter) ConfirmDeletion(requiredValue string) error {
form := p.newForm(
huh.NewGroup(
huh.NewInput().
Title(fmt.Sprintf("Type %q to confirm deletion", requiredValue)).
Validate(func(input string) error {
if input != requiredValue {
return fmt.Errorf("You entered: %q", input)
}
return nil
}),
),
)
return form.Run()
}
func (p *accessiblePrompter) InputHostname() (string, error) {
var result string
form := p.newForm(
huh.NewGroup(
huh.NewInput().
Title("Hostname:").
Validate(ghinstance.HostnameValidator).
Value(&result),
),
)
err := form.Run()
if err != nil {
return "", err
}
return result, nil
}
func (p *accessiblePrompter) MarkdownEditor(prompt, defaultValue string, blankAllowed bool) (string, error) {
var result string
skipOption := "skip"
launchOption := "launch"
options := []huh.Option[string]{
huh.NewOption(fmt.Sprintf("Launch %s", surveyext.EditorName(p.editorCmd)), launchOption),
}
if blankAllowed {
options = append(options, huh.NewOption("Skip", skipOption))
}
form := p.newForm(
huh.NewGroup(
huh.NewSelect[string]().
Title(prompt).
Options(options...).
Value(&result),
),
)
if err := form.Run(); err != nil {
return "", err
}
if result == skipOption {
return "", nil
}
// launchOption was selected
text, err := surveyext.Edit(p.editorCmd, "*.md", defaultValue, p.stdin, p.stdout, p.stderr)
if err != nil {
return "", err
}
return text, nil
}
type surveyPrompter struct {
prompter *ghPrompter.Prompter
stdin ghPrompter.FileReader
stdout ghPrompter.FileWriter
stderr ghPrompter.FileWriter
editorCmd string
}
func (p *surveyPrompter) Select(prompt, defaultValue string, options []string) (int, error) {
return p.prompter.Select(prompt, defaultValue, options)
}
func (p *surveyPrompter) MultiSelect(prompt string, defaultValues, options []string) ([]int, error) {
return p.prompter.MultiSelect(prompt, defaultValues, options)
}
func (p *surveyPrompter) Input(prompt, defaultValue string) (string, error) {
return p.prompter.Input(prompt, defaultValue)
}
func (p *surveyPrompter) Password(prompt string) (string, error) {
return p.prompter.Password(prompt)
}
func (p *surveyPrompter) Confirm(prompt string, defaultValue bool) (bool, error) {
return p.prompter.Confirm(prompt, defaultValue)
}
func (p *surveyPrompter) AuthToken() (string, error) {
var result string
err := p.ask(&survey.Password{
Message: "Paste your authentication token:",
}, &result, survey.WithValidator(survey.Required))
return result, err
}
func (p *surveyPrompter) ConfirmDeletion(requiredValue string) error {
var result string
return p.ask(
&survey.Input{
Message: fmt.Sprintf("Type %s to confirm deletion:", requiredValue),
},
&result,
survey.WithValidator(
func(val interface{}) error {
if str := val.(string); !strings.EqualFold(str, requiredValue) {
return fmt.Errorf("You entered %s", str)
}
return nil
}))
}
func (p *surveyPrompter) InputHostname() (string, error) {
var result string
err := p.ask(
&survey.Input{
Message: "Hostname:",
}, &result, survey.WithValidator(func(v interface{}) error {
return ghinstance.HostnameValidator(v.(string))
}))
return result, err
}
func (p *surveyPrompter) MarkdownEditor(prompt, defaultValue string, blankAllowed bool) (string, error) {
var result string
err := p.ask(&surveyext.GhEditor{
BlankAllowed: blankAllowed,
EditorCommand: p.editorCmd,
Editor: &survey.Editor{
Message: prompt,
Default: defaultValue,
FileName: "*.md",
HideDefault: true,
AppendDefault: true,
},
}, &result)
return result, err
}
func (p *surveyPrompter) ask(q survey.Prompt, response interface{}, opts ...survey.AskOpt) error {
opts = append(opts, survey.WithStdio(p.stdin, p.stdout, p.stderr))
err := survey.AskOne(q, response, opts...)
if err == nil {
return nil
}
return fmt.Errorf("could not prompt: %w", err)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/prompter/accessible_prompter_test.go | internal/prompter/accessible_prompter_test.go | //go:build !windows
package prompter_test
import (
"fmt"
"io"
"slices"
"strings"
"testing"
"time"
"github.com/Netflix/go-expect"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/creack/pty"
"github.com/hinshun/vt10x"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The following tests are broadly testing the accessible prompter, and NOT asserting
// on the prompter's complete and exact output strings.
//
// These tests generally operate with this logic:
// - Wait for a particular substring (a portion of the prompt) to appear
// - Send input
// - Wait for another substring to appear or for control to return to the test
// - Assert that the input value was returned from the prompter function
// In the future, expanding these tests to assert on the exact prompt strings
// would help build confidence in `huh` upgrades, but for now these tests
// are sufficient to ensure that the accessible prompter behaves roughly as expected
// but doesn't mandate that prompts always look exactly the same.
func TestAccessiblePrompter(t *testing.T) {
beforePasswordSendTimeout := 100 * time.Microsecond
t.Run("Select", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Enter a number between 1 and 3:")
require.NoError(t, err)
// Select option 1
_, err = console.SendLine("1")
require.NoError(t, err)
}()
selectValue, err := p.Select("Select a number", "", []string{"1", "2", "3"})
require.NoError(t, err)
assert.Equal(t, 0, selectValue)
})
t.Run("Select - blank input returns default value", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyDefaultValue := "12345abcdefg"
options := []string{"1", "2", dummyDefaultValue}
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Enter a number between 1 and 3:")
require.NoError(t, err)
// Just press enter to accept the default
_, err = console.SendLine("")
require.NoError(t, err)
}()
selectValue, err := p.Select("Select a number", dummyDefaultValue, options)
require.NoError(t, err)
expectedIndex := slices.Index(options, dummyDefaultValue)
assert.Equal(t, expectedIndex, selectValue)
})
t.Run("Select - default value is in prompt and in readable format", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyDefaultValue := "12345abcdefg"
options := []string{"1", "2", dummyDefaultValue}
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Select a number (default: 12345abcdefg)")
require.NoError(t, err)
// Just press enter to accept the default
_, err = console.SendLine("")
require.NoError(t, err)
}()
selectValue, err := p.Select("Select a number", dummyDefaultValue, options)
require.NoError(t, err)
expectedIndex := slices.Index(options, dummyDefaultValue)
assert.Equal(t, expectedIndex, selectValue)
})
t.Run("Select - invalid defaults are excluded from prompt", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyDefaultValue := "foo"
options := []string{"1", "2"}
go func() {
// Wait for prompt to appear without the invalid default value
_, err := console.ExpectString("Select a number \r\n")
require.NoError(t, err)
// Select option 2
_, err = console.SendLine("2")
require.NoError(t, err)
}()
selectValue, err := p.Select("Select a number", dummyDefaultValue, options)
require.NoError(t, err)
assert.Equal(t, 1, selectValue)
})
t.Run("MultiSelect", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Input a number between 0 and 3:")
require.NoError(t, err)
// Select options 1 and 2
_, err = console.SendLine("1")
require.NoError(t, err)
_, err = console.SendLine("2")
require.NoError(t, err)
// This confirms selections
_, err = console.SendLine("0")
require.NoError(t, err)
}()
multiSelectValue, err := p.MultiSelect("Select a number", []string{}, []string{"1", "2", "3"})
require.NoError(t, err)
assert.Equal(t, []int{0, 1}, multiSelectValue)
})
t.Run("MultiSelect - default values are respected by being pre-selected", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Select a number")
require.NoError(t, err)
// Don't select anything because the default should be selected.
// This confirms selections
_, err = console.SendLine("0")
require.NoError(t, err)
}()
multiSelectValue, err := p.MultiSelect("Select a number", []string{"2"}, []string{"1", "2", "3"})
require.NoError(t, err)
assert.Equal(t, []int{1}, multiSelectValue)
})
t.Run("MultiSelect - default value is in prompt and in readable format", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyDefaultValues := []string{"foo", "bar"}
options := []string{"1", "2"}
options = append(options, dummyDefaultValues...)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Select a number (defaults: foo, bar)")
require.NoError(t, err)
// Don't select anything because the defaults should be selected.
// This confirms selections
_, err = console.SendLine("0")
require.NoError(t, err)
}()
multiSelectValues, err := p.MultiSelect("Select a number", dummyDefaultValues, options)
require.NoError(t, err)
var expectedIndices []int
// Get the indices of the default values within the options slice
// as that's what we expect the prompter to return when no selections are made.
for _, defaultValue := range dummyDefaultValues {
expectedIndices = append(expectedIndices, slices.Index(options, defaultValue))
}
assert.Equal(t, expectedIndices, multiSelectValues)
})
t.Run("MultiSelect - invalid defaults are excluded from prompt", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyDefaultValues := []string{"foo", "bar"}
options := []string{"1", "2"}
go func() {
// Wait for prompt to appear without the invalid default values
_, err := console.ExpectString("Select a number \r\n")
require.NoError(t, err)
// Not selecting anything will fail because there are no defaults.
_, err = console.SendLine("2")
require.NoError(t, err)
// This confirms selections
_, err = console.SendLine("0")
require.NoError(t, err)
}()
multiSelectValues, err := p.MultiSelect("Select a number", dummyDefaultValues, options)
require.NoError(t, err)
assert.Equal(t, []int{1}, multiSelectValues)
})
t.Run("Input", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyText := "12345abcdefg"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Enter some characters")
require.NoError(t, err)
// Enter a number
_, err = console.SendLine(dummyText)
require.NoError(t, err)
}()
inputValue, err := p.Input("Enter some characters", "")
require.NoError(t, err)
assert.Equal(t, dummyText, inputValue)
})
t.Run("Input - blank input returns default value", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyDefaultValue := "12345abcdefg"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Enter some characters")
require.NoError(t, err)
// Enter nothing
_, err = console.SendLine("")
require.NoError(t, err)
}()
inputValue, err := p.Input("Enter some characters", dummyDefaultValue)
require.NoError(t, err)
assert.Equal(t, dummyDefaultValue, inputValue)
})
t.Run("Input - default value is in prompt and in readable format", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyDefaultValue := "12345abcdefg"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Enter some characters (default: 12345abcdefg)")
require.NoError(t, err)
// Enter nothing
_, err = console.SendLine("")
require.NoError(t, err)
}()
inputValue, err := p.Input("Enter some characters", dummyDefaultValue)
require.NoError(t, err)
assert.Equal(t, dummyDefaultValue, inputValue)
})
t.Run("Password", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyPassword := "12345abcdefg"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Enter password")
require.NoError(t, err)
// Wait to ensure huh has time to set the echo mode
time.Sleep(beforePasswordSendTimeout)
// Enter a number
_, err = console.SendLine(dummyPassword)
require.NoError(t, err)
}()
passwordValue, err := p.Password("Enter password")
require.NoError(t, err)
require.Equal(t, dummyPassword, passwordValue)
// Ensure the dummy password is not printed to the screen,
// asserting that echo mode is disabled.
//
// Note that since console.ExpectString returns successful if the
// expected string matches any part of the stream, we have to use an
// anchored regexp (i.e., with ^ and $) to make sure the password/token
// is not printed at all.
_, err = console.Expect(expect.RegexpPattern("^ \r\n\r\n$"))
require.NoError(t, err)
})
t.Run("Confirm", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Are you sure")
require.NoError(t, err)
// Confirm
_, err = console.SendLine("y")
require.NoError(t, err)
}()
confirmValue, err := p.Confirm("Are you sure", false)
require.NoError(t, err)
require.Equal(t, true, confirmValue)
})
t.Run("Confirm - blank input returns default", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Are you sure")
require.NoError(t, err)
// Enter nothing
_, err = console.SendLine("")
require.NoError(t, err)
}()
confirmValue, err := p.Confirm("Are you sure", false)
require.NoError(t, err)
require.Equal(t, false, confirmValue)
})
t.Run("Confirm - default value is in prompt and in readable format", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
defaultValue := true
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Are you sure (default: yes)")
require.NoError(t, err)
// Enter nothing
_, err = console.SendLine("")
require.NoError(t, err)
}()
confirmValue, err := p.Confirm("Are you sure", defaultValue)
require.NoError(t, err)
require.Equal(t, defaultValue, confirmValue)
})
t.Run("AuthToken", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyAuthToken := "12345abcdefg"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Paste your authentication token:")
require.NoError(t, err)
// Wait to ensure huh has time to set the echo mode
time.Sleep(beforePasswordSendTimeout)
// Enter some dummy auth token
_, err = console.SendLine(dummyAuthToken)
require.NoError(t, err)
}()
authValue, err := p.AuthToken()
require.NoError(t, err)
require.Equal(t, dummyAuthToken, authValue)
// Ensure the dummy password is not printed to the screen,
// asserting that echo mode is disabled.
//
// Note that since console.ExpectString returns successful if the
// expected string matches any part of the stream, we have to use an
// anchored regexp (i.e., with ^ and $) to make sure the password/token
// is not printed at all.
_, err = console.Expect(expect.RegexpPattern("^ \r\n\r\n$"))
require.NoError(t, err)
})
t.Run("AuthToken - blank input returns error", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
dummyAuthTokenForAfterFailure := "12345abcdefg"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Paste your authentication token:")
require.NoError(t, err)
// Enter nothing
_, err = console.SendLine("")
require.NoError(t, err)
// Expect an error message
_, err = console.ExpectString("token is required")
require.NoError(t, err)
// Wait for the retry prompt
_, err = console.ExpectString("Paste your authentication token:")
require.NoError(t, err)
// Wait to ensure huh has time to set the echo mode
time.Sleep(beforePasswordSendTimeout)
// Now enter some dummy auth token to return control back to the test
_, err = console.SendLine(dummyAuthTokenForAfterFailure)
require.NoError(t, err)
}()
authValue, err := p.AuthToken()
require.NoError(t, err)
require.Equal(t, dummyAuthTokenForAfterFailure, authValue)
// Ensure the dummy password is not printed to the screen,
// asserting that echo mode is disabled.
//
// Note that since console.ExpectString returns successful if the
// expected string matches any part of the stream, we have to use an
// anchored regexp (i.e., with ^ and $) to make sure the password/token
// is not printed at all.
_, err = console.Expect(expect.RegexpPattern("^ \r\n\r\n$"))
require.NoError(t, err)
})
t.Run("ConfirmDeletion", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
requiredValue := "test"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString(fmt.Sprintf("Type %q to confirm deletion", requiredValue))
require.NoError(t, err)
// Confirm
_, err = console.SendLine(requiredValue)
require.NoError(t, err)
}()
// An err indicates that the confirmation text sent did not match
err := p.ConfirmDeletion(requiredValue)
require.NoError(t, err)
})
t.Run("ConfirmDeletion - bad input", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
requiredValue := "test"
badInputValue := "garbage"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString(fmt.Sprintf("Type %q to confirm deletion", requiredValue))
require.NoError(t, err)
// Confirm with bad input
_, err = console.SendLine(badInputValue)
require.NoError(t, err)
// Expect an error message and loop back to the prompt
_, err = console.ExpectString(fmt.Sprintf("You entered: %q", badInputValue))
require.NoError(t, err)
// Confirm with the correct input to return control back to the test
_, err = console.SendLine(requiredValue)
require.NoError(t, err)
}()
// An err indicates that the confirmation text sent did not match
err := p.ConfirmDeletion(requiredValue)
require.NoError(t, err)
})
t.Run("InputHostname", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
hostname := "example.com"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Hostname:")
require.NoError(t, err)
// Enter the hostname
_, err = console.SendLine(hostname)
require.NoError(t, err)
}()
inputValue, err := p.InputHostname()
require.NoError(t, err)
require.Equal(t, hostname, inputValue)
})
t.Run("MarkdownEditor - blank allowed with blank input returns blank", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("How to edit?")
require.NoError(t, err)
// Enter 2, to select "skip"
_, err = console.SendLine("2")
require.NoError(t, err)
}()
inputValue, err := p.MarkdownEditor("How to edit?", "", true)
require.NoError(t, err)
require.Equal(t, "", inputValue)
})
t.Run("MarkdownEditor - blank disallowed with default value returns default value", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
defaultValue := "12345abcdefg"
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("How to edit?")
require.NoError(t, err)
// Enter number 2 to select "skip". This shouldn't be allowed.
_, err = console.SendLine("2")
require.NoError(t, err)
// Expect a notice to enter something valid since blank is disallowed.
_, err = console.ExpectString("Invalid: must be 1")
require.NoError(t, err)
// Send a 1 to select to open the editor. This will immediately exit
_, err = console.SendLine("1")
require.NoError(t, err)
}()
inputValue, err := p.MarkdownEditor("How to edit?", defaultValue, false)
require.NoError(t, err)
require.Equal(t, defaultValue, inputValue)
})
t.Run("MarkdownEditor - blank disallowed no default value returns error", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestAccessiblePrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("How to edit?")
require.NoError(t, err)
// Enter number 2 to select "skip". This shouldn't be allowed.
_, err = console.SendLine("2")
require.NoError(t, err)
// Expect a notice to enter something valid since blank is disallowed.
_, err = console.ExpectString("Invalid: must be 1")
require.NoError(t, err)
// Send a 1 to select to open the editor since skip is invalid and
// we need to return control back to the test.
_, err = console.SendLine("1")
require.NoError(t, err)
}()
inputValue, err := p.MarkdownEditor("How to edit?", "", false)
require.NoError(t, err)
require.Equal(t, "", inputValue)
})
}
func TestSurveyPrompter(t *testing.T) {
// This not a comprehensive test of the survey prompter, but it does
// demonstrate that the survey prompter is used when the
// accessible prompter is disabled.
t.Run("Select uses survey prompter when accessible prompter is disabled", func(t *testing.T) {
console := newTestVirtualTerminal(t)
p := newTestSurveyPrompter(t, console)
go func() {
// Wait for prompt to appear
_, err := console.ExpectString("Select a number")
require.NoError(t, err)
// Send a newline to select the first option
// Note: This would not work with the accessible prompter
// because it would requires sending a 1 to select the first option.
// So it proves we are seeing a survey prompter.
_, err = console.SendLine("")
require.NoError(t, err)
}()
selectValue, err := p.Select("Select a number", "", []string{"1", "2", "3"})
require.NoError(t, err)
assert.Equal(t, 0, selectValue)
})
}
func newTestVirtualTerminal(t *testing.T) *expect.Console {
t.Helper()
// Create a PTY and hook up a virtual terminal emulator
ptm, pts, err := pty.Open()
require.NoError(t, err)
term := vt10x.New(vt10x.WithWriter(pts))
// Create a console via Expect that allows scripting against the terminal
consoleOpts := []expect.ConsoleOpt{
expect.WithStdin(ptm),
expect.WithStdout(term),
expect.WithCloser(ptm, pts),
failOnExpectError(t),
failOnSendError(t),
expect.WithDefaultTimeout(time.Second),
}
console, err := expect.NewConsole(consoleOpts...)
require.NoError(t, err)
t.Cleanup(func() { testCloser(t, console) })
return console
}
func newTestVirtualTerminalIOStreams(t *testing.T, console *expect.Console) *iostreams.IOStreams {
t.Helper()
io := &iostreams.IOStreams{
In: console.Tty(),
Out: console.Tty(),
ErrOut: console.Tty(),
}
io.SetStdinTTY(false)
io.SetStdoutTTY(false)
io.SetStderrTTY(false)
return io
}
// `echo` is chosen as the editor command because it immediately returns
// a success exit code, returns an empty string, doesn't require any user input,
// and since this file is only built on Linux, it is near guaranteed to be available.
var editorCmd = "echo"
func newTestAccessiblePrompter(t *testing.T, console *expect.Console) prompter.Prompter {
t.Helper()
io := newTestVirtualTerminalIOStreams(t, console)
io.SetAccessiblePrompterEnabled(true)
return prompter.New(editorCmd, io)
}
func newTestSurveyPrompter(t *testing.T, console *expect.Console) prompter.Prompter {
t.Helper()
io := newTestVirtualTerminalIOStreams(t, console)
io.SetAccessiblePrompterEnabled(false)
return prompter.New(editorCmd, io)
}
// failOnExpectError adds an observer that will fail the test in a standardised way
// if any expectation on the command output fails, without requiring an explicit
// assertion.
//
// Use WithRelaxedIO to disable this behaviour.
func failOnExpectError(t *testing.T) expect.ConsoleOpt {
t.Helper()
return expect.WithExpectObserver(
func(matchers []expect.Matcher, buf string, err error) {
t.Helper()
if err == nil {
return
}
if len(matchers) == 0 {
t.Fatalf("Error occurred while matching %q: %s\n", buf, err)
}
var criteria []string
for _, matcher := range matchers {
criteria = append(criteria, fmt.Sprintf("%q", matcher.Criteria()))
}
t.Fatalf("Failed to find [%s] in %q: %s\n", strings.Join(criteria, ", "), buf, err)
},
)
}
// failOnSendError adds an observer that will fail the test in a standardised way
// if any sending of input fails, without requiring an explicit assertion.
//
// Use WithRelaxedIO to disable this behaviour.
func failOnSendError(t *testing.T) expect.ConsoleOpt {
t.Helper()
return expect.WithSendObserver(
func(msg string, n int, err error) {
t.Helper()
if err != nil {
t.Fatalf("Failed to send %q: %s\n", msg, err)
}
if len(msg) != n {
t.Fatalf("Only sent %d of %d bytes for %q\n", n, len(msg), msg)
}
},
)
}
// testCloser is a helper to fail the test if a Closer fails to close.
func testCloser(t *testing.T, closer io.Closer) {
t.Helper()
if err := closer.Close(); err != nil {
t.Errorf("Close failed: %s", err)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/featuredetection/feature_detection_test.go | internal/featuredetection/feature_detection_test.go | package featuredetection
import (
"net/http"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIssueFeatures(t *testing.T) {
tests := []struct {
name string
hostname string
queryResponse map[string]string
wantFeatures IssueFeatures
wantErr bool
}{
{
name: "github.com",
hostname: "github.com",
wantFeatures: IssueFeatures{
StateReason: true,
ActorIsAssignable: true,
},
wantErr: false,
},
{
name: "ghec data residency (ghe.com)",
hostname: "stampname.ghe.com",
wantFeatures: IssueFeatures{
StateReason: true,
ActorIsAssignable: true,
},
wantErr: false,
},
{
name: "GHE empty response",
hostname: "git.my.org",
queryResponse: map[string]string{
`query Issue_fields\b`: `{"data": {}}`,
},
wantFeatures: IssueFeatures{
StateReason: false,
ActorIsAssignable: false,
},
wantErr: false,
},
{
name: "GHE has state reason field",
hostname: "git.my.org",
queryResponse: map[string]string{
`query Issue_fields\b`: heredoc.Doc(`
{ "data": { "Issue": { "fields": [
{"name": "stateReason"}
] } } }
`),
},
wantFeatures: IssueFeatures{
StateReason: true,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
httpClient := &http.Client{}
httpmock.ReplaceTripper(httpClient, reg)
for query, resp := range tt.queryResponse {
reg.Register(httpmock.GraphQL(query), httpmock.StringResponse(resp))
}
detector := detector{host: tt.hostname, httpClient: httpClient}
gotFeatures, err := detector.IssueFeatures()
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wantFeatures, gotFeatures)
})
}
}
func TestPullRequestFeatures(t *testing.T) {
tests := []struct {
name string
hostname string
queryResponse map[string]string
wantFeatures PullRequestFeatures
wantErr bool
}{
{
name: "github.com with all features",
hostname: "github.com",
queryResponse: map[string]string{
`query PullRequest_fields\b`: heredoc.Doc(`
{
"data": {
"PullRequest": {
"fields": [
{"name": "isInMergeQueue"},
{"name": "isMergeQueueEnabled"}
]
},
"StatusCheckRollupContextConnection": {
"fields": [
{"name": "checkRunCount"},
{"name": "checkRunCountsByState"},
{"name": "statusContextCount"},
{"name": "statusContextCountsByState"}
]
}
}
}`),
`query PullRequest_fields2\b`: heredoc.Doc(`
{
"data": {
"WorkflowRun": {
"fields": [
{"name": "event"}
]
}
}
}`),
},
wantFeatures: PullRequestFeatures{
MergeQueue: true,
CheckRunAndStatusContextCounts: true,
CheckRunEvent: true,
},
wantErr: false,
},
{
name: "github.com with no merge queue",
hostname: "github.com",
queryResponse: map[string]string{
`query PullRequest_fields\b`: heredoc.Doc(`
{
"data": {
"PullRequest": {
"fields": []
},
"StatusCheckRollupContextConnection": {
"fields": [
{"name": "checkRunCount"},
{"name": "checkRunCountsByState"},
{"name": "statusContextCount"},
{"name": "statusContextCountsByState"}
]
}
}
}`),
`query PullRequest_fields2\b`: heredoc.Doc(`
{
"data": {
"WorkflowRun": {
"fields": [
{"name": "event"}
]
}
}
}`),
},
wantFeatures: PullRequestFeatures{
MergeQueue: false,
CheckRunAndStatusContextCounts: true,
CheckRunEvent: true,
},
wantErr: false,
},
{
name: "GHE with all features",
hostname: "git.my.org",
queryResponse: map[string]string{
`query PullRequest_fields\b`: heredoc.Doc(`
{
"data": {
"PullRequest": {
"fields": [
{"name": "isInMergeQueue"},
{"name": "isMergeQueueEnabled"}
]
},
"StatusCheckRollupContextConnection": {
"fields": [
{"name": "checkRunCount"},
{"name": "checkRunCountsByState"},
{"name": "statusContextCount"},
{"name": "statusContextCountsByState"}
]
}
}
}`),
`query PullRequest_fields2\b`: heredoc.Doc(`
{
"data": {
"WorkflowRun": {
"fields": [
{"name": "event"}
]
}
}
}`),
},
wantFeatures: PullRequestFeatures{
MergeQueue: true,
CheckRunAndStatusContextCounts: true,
CheckRunEvent: true,
},
wantErr: false,
},
{
name: "GHE with no features",
hostname: "git.my.org",
queryResponse: map[string]string{
`query PullRequest_fields\b`: heredoc.Doc(`
{
"data": {
"PullRequest": {
"fields": []
},
"StatusCheckRollupContextConnection": {
"fields": []
}
}
}`),
`query PullRequest_fields2\b`: heredoc.Doc(`
{
"data": {
"WorkflowRun": {
"fields": []
}
}
}`),
},
wantFeatures: PullRequestFeatures{
MergeQueue: false,
CheckRunAndStatusContextCounts: false,
CheckRunEvent: false,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
httpClient := &http.Client{}
httpmock.ReplaceTripper(httpClient, reg)
for query, resp := range tt.queryResponse {
reg.Register(httpmock.GraphQL(query), httpmock.StringResponse(resp))
}
detector := detector{host: tt.hostname, httpClient: httpClient}
gotFeatures, err := detector.PullRequestFeatures()
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wantFeatures, gotFeatures)
})
}
}
func TestRepositoryFeatures(t *testing.T) {
tests := []struct {
name string
hostname string
queryResponse map[string]string
wantFeatures RepositoryFeatures
wantErr bool
}{
{
name: "github.com",
hostname: "github.com",
wantFeatures: RepositoryFeatures{
PullRequestTemplateQuery: true,
VisibilityField: true,
AutoMerge: true,
},
wantErr: false,
},
{
name: "ghec data residency (ghe.com)",
hostname: "stampname.ghe.com",
wantFeatures: RepositoryFeatures{
PullRequestTemplateQuery: true,
VisibilityField: true,
AutoMerge: true,
},
wantErr: false,
},
{
name: "GHE empty response",
hostname: "git.my.org",
queryResponse: map[string]string{
`query Repository_fields\b`: `{"data": {}}`,
},
wantFeatures: RepositoryFeatures{
PullRequestTemplateQuery: false,
},
wantErr: false,
},
{
name: "GHE has pull request template query",
hostname: "git.my.org",
queryResponse: map[string]string{
`query Repository_fields\b`: heredoc.Doc(`
{ "data": { "Repository": { "fields": [
{"name": "pullRequestTemplates"}
] } } }
`),
},
wantFeatures: RepositoryFeatures{
PullRequestTemplateQuery: true,
},
wantErr: false,
},
{
name: "GHE has visibility field",
hostname: "git.my.org",
queryResponse: map[string]string{
`query Repository_fields\b`: heredoc.Doc(`
{ "data": { "Repository": { "fields": [
{"name": "visibility"}
] } } }
`),
},
wantFeatures: RepositoryFeatures{
VisibilityField: true,
},
wantErr: false,
},
{
name: "GHE has automerge field",
hostname: "git.my.org",
queryResponse: map[string]string{
`query Repository_fields\b`: heredoc.Doc(`
{ "data": { "Repository": { "fields": [
{"name": "autoMergeAllowed"}
] } } }
`),
},
wantFeatures: RepositoryFeatures{
AutoMerge: true,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
httpClient := &http.Client{}
httpmock.ReplaceTripper(httpClient, reg)
for query, resp := range tt.queryResponse {
reg.Register(httpmock.GraphQL(query), httpmock.StringResponse(resp))
}
detector := detector{host: tt.hostname, httpClient: httpClient}
gotFeatures, err := detector.RepositoryFeatures()
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wantFeatures, gotFeatures)
})
}
}
func TestProjectV1Support(t *testing.T) {
tests := []struct {
name string
hostname string
httpStubs func(*httpmock.Registry)
wantFeatures gh.ProjectsV1Support
}{
{
name: "github.com",
hostname: "github.com",
wantFeatures: gh.ProjectsV1Unsupported,
},
{
name: "ghec data residency (ghe.com)",
hostname: "stampname.ghe.com",
wantFeatures: gh.ProjectsV1Unsupported,
},
{
name: "GHE 3.16.0",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.16.0"}`),
)
},
wantFeatures: gh.ProjectsV1Supported,
},
{
name: "GHE 3.16.1",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.16.1"}`),
)
},
wantFeatures: gh.ProjectsV1Supported,
},
{
name: "GHE 3.17",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.17.0"}`),
)
},
wantFeatures: gh.ProjectsV1Unsupported,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
httpClient := &http.Client{}
httpmock.ReplaceTripper(httpClient, reg)
detector := NewDetector(httpClient, tt.hostname)
require.Equal(t, tt.wantFeatures, detector.ProjectsV1())
})
}
}
func TestAdvancedIssueSearchSupport(t *testing.T) {
withIssueAdvanced := `{"data":{"SearchType":{"enumValues":[{"name":"ISSUE"},{"name":"ISSUE_ADVANCED"},{"name":"REPOSITORY"},{"name":"USER"},{"name":"DISCUSSION"}]}}}`
withoutIssueAdvanced := `{"data":{"SearchType":{"enumValues":[{"name":"ISSUE"},{"name":"REPOSITORY"},{"name":"USER"},{"name":"DISCUSSION"}]}}}`
tests := []struct {
name string
hostname string
httpStubs func(*httpmock.Registry)
wantFeatures SearchFeatures
}{
{
name: "github.com, before ISSUE_ADVANCED cleanup",
hostname: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOptIn,
},
{
name: "github.com, after ISSUE_ADVANCED cleanup",
hostname: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withoutIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOnlyBackend,
},
{
name: "ghec data residency (ghe.com), before ISSUE_ADVANCED cleanup",
hostname: "stampname.ghe.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOptIn,
},
{
name: "ghec data residency (ghe.com), after ISSUE_ADVANCED cleanup",
hostname: "stampname.ghe.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withoutIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOnlyBackend,
},
{
name: "GHE 3.18, before ISSUE_ADVANCED cleanup",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.18.0"}`),
)
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOptIn,
},
{
name: "GHE 3.18, after ISSUE_ADVANCED cleanup",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.18.0"}`),
)
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withoutIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOnlyBackend,
},
{
name: "GHE >3.18, before ISSUE_ADVANCED cleanup",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.18.1"}`),
)
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOptIn,
},
{
name: "GHE >3.18, after ISSUE_ADVANCED cleanup",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.18.1"}`),
)
reg.Register(
httpmock.GraphQL(`query SearchType_enumValues\b`),
httpmock.StringResponse(withoutIssueAdvanced),
)
},
wantFeatures: advancedIssueSearchSupportedAsOnlyBackend,
},
{
name: "GHE <3.18 (no advanced issue search support)",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "api/v3/meta"),
httpmock.StringResponse(`{"installed_version":"3.17.999"}`),
)
},
wantFeatures: advancedIssueSearchNotSupported,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
httpClient := &http.Client{}
httpmock.ReplaceTripper(httpClient, reg)
detector := NewDetector(httpClient, tt.hostname)
features, err := detector.SearchFeatures()
require.NoError(t, err)
require.Equal(t, tt.wantFeatures, features)
})
}
}
func TestReleaseFeatures(t *testing.T) {
withImmutableReleaseSupport := `{"data":{"Release":{"fields":[{"name":"author"},{"name":"name"},{"name":"immutable"}]}}}`
withoutImmutableReleaseSupport := `{"data":{"Release":{"fields":[{"name":"author"},{"name":"name"}]}}}`
tests := []struct {
name string
hostname string
httpStubs func(*httpmock.Registry)
wantFeatures ReleaseFeatures
}{
{
// This is not a real case as `github.com` supports immutable releases.
name: "github.com, immutable releases unsupported",
hostname: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query Release_fields\b`),
httpmock.StringResponse(withoutImmutableReleaseSupport),
)
},
wantFeatures: ReleaseFeatures{
ImmutableReleases: false,
},
},
{
name: "github.com, immutable releases supported",
hostname: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query Release_fields\b`),
httpmock.StringResponse(withImmutableReleaseSupport),
)
},
wantFeatures: ReleaseFeatures{
ImmutableReleases: true,
},
},
{
// This is not a real case as `github.com` supports immutable releases.
name: "ghec data residency (ghe.com), immutable releases unsupported",
hostname: "stampname.ghe.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query Release_fields\b`),
httpmock.StringResponse(withoutImmutableReleaseSupport),
)
},
wantFeatures: ReleaseFeatures{
ImmutableReleases: false,
},
},
{
name: "ghec data residency (ghe.com), immutable releases supported",
hostname: "stampname.ghe.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query Release_fields\b`),
httpmock.StringResponse(withImmutableReleaseSupport),
)
},
wantFeatures: ReleaseFeatures{
ImmutableReleases: true,
},
},
{
name: "GHE, immutable releases unsupported",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query Release_fields\b`),
httpmock.StringResponse(withoutImmutableReleaseSupport),
)
},
wantFeatures: ReleaseFeatures{
ImmutableReleases: false,
},
},
{
name: "GHE, immutable releases supported",
hostname: "git.my.org",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query Release_fields\b`),
httpmock.StringResponse(withImmutableReleaseSupport),
)
},
wantFeatures: ReleaseFeatures{
ImmutableReleases: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
httpClient := &http.Client{}
httpmock.ReplaceTripper(httpClient, reg)
detector := NewDetector(httpClient, tt.hostname)
features, err := detector.ReleaseFeatures()
require.NoError(t, err)
require.Equal(t, tt.wantFeatures, features)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/featuredetection/detector_mock.go | internal/featuredetection/detector_mock.go | package featuredetection
import "github.com/cli/cli/v2/internal/gh"
type DisabledDetectorMock struct{}
func (md *DisabledDetectorMock) IssueFeatures() (IssueFeatures, error) {
return IssueFeatures{}, nil
}
func (md *DisabledDetectorMock) PullRequestFeatures() (PullRequestFeatures, error) {
return PullRequestFeatures{}, nil
}
func (md *DisabledDetectorMock) RepositoryFeatures() (RepositoryFeatures, error) {
return RepositoryFeatures{}, nil
}
func (md *DisabledDetectorMock) ProjectsV1() gh.ProjectsV1Support {
return gh.ProjectsV1Unsupported
}
func (md *DisabledDetectorMock) SearchFeatures() (SearchFeatures, error) {
return advancedIssueSearchNotSupported, nil
}
func (md *DisabledDetectorMock) ReleaseFeatures() (ReleaseFeatures, error) {
return ReleaseFeatures{}, nil
}
type EnabledDetectorMock struct{}
func (md *EnabledDetectorMock) IssueFeatures() (IssueFeatures, error) {
return allIssueFeatures, nil
}
func (md *EnabledDetectorMock) PullRequestFeatures() (PullRequestFeatures, error) {
return allPullRequestFeatures, nil
}
func (md *EnabledDetectorMock) RepositoryFeatures() (RepositoryFeatures, error) {
return allRepositoryFeatures, nil
}
func (md *EnabledDetectorMock) ProjectsV1() gh.ProjectsV1Support {
return gh.ProjectsV1Supported
}
func (md *EnabledDetectorMock) SearchFeatures() (SearchFeatures, error) {
return advancedIssueSearchNotSupported, nil
}
func (md *EnabledDetectorMock) ReleaseFeatures() (ReleaseFeatures, error) {
return ReleaseFeatures{
ImmutableReleases: true,
}, nil
}
type AdvancedIssueSearchDetectorMock struct {
EnabledDetectorMock
searchFeatures SearchFeatures
}
func (md *AdvancedIssueSearchDetectorMock) SearchFeatures() (SearchFeatures, error) {
return md.searchFeatures, nil
}
func AdvancedIssueSearchUnsupported() *AdvancedIssueSearchDetectorMock {
return &AdvancedIssueSearchDetectorMock{
searchFeatures: advancedIssueSearchNotSupported,
}
}
func AdvancedIssueSearchSupportedAsOptIn() *AdvancedIssueSearchDetectorMock {
return &AdvancedIssueSearchDetectorMock{
searchFeatures: advancedIssueSearchSupportedAsOptIn,
}
}
func AdvancedIssueSearchSupportedAsOnlyBackend() *AdvancedIssueSearchDetectorMock {
return &AdvancedIssueSearchDetectorMock{
searchFeatures: advancedIssueSearchSupportedAsOnlyBackend,
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/featuredetection/feature_detection.go | internal/featuredetection/feature_detection.go | package featuredetection
import (
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/hashicorp/go-version"
"golang.org/x/sync/errgroup"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
)
type Detector interface {
IssueFeatures() (IssueFeatures, error)
PullRequestFeatures() (PullRequestFeatures, error)
RepositoryFeatures() (RepositoryFeatures, error)
ProjectsV1() gh.ProjectsV1Support
SearchFeatures() (SearchFeatures, error)
ReleaseFeatures() (ReleaseFeatures, error)
}
type IssueFeatures struct {
StateReason bool
ActorIsAssignable bool
}
var allIssueFeatures = IssueFeatures{
StateReason: true,
ActorIsAssignable: true,
}
type PullRequestFeatures struct {
MergeQueue bool
// CheckRunAndStatusContextCounts indicates whether the API supports
// the checkRunCount, checkRunCountsByState, statusContextCount and statusContextCountsByState
// fields on the StatusCheckRollupContextConnection
CheckRunAndStatusContextCounts bool
CheckRunEvent bool
}
var allPullRequestFeatures = PullRequestFeatures{
MergeQueue: true,
CheckRunAndStatusContextCounts: true,
CheckRunEvent: true,
}
type RepositoryFeatures struct {
PullRequestTemplateQuery bool
VisibilityField bool
AutoMerge bool
}
var allRepositoryFeatures = RepositoryFeatures{
PullRequestTemplateQuery: true,
VisibilityField: true,
AutoMerge: true,
}
type SearchFeatures struct {
// AdvancedIssueSearch indicates whether the host supports advanced issue
// search via API calls.
AdvancedIssueSearchAPI bool
// AdvancedIssueSearchOptIn indicates whether the host supports advanced
// issue search as an opt-in feature, which has to be explicitly enabled in
// API calls.
AdvancedIssueSearchAPIOptIn bool
// TODO advancedSearchFuture
// When advanced issue search is supported in Pull Requests tab, or in
// global search we can introduce more fields to reflect the support status.
}
// advancedIssueSearchNotSupported mimics GHE <3.18 where advanced issue search
// is either not supported or is not meant to be used due to not being stable
// enough (i.e. in preview).
var advancedIssueSearchNotSupported = SearchFeatures{
AdvancedIssueSearchAPI: false,
}
// advancedIssueSearchSupportedAsOptIn mimics github.com and GHE >=3.18 before
// the full cleanup of temp types (i.e. ISSUE_ADVANCED search type is still
// present on the schema).
var advancedIssueSearchSupportedAsOptIn = SearchFeatures{
AdvancedIssueSearchAPI: true,
AdvancedIssueSearchAPIOptIn: true,
}
// advancedIssueSearchSupportedAsOnlyBackend mimics github.com and GHE >=3.18
// after the full cleanup of temp types (i.e. ISSUE_ADVANCED search type is
// removed from the schema).
var advancedIssueSearchSupportedAsOnlyBackend = SearchFeatures{
AdvancedIssueSearchAPI: true,
AdvancedIssueSearchAPIOptIn: false,
}
type ReleaseFeatures struct {
ImmutableReleases bool
}
type detector struct {
host string
httpClient *http.Client
}
func NewDetector(httpClient *http.Client, host string) Detector {
return &detector{
httpClient: httpClient,
host: host,
}
}
func (d *detector) IssueFeatures() (IssueFeatures, error) {
if !ghauth.IsEnterprise(d.host) {
return allIssueFeatures, nil
}
features := IssueFeatures{
StateReason: false,
ActorIsAssignable: false, // replaceActorsForAssignable GraphQL mutation unavailable on GHES
}
var featureDetection struct {
Issue struct {
Fields []struct {
Name string
} `graphql:"fields(includeDeprecated: true)"`
} `graphql:"Issue: __type(name: \"Issue\")"`
}
gql := api.NewClientFromHTTP(d.httpClient)
err := gql.Query(d.host, "Issue_fields", &featureDetection, nil)
if err != nil {
return features, err
}
for _, field := range featureDetection.Issue.Fields {
if field.Name == "stateReason" {
features.StateReason = true
}
}
return features, nil
}
func (d *detector) PullRequestFeatures() (PullRequestFeatures, error) {
// TODO: reinstate the short-circuit once the APIs are fully available on github.com
// https://github.com/cli/cli/issues/5778
//
// if !ghinstance.IsEnterprise(d.host) {
// return allPullRequestFeatures, nil
// }
var pullRequestFeatureDetection struct {
PullRequest struct {
Fields []struct {
Name string
} `graphql:"fields(includeDeprecated: true)"`
} `graphql:"PullRequest: __type(name: \"PullRequest\")"`
StatusCheckRollupContextConnection struct {
Fields []struct {
Name string
} `graphql:"fields(includeDeprecated: true)"`
} `graphql:"StatusCheckRollupContextConnection: __type(name: \"StatusCheckRollupContextConnection\")"`
}
// Break feature detection down into two separate queries because the platform
// only supports two `__type` expressions in one query.
var pullRequestFeatureDetection2 struct {
WorkflowRun struct {
Fields []struct {
Name string
} `graphql:"fields(includeDeprecated: true)"`
} `graphql:"WorkflowRun: __type(name: \"WorkflowRun\")"`
}
gql := api.NewClientFromHTTP(d.httpClient)
var wg errgroup.Group
wg.Go(func() error {
return gql.Query(d.host, "PullRequest_fields", &pullRequestFeatureDetection, nil)
})
wg.Go(func() error {
return gql.Query(d.host, "PullRequest_fields2", &pullRequestFeatureDetection2, nil)
})
if err := wg.Wait(); err != nil {
return PullRequestFeatures{}, err
}
features := PullRequestFeatures{}
for _, field := range pullRequestFeatureDetection.PullRequest.Fields {
if field.Name == "isInMergeQueue" {
features.MergeQueue = true
}
}
for _, field := range pullRequestFeatureDetection.StatusCheckRollupContextConnection.Fields {
// We only check for checkRunCount here but it, checkRunCountsByState, statusContextCount and statusContextCountsByState
// were all introduced in the same version of the API.
if field.Name == "checkRunCount" {
features.CheckRunAndStatusContextCounts = true
}
}
for _, field := range pullRequestFeatureDetection2.WorkflowRun.Fields {
if field.Name == "event" {
features.CheckRunEvent = true
}
}
return features, nil
}
func (d *detector) RepositoryFeatures() (RepositoryFeatures, error) {
if !ghauth.IsEnterprise(d.host) {
return allRepositoryFeatures, nil
}
features := RepositoryFeatures{}
var featureDetection struct {
Repository struct {
Fields []struct {
Name string
} `graphql:"fields(includeDeprecated: true)"`
} `graphql:"Repository: __type(name: \"Repository\")"`
}
gql := api.NewClientFromHTTP(d.httpClient)
err := gql.Query(d.host, "Repository_fields", &featureDetection, nil)
if err != nil {
return features, err
}
for _, field := range featureDetection.Repository.Fields {
if field.Name == "pullRequestTemplates" {
features.PullRequestTemplateQuery = true
}
if field.Name == "visibility" {
features.VisibilityField = true
}
if field.Name == "autoMergeAllowed" {
features.AutoMerge = true
}
}
return features, nil
}
const (
enterpriseProjectsV1Removed = "3.17.0"
)
func (d *detector) ProjectsV1() gh.ProjectsV1Support {
if !ghauth.IsEnterprise(d.host) {
return gh.ProjectsV1Unsupported
}
hostVersion, hostVersionErr := resolveEnterpriseVersion(d.httpClient, d.host)
v1ProjectCutoffVersion, v1ProjectCutoffVersionErr := version.NewVersion(enterpriseProjectsV1Removed)
if hostVersionErr == nil && v1ProjectCutoffVersionErr == nil && hostVersion.LessThan(v1ProjectCutoffVersion) {
return gh.ProjectsV1Supported
}
return gh.ProjectsV1Unsupported
}
const (
// enterpriseAdvancedIssueSearchSupport is the minimum version of GHES that
// supports advanced issue search and gh should use it.
//
// Note that advanced issue search is also available on GHES 3.17, but it's
// at the preview stage and is not as mature as it is on github.com or later
// GHES version.
enterpriseAdvancedIssueSearchSupport = "3.18.0"
)
func (d *detector) SearchFeatures() (SearchFeatures, error) {
// TODO advancedIssueSearchCleanup
// Once GHES 3.17 support ends, we don't need this and, probably, the entire search feature detection.
// Regarding the release of advanced issue search (AIS, for short), there
// are three time spans/periods:
//
// 1. Pre-deprecation: where both legacy search and AIS are available
// - GraphQL: `ISSUE` and `ISSUE_ADVANCED` search types in GraphQL behave differently
// - REST: `advance_search=true` query parameter can be used to switch to AIS
// 2. Deprecation: only AIS available
// - GraphQL: `ISSUE` and `ISSUE_ADVANCED` search types in GraphQL behave the same (AIS)
// - REST: `advance_search` query parameter has no effect (AIS)
// 3. Cleanup: only AIS available
// - GraphQL: `ISSUE` search type in GraphQL is the only available option (AIS)
// - REST: `advance_search` query parameter has no effect (AIS)
//
// Since there's no schema-wise difference between pre-deprecation and
// deprecation periods (i.e. `ISSUE_ADVANCED` is available during both),
// we cannot figure out the exact time period. The consensus is to to use
// the advanced search syntax during both periods.
var feature SearchFeatures
if ghauth.IsEnterprise(d.host) {
enterpriseAISSupportVersion, err := version.NewVersion(enterpriseAdvancedIssueSearchSupport)
if err != nil {
return SearchFeatures{}, err
}
hostVersion, err := resolveEnterpriseVersion(d.httpClient, d.host)
if err != nil {
return SearchFeatures{}, err
}
if hostVersion.GreaterThanOrEqual(enterpriseAISSupportVersion) {
// As of August 2025, advanced issue search is going to be available
// on GHES 3.18+, including Issues tabs in repositories.
feature.AdvancedIssueSearchAPI = true
// TODO advancedSearchFuture
// When the advanced search syntax is supported in global search or
// Pull Requests tabs (in repositories), we can add and enable the
// corresponding fields.
}
} else {
// As of August 2025, advanced issue search is available on github.com,
// including Issues tabs in repositories.
feature.AdvancedIssueSearchAPI = true
// TODO advancedSearchFuture
// When the advanced search syntax is supported in global search or
// Pull Requests tabs (in repositories), we can add and enable the
// corresponding fields.
}
if !feature.AdvancedIssueSearchAPI {
return feature, nil
}
var searchTypeFeatureDetection struct {
SearchType struct {
EnumValues []struct {
Name string
} `graphql:"enumValues(includeDeprecated: true)"`
} `graphql:"SearchType: __type(name: \"SearchType\")"`
}
gql := api.NewClientFromHTTP(d.httpClient)
if err := gql.Query(d.host, "SearchType_enumValues", &searchTypeFeatureDetection, nil); err != nil {
return SearchFeatures{}, err
}
for _, enumValue := range searchTypeFeatureDetection.SearchType.EnumValues {
if enumValue.Name == "ISSUE_ADVANCED" {
// As long as ISSUE_ADVANCED is present on the schema, we should
// explicitly opt-in when making API calls.
feature.AdvancedIssueSearchAPIOptIn = true
break
}
}
return feature, nil
}
func (d *detector) ReleaseFeatures() (ReleaseFeatures, error) {
// TODO: immutableReleaseFullSupport
// Once all supported GHES versions fully support immutable releases, we can
// remove this function, of course, unless there will be other release-related
// features that are not available on all GH hosts.
var releaseFeatureDetection struct {
Release struct {
Fields []struct {
Name string
} `graphql:"fields"`
} `graphql:"Release: __type(name: \"Release\")"`
}
gql := api.NewClientFromHTTP(d.httpClient)
if err := gql.Query(d.host, "Release_fields", &releaseFeatureDetection, nil); err != nil {
return ReleaseFeatures{}, err
}
for _, field := range releaseFeatureDetection.Release.Fields {
if field.Name == "immutable" {
return ReleaseFeatures{
ImmutableReleases: true,
}, nil
}
}
return ReleaseFeatures{}, nil
}
func resolveEnterpriseVersion(httpClient *http.Client, host string) (*version.Version, error) {
var metaResponse struct {
InstalledVersion string `json:"installed_version"`
}
apiClient := api.NewClientFromHTTP(httpClient)
err := apiClient.REST(host, "GET", "meta", nil, &metaResponse)
if err != nil {
return nil, err
}
return version.NewVersion(metaResponse.InstalledVersion)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/build/build.go | internal/build/build.go | package build
import (
"os"
"runtime/debug"
)
// Version is dynamically set by the toolchain or overridden by the Makefile.
var Version = "DEV"
// Date is dynamically set at build time in the Makefile.
var Date = "" // YYYY-MM-DD
func init() {
if Version == "DEV" {
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "(devel)" {
Version = info.Main.Version
}
}
// Signal the tcell library to skip its expensive `init` block. This saves 30-40ms in startup
// time for the gh process. The downside is that some Unicode glyphs from user-generated
// content might cause misalignment in tcell-enabled views.
//
// https://github.com/gdamore/tcell/commit/2f889d79bd61b1fd2f43372529975a65b792a7ae
_ = os.Setenv("TCELL_MINIMIZE", "1")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/docs/man.go | internal/docs/man.go | package docs
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/root"
"github.com/cpuguy83/go-md2man/v2/md2man"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"github.com/spf13/pflag"
)
// GenManTree will generate a man page for this command and all descendants
// in the directory given. The header may be nil. This function may not work
// correctly if your command names have `-` in them. If you have `cmd` with two
// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
// it is undefined which help output will be in the file `cmd-sub-third.1`.
func GenManTree(cmd *cobra.Command, dir string) error {
if os.Getenv("GH_COBRA") != "" {
return doc.GenManTreeFromOpts(cmd, doc.GenManTreeOptions{
Path: dir,
CommandSeparator: "-",
})
}
return genManTreeFromOpts(cmd, GenManTreeOptions{
Path: dir,
CommandSeparator: "-",
})
}
// genManTreeFromOpts generates a man page for the command and all descendants.
// The pages are written to the opts.Path directory.
func genManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
continue
}
if err := genManTreeFromOpts(c, opts); err != nil {
return err
}
}
section := "1"
separator := "_"
if opts.CommandSeparator != "" {
separator = opts.CommandSeparator
}
basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)
filename := filepath.Join(opts.Path, basename+"."+section)
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
var versionString string
if v := os.Getenv("GH_VERSION"); v != "" {
versionString = "GitHub CLI " + v
}
return renderMan(cmd, &GenManHeader{
Section: section,
Source: versionString,
Manual: "GitHub CLI manual",
}, f)
}
// GenManTreeOptions is the options for generating the man pages.
// Used only in GenManTreeFromOpts.
type GenManTreeOptions struct {
Path string
CommandSeparator string
}
// GenManHeader is a lot like the .TH header at the start of man pages. These
// include the title, section, date, source, and manual. We will use the
// current time if Date is unset.
type GenManHeader struct {
Title string
Section string
Date *time.Time
Source string
Manual string
}
// renderMan will generate a man page for the given command and write it to
// w. The header argument may be nil, however obviously w may not.
func renderMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
if err := fillHeader(header, cmd.CommandPath()); err != nil {
return err
}
b := genMan(cmd, header)
_, err := w.Write(md2man.Render(b))
return err
}
func fillHeader(header *GenManHeader, name string) error {
if header.Title == "" {
header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
}
if header.Section == "" {
header.Section = "1"
}
if header.Date == nil {
now := time.Now()
if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" {
unixEpoch, err := strconv.ParseInt(epoch, 10, 64)
if err != nil {
return fmt.Errorf("invalid SOURCE_DATE_EPOCH: %v", err)
}
now = time.Unix(unixEpoch, 0)
}
header.Date = &now
}
return nil
}
func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {
buf.WriteString(fmt.Sprintf(`%% "%s" "%s" "%s" "%s" "%s"
# NAME
`, header.Title, header.Section, header.Date.Format("Jan 2006"), header.Source, header.Manual))
buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))
buf.WriteString("# SYNOPSIS\n")
buf.WriteString(fmt.Sprintf("`%s`\n\n", cmd.UseLine()))
if cmd.Long != "" && cmd.Long != cmd.Short {
buf.WriteString("# DESCRIPTION\n")
buf.WriteString(cmd.Long + "\n\n")
}
}
func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {
flags.VisitAll(func(flag *pflag.Flag) {
if len(flag.Deprecated) > 0 || flag.Hidden || flag.Name == "help" {
return
}
varname, usage := pflag.UnquoteUsage(flag)
if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
buf.WriteString(fmt.Sprintf("`-%s`, `--%s`", flag.Shorthand, flag.Name))
} else {
buf.WriteString(fmt.Sprintf("`--%s`", flag.Name))
}
defval := getDefaultValueDisplayString(flag)
if varname == "" && defval != "" {
buf.WriteString(fmt.Sprintf(" `%s`\n", strings.TrimSpace(defval)))
} else if varname == "" {
buf.WriteString("\n")
} else {
buf.WriteString(fmt.Sprintf(" `<%s>%s`\n", varname, defval))
}
buf.WriteString(fmt.Sprintf(": %s\n\n", usage))
})
}
func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {
flags := command.NonInheritedFlags()
if flags.HasAvailableFlags() {
buf.WriteString("# OPTIONS\n")
manPrintFlags(buf, flags)
buf.WriteString("\n")
}
flags = command.InheritedFlags()
if hasNonHelpFlags(flags) {
buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n")
manPrintFlags(buf, flags)
buf.WriteString("\n")
}
}
func manPrintAliases(buf *bytes.Buffer, command *cobra.Command) {
if len(command.Aliases) > 0 {
buf.WriteString("# ALIASES\n")
buf.WriteString(strings.Join(root.BuildAliasList(command, command.Aliases), ", "))
buf.WriteString("\n")
}
}
func manPrintJSONFields(buf *bytes.Buffer, command *cobra.Command) {
raw, ok := command.Annotations["help:json-fields"]
if !ok {
return
}
buf.WriteString("# JSON FIELDS\n")
buf.WriteString(text.FormatSlice(strings.Split(raw, ","), 0, 0, "`", "`", true))
buf.WriteString("\n")
}
func manPrintExitCodes(buf *bytes.Buffer) {
buf.WriteString("# EXIT CODES\n")
buf.WriteString("0: Successful execution\n\n")
buf.WriteString("1: Error\n\n")
buf.WriteString("2: Command canceled\n\n")
buf.WriteString("4: Authentication required\n\n")
buf.WriteString("NOTE: Specific commands may have additional exit codes. Refer to the command's help for more information.\n\n")
}
func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
cmd.InitDefaultHelpCmd()
cmd.InitDefaultHelpFlag()
// something like `rootcmd-subcmd1-subcmd2`
dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
buf := new(bytes.Buffer)
manPreamble(buf, header, cmd, dashCommandName)
for _, g := range root.GroupedCommands(cmd) {
fmt.Fprintf(buf, "# %s\n", strings.ToUpper(g.Title))
for _, subcmd := range g.Commands {
fmt.Fprintf(buf, "`%s`\n: %s\n\n", manLink(subcmd), subcmd.Short)
}
}
manPrintOptions(buf, cmd)
manPrintAliases(buf, cmd)
manPrintJSONFields(buf, cmd)
manPrintExitCodes(buf)
if len(cmd.Example) > 0 {
buf.WriteString("# EXAMPLE\n")
buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example))
}
if cmd.HasParent() {
buf.WriteString("# SEE ALSO\n")
buf.WriteString(fmt.Sprintf("`%s`\n", manLink(cmd.Parent())))
}
return buf.Bytes()
}
func manLink(cmd *cobra.Command) string {
p := cmd.CommandPath()
return fmt.Sprintf("%s(%d)", strings.Replace(p, " ", "-", -1), 1)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/docs/docs_test.go | internal/docs/docs_test.go | package docs
import (
"strings"
"testing"
"github.com/spf13/cobra"
)
func emptyRun(*cobra.Command, []string) {}
func init() {
rootCmd.PersistentFlags().StringP("rootflag", "r", "two", "")
rootCmd.PersistentFlags().StringP("strtwo", "t", "two", "help message for parent flag strtwo")
echoCmd.PersistentFlags().StringP("strone", "s", "one", "help message for flag strone")
echoCmd.PersistentFlags().BoolP("persistentbool", "p", false, "help message for flag persistentbool")
echoCmd.Flags().IntP("intone", "i", 123, "help message for flag intone")
echoCmd.Flags().BoolP("boolone", "b", true, "help message for flag boolone")
timesCmd.PersistentFlags().StringP("strtwo", "t", "2", "help message for child flag strtwo")
timesCmd.Flags().IntP("inttwo", "j", 234, "help message for flag inttwo")
timesCmd.Flags().BoolP("booltwo", "c", false, "help message for flag booltwo")
printCmd.PersistentFlags().StringP("strthree", "s", "three", "help message for flag strthree")
printCmd.Flags().IntP("intthree", "i", 345, "help message for flag intthree")
printCmd.Flags().BoolP("boolthree", "b", true, "help message for flag boolthree")
jsonCmd.Flags().StringSlice("json", nil, "help message for flag json")
aliasCmd.Flags().StringSlice("yang", nil, "help message for flag yang")
echoCmd.AddCommand(timesCmd, echoSubCmd, deprecatedCmd)
rootCmd.AddCommand(printCmd, echoCmd, dummyCmd)
}
var rootCmd = &cobra.Command{
Use: "root",
Short: "Root short description",
Long: "Root long description",
Run: emptyRun,
}
var echoCmd = &cobra.Command{
Use: "echo [string to echo]",
Aliases: []string{"say"},
Short: "Echo anything to the screen",
Long: "an utterly useless command for testing",
Example: "Just run cobra-test echo",
}
var echoSubCmd = &cobra.Command{
Use: "echosub [string to print]",
Short: "second sub command for echo",
Long: "an absolutely utterly useless command for testing gendocs!.",
Run: emptyRun,
}
var timesCmd = &cobra.Command{
Use: "times [# times] [string to echo]",
SuggestFor: []string{"counts"},
Short: "Echo anything to the screen more times",
Long: `a slightly useless command for testing.`,
Run: emptyRun,
}
var deprecatedCmd = &cobra.Command{
Use: "deprecated [can't do anything here]",
Short: "A command which is deprecated",
Long: `an absolutely utterly useless command for testing deprecation!.`,
Deprecated: "Please use echo instead",
}
var printCmd = &cobra.Command{
Use: "print [string to print]",
Short: "Print anything to the screen",
Long: `an absolutely utterly useless command for testing.`,
}
var aliasCmd = &cobra.Command{
Use: "ying [yang]",
Short: "The ying and yang of it all",
Long: "an absolutely utterly useless command for testing aliases!.",
Aliases: []string{"yoo", "foo"},
}
var jsonCmd = &cobra.Command{
Use: "blah --json <fields>",
Short: "View details in JSON",
Annotations: map[string]string{
"help:json-fields": "foo,bar,baz",
},
}
var dummyCmd = &cobra.Command{
Use: "dummy [action]",
Short: "Performs a dummy action",
}
func checkStringContains(t *testing.T, got, expected string) {
t.Helper()
if !strings.Contains(got, expected) {
t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)
}
}
func checkStringOmits(t *testing.T, got, expected string) {
t.Helper()
if strings.Contains(got, expected) {
t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/docs/markdown_test.go | internal/docs/markdown_test.go | package docs
import (
"bytes"
"os"
"path/filepath"
"testing"
"github.com/spf13/cobra"
)
func TestGenMdDoc(t *testing.T) {
linkHandler := func(s string) string { return s }
// We generate on subcommand so we have both subcommands and parents.
buf := new(bytes.Buffer)
if err := genMarkdownCustom(echoCmd, buf, linkHandler); err != nil {
t.Fatal(err)
}
output := buf.String()
checkStringContains(t, output, echoCmd.Long)
checkStringContains(t, output, echoCmd.Example)
checkStringContains(t, output, "boolone")
checkStringContains(t, output, "rootflag")
checkStringOmits(t, output, rootCmd.Short)
checkStringOmits(t, output, echoSubCmd.Short)
checkStringOmits(t, output, deprecatedCmd.Short)
checkStringContains(t, output, "Options inherited from parent commands")
}
func TestGenMdDocWithNoLongOrSynopsis(t *testing.T) {
linkHandler := func(s string) string { return s }
// We generate on subcommand so we have both subcommands and parents.
buf := new(bytes.Buffer)
if err := genMarkdownCustom(dummyCmd, buf, linkHandler); err != nil {
t.Fatal(err)
}
output := buf.String()
checkStringContains(t, output, dummyCmd.Example)
checkStringContains(t, output, dummyCmd.Short)
checkStringContains(t, output, "Options inherited from parent commands")
checkStringOmits(t, output, "### Synopsis")
}
func TestGenMdNoHiddenParents(t *testing.T) {
linkHandler := func(s string) string { return s }
// We generate on subcommand so we have both subcommands and parents.
for _, name := range []string{"rootflag", "strtwo"} {
f := rootCmd.PersistentFlags().Lookup(name)
f.Hidden = true
defer func() { f.Hidden = false }()
}
buf := new(bytes.Buffer)
if err := genMarkdownCustom(echoCmd, buf, linkHandler); err != nil {
t.Fatal(err)
}
output := buf.String()
checkStringContains(t, output, echoCmd.Long)
checkStringContains(t, output, echoCmd.Example)
checkStringContains(t, output, "boolone")
checkStringOmits(t, output, "rootflag")
checkStringOmits(t, output, rootCmd.Short)
checkStringOmits(t, output, echoSubCmd.Short)
checkStringOmits(t, output, deprecatedCmd.Short)
checkStringOmits(t, output, "Options inherited from parent commands")
}
func TestGenMdAliases(t *testing.T) {
buf := new(bytes.Buffer)
if err := genMarkdownCustom(aliasCmd, buf, nil); err != nil {
t.Fatal(err)
}
output := buf.String()
checkStringContains(t, output, aliasCmd.Long)
checkStringContains(t, output, jsonCmd.Example)
checkStringContains(t, output, "ALIASES")
checkStringContains(t, output, "yoo")
checkStringContains(t, output, "foo")
}
func TestGenMdJSONFields(t *testing.T) {
buf := new(bytes.Buffer)
if err := genMarkdownCustom(jsonCmd, buf, nil); err != nil {
t.Fatal(err)
}
output := buf.String()
checkStringContains(t, output, jsonCmd.Long)
checkStringContains(t, output, jsonCmd.Example)
checkStringContains(t, output, "JSON Fields")
checkStringContains(t, output, "`foo`")
checkStringContains(t, output, "`bar`")
checkStringContains(t, output, "`baz`")
}
func TestGenMdTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
tmpdir, err := os.MkdirTemp("", "test-gen-md-tree")
if err != nil {
t.Fatalf("Failed to create tmpdir: %v", err)
}
defer os.RemoveAll(tmpdir)
if err := GenMarkdownTreeCustom(c, tmpdir, func(s string) string { return s }, func(s string) string { return s }); err != nil {
t.Fatalf("GenMarkdownTree failed: %v", err)
}
if _, err := os.Stat(filepath.Join(tmpdir, "do.md")); err != nil {
t.Fatalf("Expected file 'do.md' to exist")
}
}
func BenchmarkGenMarkdownToFile(b *testing.B) {
file, err := os.CreateTemp(b.TempDir(), "")
if err != nil {
b.Fatal(err)
}
defer file.Close()
linkHandler := func(s string) string { return s }
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := genMarkdownCustom(rootCmd, file, linkHandler); err != nil {
b.Fatal(err)
}
}
}
func TestPrintFlagsHTMLShowsDefaultValues(t *testing.T) {
type TestOptions struct {
Limit int
Template string
Fork bool
NoArchive bool
Topic []string
}
opts := TestOptions{}
// Int flag should show it
c := &cobra.Command{}
c.Flags().IntVar(&opts.Limit, "limit", 30, "Some limit")
flags := c.NonInheritedFlags()
buf := new(bytes.Buffer)
flags.SetOutput(buf)
if err := printFlagsHTML(buf, flags); err != nil {
t.Fatalf("printFlagsHTML failed: %s", err.Error())
}
output := buf.String()
checkStringContains(t, output, "(default 30)")
// Bool flag should hide it if default is false
c = &cobra.Command{}
c.Flags().BoolVar(&opts.Fork, "fork", false, "Show only forks")
flags = c.NonInheritedFlags()
buf = new(bytes.Buffer)
flags.SetOutput(buf)
if err := printFlagsHTML(buf, flags); err != nil {
t.Fatalf("printFlagsHTML failed: %s", err.Error())
}
output = buf.String()
checkStringOmits(t, output, "(default ")
// Bool flag should show it if default is true
c = &cobra.Command{}
c.Flags().BoolVar(&opts.NoArchive, "no-archived", true, "Hide archived")
flags = c.NonInheritedFlags()
buf = new(bytes.Buffer)
flags.SetOutput(buf)
if err := printFlagsHTML(buf, flags); err != nil {
t.Fatalf("printFlagsHTML failed: %s", err.Error())
}
output = buf.String()
checkStringContains(t, output, "(default true)")
// String flag should show it if default is not an empty string
c = &cobra.Command{}
c.Flags().StringVar(&opts.Template, "template", "T1", "Some template")
flags = c.NonInheritedFlags()
buf = new(bytes.Buffer)
flags.SetOutput(buf)
if err := printFlagsHTML(buf, flags); err != nil {
t.Fatalf("printFlagsHTML failed: %s", err.Error())
}
output = buf.String()
checkStringContains(t, output, "(default "T1")")
// String flag should hide it if default is an empty string
c = &cobra.Command{}
c.Flags().StringVar(&opts.Template, "template", "", "Some template")
flags = c.NonInheritedFlags()
buf = new(bytes.Buffer)
flags.SetOutput(buf)
if err := printFlagsHTML(buf, flags); err != nil {
t.Fatalf("printFlagsHTML failed: %s", err.Error())
}
output = buf.String()
checkStringOmits(t, output, "(default ")
// String slice flag should hide it if default is an empty slice
c = &cobra.Command{}
c.Flags().StringSliceVar(&opts.Topic, "topic", nil, "Some topics")
flags = c.NonInheritedFlags()
buf = new(bytes.Buffer)
flags.SetOutput(buf)
if err := printFlagsHTML(buf, flags); err != nil {
t.Fatalf("printFlagsHTML failed: %s", err.Error())
}
output = buf.String()
checkStringOmits(t, output, "(default ")
// String slice flag should show it if default is not an empty slice
c = &cobra.Command{}
c.Flags().StringSliceVar(&opts.Topic, "topic", []string{"apples", "oranges"}, "Some topics")
flags = c.NonInheritedFlags()
buf = new(bytes.Buffer)
flags.SetOutput(buf)
if err := printFlagsHTML(buf, flags); err != nil {
t.Fatalf("printFlagsHTML failed: %s", err.Error())
}
output = buf.String()
checkStringContains(t, output, "(default [apples,oranges])")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/docs/man_test.go | internal/docs/man_test.go | package docs
import (
"bufio"
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/spf13/cobra"
)
func translate(in string) string {
return strings.Replace(in, "-", "\\-", -1)
}
func TestGenManDoc(t *testing.T) {
header := &GenManHeader{
Title: "Project",
Section: "1",
}
// We generate on a subcommand so we have both subcommands and parents
buf := new(bytes.Buffer)
if err := renderMan(echoCmd, header, buf); err != nil {
t.Fatal(err)
}
output := buf.String()
// Make sure parent has - in CommandPath() in SEE ALSO:
parentPath := echoCmd.Parent().CommandPath()
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
expected := translate(dashParentPath)
expected = expected + "(" + header.Section + ")"
checkStringContains(t, output, expected)
checkStringContains(t, output, translate(echoCmd.Name()))
checkStringContains(t, output, translate(echoCmd.Name()))
checkStringContains(t, output, "boolone")
checkStringContains(t, output, "rootflag")
checkStringContains(t, output, translate(rootCmd.Name()))
checkStringContains(t, output, translate(echoSubCmd.Name()))
checkStringOmits(t, output, translate(deprecatedCmd.Name()))
}
func TestGenManNoHiddenParents(t *testing.T) {
header := &GenManHeader{
Title: "Project",
Section: "1",
}
// We generate on a subcommand so we have both subcommands and parents
for _, name := range []string{"rootflag", "strtwo"} {
f := rootCmd.PersistentFlags().Lookup(name)
f.Hidden = true
defer func() { f.Hidden = false }()
}
buf := new(bytes.Buffer)
if err := renderMan(echoCmd, header, buf); err != nil {
t.Fatal(err)
}
output := buf.String()
// Make sure parent has - in CommandPath() in SEE ALSO:
parentPath := echoCmd.Parent().CommandPath()
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
expected := translate(dashParentPath)
expected = expected + "(" + header.Section + ")"
checkStringContains(t, output, expected)
checkStringContains(t, output, translate(echoCmd.Name()))
checkStringContains(t, output, translate(echoCmd.Name()))
checkStringContains(t, output, "boolone")
checkStringOmits(t, output, "rootflag")
checkStringContains(t, output, translate(rootCmd.Name()))
checkStringContains(t, output, translate(echoSubCmd.Name()))
checkStringOmits(t, output, translate(deprecatedCmd.Name()))
checkStringOmits(t, output, "OPTIONS INHERITED FROM PARENT COMMANDS")
}
func TestGenManSeeAlso(t *testing.T) {
rootCmd := &cobra.Command{Use: "root", Run: emptyRun}
aCmd := &cobra.Command{Use: "aaa", Run: emptyRun, Hidden: true} // #229
bCmd := &cobra.Command{Use: "bbb", Run: emptyRun}
cCmd := &cobra.Command{Use: "ccc", Run: emptyRun}
rootCmd.AddCommand(aCmd, bCmd, cCmd)
buf := new(bytes.Buffer)
header := &GenManHeader{}
if err := renderMan(rootCmd, header, buf); err != nil {
t.Fatal(err)
}
scanner := bufio.NewScanner(buf)
if err := assertLineFound(scanner, ".SH SEE ALSO"); err == nil {
t.Fatalf("Did not expect SEE ALSO section header")
}
}
func TestGenManAliases(t *testing.T) {
buf := new(bytes.Buffer)
header := &GenManHeader{}
if err := renderMan(aliasCmd, header, buf); err != nil {
t.Fatal(err)
}
output := buf.String()
checkStringContains(t, output, translate(aliasCmd.Name()))
checkStringContains(t, output, "ALIASES")
checkStringContains(t, output, "foo")
checkStringContains(t, output, "yoo")
}
func TestGenManJSONFields(t *testing.T) {
buf := new(bytes.Buffer)
header := &GenManHeader{}
if err := renderMan(jsonCmd, header, buf); err != nil {
t.Fatal(err)
}
output := buf.String()
checkStringContains(t, output, translate(jsonCmd.Name()))
checkStringContains(t, output, "JSON FIELDS")
checkStringContains(t, output, "foo")
checkStringContains(t, output, "bar")
checkStringContains(t, output, "baz")
}
func TestGenManDocExitCodes(t *testing.T) {
header := &GenManHeader{
Title: "Project",
Section: "1",
}
cmd := &cobra.Command{
Use: "test-command",
Short: "A test command",
Long: "A test command for checking exit codes section",
}
buf := new(bytes.Buffer)
if err := renderMan(cmd, header, buf); err != nil {
t.Fatal(err)
}
output := buf.String()
// Check for the presence of the exit codes section
checkStringContains(t, output, ".SH EXIT CODES")
checkStringContains(t, output, "0: Successful execution")
checkStringContains(t, output, "1: Error")
checkStringContains(t, output, "2: Command canceled")
checkStringContains(t, output, "4: Authentication required")
checkStringContains(t, output, "NOTE: Specific commands may have additional exit codes. Refer to the command's help for more information.")
}
func TestManPrintFlagsHidesShortDeprecated(t *testing.T) {
c := &cobra.Command{}
c.Flags().StringP("foo", "f", "default", "Foo flag")
_ = c.Flags().MarkShorthandDeprecated("foo", "don't use it no more")
buf := new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got := buf.String()
expected := "`--foo` `<string> (default \"default\")`\n: Foo flag\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
}
func TestGenManTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
tmpdir, err := os.MkdirTemp("", "test-gen-man-tree")
if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error())
}
defer os.RemoveAll(tmpdir)
if err := GenManTree(c, tmpdir); err != nil {
t.Fatalf("GenManTree failed: %s", err.Error())
}
if _, err := os.Stat(filepath.Join(tmpdir, "do.1")); err != nil {
t.Fatalf("Expected file 'do.1' to exist")
}
}
func TestManPrintFlagsShowsDefaultValues(t *testing.T) {
type TestOptions struct {
Limit int
Template string
Fork bool
NoArchive bool
Topic []string
}
opts := TestOptions{}
// Int flag should show it
c := &cobra.Command{}
c.Flags().IntVar(&opts.Limit, "limit", 30, "Some limit")
buf := new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got := buf.String()
expected := "`--limit` `<int> (default 30)`\n: Some limit\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// Bool flag should hide it if default is false
c = &cobra.Command{}
c.Flags().BoolVar(&opts.Fork, "fork", false, "Show only forks")
buf = new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got = buf.String()
expected = "`--fork`\n: Show only forks\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// Bool flag should show it if default is true
c = &cobra.Command{}
c.Flags().BoolVar(&opts.NoArchive, "no-archived", true, "Hide archived")
buf = new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got = buf.String()
expected = "`--no-archived` `(default true)`\n: Hide archived\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// String flag should show it if default is not an empty string
c = &cobra.Command{}
c.Flags().StringVar(&opts.Template, "template", "T1", "Some template")
buf = new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got = buf.String()
expected = "`--template` `<string> (default \"T1\")`\n: Some template\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// String flag should hide it if default is an empty string
c = &cobra.Command{}
c.Flags().StringVar(&opts.Template, "template", "", "Some template")
buf = new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got = buf.String()
expected = "`--template` `<string>`\n: Some template\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// String slice flag should hide it if default is an empty slice
c = &cobra.Command{}
c.Flags().StringSliceVar(&opts.Topic, "topic", nil, "Some topics")
buf = new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got = buf.String()
expected = "`--topic` `<strings>`\n: Some topics\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
// String slice flag should show it if default is not an empty slice
c = &cobra.Command{}
c.Flags().StringSliceVar(&opts.Topic, "topic", []string{"apples", "oranges"}, "Some topics")
buf = new(bytes.Buffer)
manPrintFlags(buf, c.Flags())
got = buf.String()
expected = "`--topic` `<strings> (default [apples,oranges])`\n: Some topics\n\n"
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}
}
func assertLineFound(scanner *bufio.Scanner, expectedLine string) error {
for scanner.Scan() {
line := scanner.Text()
if line == expectedLine {
return nil
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("scan failed: %s", err)
}
return fmt.Errorf("hit EOF before finding %v", expectedLine)
}
func BenchmarkGenManToFile(b *testing.B) {
file, err := os.CreateTemp(b.TempDir(), "")
if err != nil {
b.Fatal(err)
}
defer file.Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := renderMan(rootCmd, nil, file); err != nil {
b.Fatal(err)
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/docs/markdown.go | internal/docs/markdown.go | package docs
import (
"fmt"
"html/template"
"io"
"os"
"path/filepath"
"strings"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/root"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"github.com/spf13/pflag"
)
func printJSONFields(w io.Writer, cmd *cobra.Command) {
raw, ok := cmd.Annotations["help:json-fields"]
if !ok {
return
}
fmt.Fprint(w, "### JSON Fields\n\n")
fmt.Fprint(w, text.FormatSlice(strings.Split(raw, ","), 0, 0, "`", "`", true))
fmt.Fprint(w, "\n\n")
}
func printAliases(w io.Writer, cmd *cobra.Command) {
if len(cmd.Aliases) > 0 {
fmt.Fprintf(w, "### ALIASES\n\n")
fmt.Fprint(w, text.FormatSlice(strings.Split(strings.Join(root.BuildAliasList(cmd, cmd.Aliases), ", "), ","), 0, 0, "", "", true))
fmt.Fprint(w, "\n\n")
}
}
func printOptions(w io.Writer, cmd *cobra.Command) error {
flags := cmd.NonInheritedFlags()
flags.SetOutput(w)
if flags.HasAvailableFlags() {
fmt.Fprint(w, "### Options\n\n")
if err := printFlagsHTML(w, flags); err != nil {
return err
}
fmt.Fprint(w, "\n\n")
}
parentFlags := cmd.InheritedFlags()
parentFlags.SetOutput(w)
if hasNonHelpFlags(parentFlags) {
fmt.Fprint(w, "### Options inherited from parent commands\n\n")
if err := printFlagsHTML(w, parentFlags); err != nil {
return err
}
fmt.Fprint(w, "\n\n")
}
return nil
}
func hasNonHelpFlags(fs *pflag.FlagSet) (found bool) {
fs.VisitAll(func(f *pflag.Flag) {
if !f.Hidden && f.Name != "help" {
found = true
}
})
return
}
var hiddenFlagDefaults = map[string]bool{
"false": true,
"": true,
"[]": true,
"0s": true,
}
var defaultValFormats = map[string]string{
"string": " (default \"%s\")",
"duration": " (default \"%s\")",
}
func getDefaultValueDisplayString(f *pflag.Flag) string {
if hiddenFlagDefaults[f.DefValue] || hiddenFlagDefaults[f.Value.Type()] {
return ""
}
if dvf, found := defaultValFormats[f.Value.Type()]; found {
return fmt.Sprintf(dvf, f.Value)
}
return fmt.Sprintf(" (default %s)", f.Value)
}
type flagView struct {
Name string
Varname string
Shorthand string
DefValue string
Usage string
}
var flagsTemplate = `
<dl class="flags">{{ range . }}
<dt>{{ if .Shorthand }}<code>-{{.Shorthand}}</code>, {{ end }}
<code>--{{.Name}}{{ if .Varname }} <{{.Varname}}>{{ end }}{{.DefValue}}</code></dt>
<dd>{{.Usage}}</dd>
{{ end }}</dl>
`
var tpl = template.Must(template.New("flags").Parse(flagsTemplate))
func printFlagsHTML(w io.Writer, fs *pflag.FlagSet) error {
var flags []flagView
fs.VisitAll(func(f *pflag.Flag) {
if f.Hidden || f.Name == "help" {
return
}
varname, usage := pflag.UnquoteUsage(f)
flags = append(flags, flagView{
Name: f.Name,
Varname: varname,
Shorthand: f.Shorthand,
DefValue: getDefaultValueDisplayString(f),
Usage: usage,
})
})
return tpl.Execute(w, flags)
}
// genMarkdownCustom creates custom markdown output.
func genMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
fmt.Fprint(w, "{% raw %}")
fmt.Fprintf(w, "## %s\n\n", cmd.CommandPath())
hasLong := cmd.Long != ""
if !hasLong {
fmt.Fprintf(w, "%s\n\n", cmd.Short)
}
if cmd.Runnable() {
fmt.Fprintf(w, "```\n%s\n```\n\n", cmd.UseLine())
}
if hasLong {
fmt.Fprintf(w, "%s\n\n", cmd.Long)
}
for _, g := range root.GroupedCommands(cmd) {
fmt.Fprintf(w, "### %s\n\n", g.Title)
for _, subcmd := range g.Commands {
fmt.Fprintf(w, "* [%s](%s)\n", subcmd.CommandPath(), linkHandler(cmdManualPath(subcmd)))
}
fmt.Fprint(w, "\n\n")
}
if err := printOptions(w, cmd); err != nil {
return err
}
printAliases(w, cmd)
printJSONFields(w, cmd)
fmt.Fprint(w, "{% endraw %}\n")
if len(cmd.Example) > 0 {
fmt.Fprint(w, "### Examples\n\n{% highlight bash %}{% raw %}\n")
fmt.Fprint(w, cmd.Example)
fmt.Fprint(w, "{% endraw %}{% endhighlight %}\n\n")
}
if cmd.HasParent() {
p := cmd.Parent()
fmt.Fprint(w, "### See also\n\n")
fmt.Fprintf(w, "* [%s](%s)\n", p.CommandPath(), linkHandler(cmdManualPath(p)))
}
return nil
}
// GenMarkdownTreeCustom is the same as GenMarkdownTree, but
// with custom filePrepender and linkHandler.
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
if os.Getenv("GH_COBRA") != "" {
return doc.GenMarkdownTreeCustom(cmd, dir, filePrepender, linkHandler)
}
for _, c := range cmd.Commands() {
_, forceGeneration := c.Annotations["markdown:generate"]
if c.Hidden && !forceGeneration {
continue
}
if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
return err
}
}
filename := filepath.Join(dir, cmdManualPath(cmd))
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
return err
}
if err := genMarkdownCustom(cmd, f, linkHandler); err != nil {
return err
}
return nil
}
func cmdManualPath(c *cobra.Command) string {
if basenameOverride, found := c.Annotations["markdown:basename"]; found {
return basenameOverride + ".md"
}
return strings.ReplaceAll(c.CommandPath(), " ", "_") + ".md"
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/update/update_test.go | internal/update/update_test.go | package update
import (
"context"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/cli/cli/v2/pkg/cmd/extension"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/require"
)
func TestCheckForUpdate(t *testing.T) {
scenarios := []struct {
Name string
CurrentVersion string
LatestVersion string
LatestURL string
ExpectsResult bool
}{
{
Name: "latest is newer",
CurrentVersion: "v0.0.1",
LatestVersion: "v1.0.0",
LatestURL: "https://www.spacejam.com/archive/spacejam/movie/jam.htm",
ExpectsResult: true,
},
{
Name: "current is prerelease",
CurrentVersion: "v1.0.0-pre.1",
LatestVersion: "v1.0.0",
LatestURL: "https://www.spacejam.com/archive/spacejam/movie/jam.htm",
ExpectsResult: true,
},
{
Name: "current is built from source",
CurrentVersion: "v1.2.3-123-gdeadbeef",
LatestVersion: "v1.2.3",
LatestURL: "https://www.spacejam.com/archive/spacejam/movie/jam.htm",
ExpectsResult: false,
},
{
Name: "current is built from source after a prerelease",
CurrentVersion: "v1.2.3-rc.1-123-gdeadbeef",
LatestVersion: "v1.2.3",
LatestURL: "https://www.spacejam.com/archive/spacejam/movie/jam.htm",
ExpectsResult: true,
},
{
Name: "latest is newer than version build from source",
CurrentVersion: "v1.2.3-123-gdeadbeef",
LatestVersion: "v1.2.4",
LatestURL: "https://www.spacejam.com/archive/spacejam/movie/jam.htm",
ExpectsResult: true,
},
{
Name: "latest is current",
CurrentVersion: "v1.0.0",
LatestVersion: "v1.0.0",
LatestURL: "https://www.spacejam.com/archive/spacejam/movie/jam.htm",
ExpectsResult: false,
},
{
Name: "latest is older",
CurrentVersion: "v0.10.0-pre.1",
LatestVersion: "v0.9.0",
LatestURL: "https://www.spacejam.com/archive/spacejam/movie/jam.htm",
ExpectsResult: false,
},
}
for _, s := range scenarios {
t.Run(s.Name, func(t *testing.T) {
reg := &httpmock.Registry{}
httpClient := &http.Client{}
httpmock.ReplaceTripper(httpClient, reg)
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/releases/latest"),
httpmock.StringResponse(fmt.Sprintf(`{
"tag_name": "%s",
"html_url": "%s"
}`, s.LatestVersion, s.LatestURL)),
)
rel, err := CheckForUpdate(context.TODO(), httpClient, tempFilePath(), "OWNER/REPO", s.CurrentVersion)
if err != nil {
t.Fatal(err)
}
if len(reg.Requests) != 1 {
t.Fatalf("expected 1 HTTP request, got %d", len(reg.Requests))
}
requestPath := reg.Requests[0].URL.Path
if requestPath != "/repos/OWNER/REPO/releases/latest" {
t.Errorf("HTTP path: %q", requestPath)
}
if !s.ExpectsResult {
if rel != nil {
t.Fatal("expected no new release")
}
return
}
if rel == nil {
t.Fatal("expected to report new release")
}
if rel.Version != s.LatestVersion {
t.Errorf("Version: %q", rel.Version)
}
if rel.URL != s.LatestURL {
t.Errorf("URL: %q", rel.URL)
}
})
}
}
func TestCheckForExtensionUpdate(t *testing.T) {
now := time.Date(2024, 12, 17, 12, 0, 0, 0, time.UTC)
previousTooSoon := now.Add(-23 * time.Hour).Add(-59 * time.Minute).Add(-59 * time.Second)
previousOldEnough := now.Add(-24 * time.Hour)
tests := []struct {
name string
extCurrentVersion string
extLatestVersion string
extKind extension.ExtensionKind
extURL string
previousStateEntry *StateEntry
expectedStateEntry *StateEntry
expectedReleaseInfo *ReleaseInfo
wantErr bool
}{
{
name: "return latest release given git extension is out of date and no state entry",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.GitKind,
extURL: "http://example.com",
expectedStateEntry: &StateEntry{
CheckedForUpdateAt: now,
LatestRelease: ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
expectedReleaseInfo: &ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
{
name: "return latest release given git extension is out of date and state entry is old enough",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.GitKind,
extURL: "http://example.com",
previousStateEntry: &StateEntry{
CheckedForUpdateAt: previousOldEnough,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedStateEntry: &StateEntry{
CheckedForUpdateAt: now,
LatestRelease: ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
expectedReleaseInfo: &ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
{
name: "return nothing given git extension is out of date but state entry is too recent",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.GitKind,
extURL: "http://example.com",
previousStateEntry: &StateEntry{
CheckedForUpdateAt: previousTooSoon,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedStateEntry: &StateEntry{
CheckedForUpdateAt: previousTooSoon,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedReleaseInfo: nil,
},
{
name: "return latest release given binary extension is out of date and no state entry",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.BinaryKind,
extURL: "http://example.com",
expectedStateEntry: &StateEntry{
CheckedForUpdateAt: now,
LatestRelease: ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
expectedReleaseInfo: &ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
{
name: "return latest release given binary extension is out of date and state entry is old enough",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.BinaryKind,
extURL: "http://example.com",
previousStateEntry: &StateEntry{
CheckedForUpdateAt: previousOldEnough,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedStateEntry: &StateEntry{
CheckedForUpdateAt: now,
LatestRelease: ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
expectedReleaseInfo: &ReleaseInfo{
Version: "v1.0.0",
URL: "http://example.com",
},
},
{
name: "return nothing given binary extension is out of date but state entry is too recent",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.BinaryKind,
extURL: "http://example.com",
previousStateEntry: &StateEntry{
CheckedForUpdateAt: previousTooSoon,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedStateEntry: &StateEntry{
CheckedForUpdateAt: previousTooSoon,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedReleaseInfo: nil,
},
{
name: "return nothing given local extension with no state entry",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.LocalKind,
extURL: "http://example.com",
expectedStateEntry: nil,
expectedReleaseInfo: nil,
},
{
name: "return nothing given local extension despite state entry is old enough",
extCurrentVersion: "v0.1.0",
extLatestVersion: "v1.0.0",
extKind: extension.LocalKind,
extURL: "http://example.com",
previousStateEntry: &StateEntry{
CheckedForUpdateAt: previousOldEnough,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedStateEntry: &StateEntry{
CheckedForUpdateAt: previousOldEnough,
LatestRelease: ReleaseInfo{
Version: "v0.1.0",
URL: "http://example.com",
},
},
expectedReleaseInfo: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
updateDir := t.TempDir()
em := &extensions.ExtensionManagerMock{
UpdateDirFunc: func(name string) string {
return filepath.Join(updateDir, name)
},
}
ext := &extensions.ExtensionMock{
NameFunc: func() string {
return "extension-update-test"
},
CurrentVersionFunc: func() string {
return tt.extCurrentVersion
},
LatestVersionFunc: func() string {
return tt.extLatestVersion
},
IsLocalFunc: func() bool {
return tt.extKind == extension.LocalKind
},
IsBinaryFunc: func() bool {
return tt.extKind == extension.BinaryKind
},
URLFunc: func() string {
return tt.extURL
},
}
// UpdateAvailable is arguably code under test but moq does not support partial mocks so this is a little brittle.
ext.UpdateAvailableFunc = func() bool {
if ext.IsLocal() {
panic("Local extensions do not get update notices")
}
// Actual extension versions should drive tests instead of managing UpdateAvailable separately.
current := ext.CurrentVersion()
latest := ext.LatestVersion()
return current != "" && latest != "" && current != latest
}
// Setup previous state file for test as necessary
stateFilePath := filepath.Join(em.UpdateDir(ext.Name()), "state.yml")
if tt.previousStateEntry != nil {
require.NoError(t, setStateEntry(stateFilePath, tt.previousStateEntry.CheckedForUpdateAt, tt.previousStateEntry.LatestRelease))
}
actual, err := CheckForExtensionUpdate(em, ext, now)
if tt.wantErr {
require.Error(t, err)
return
}
require.Equal(t, tt.expectedReleaseInfo, actual)
if tt.expectedStateEntry == nil {
require.NoFileExists(t, stateFilePath)
} else {
stateEntry, err := getStateEntry(stateFilePath)
require.NoError(t, err)
require.Equal(t, tt.expectedStateEntry, stateEntry)
}
})
}
}
func TestShouldCheckForUpdate(t *testing.T) {
tests := []struct {
name string
env map[string]string
expected bool
}{
{
name: "should not check when user has explicitly disable notifications",
env: map[string]string{
"GH_NO_UPDATE_NOTIFIER": "1",
},
expected: false,
},
{
name: "should not check when user is in codespace",
env: map[string]string{
"CODESPACES": "1",
},
expected: false,
},
{
name: "should not check when in GitHub Actions / Travis / Circle / Cirrus / GitLab / AppVeyor / CodeShip / dsari",
env: map[string]string{
"CI": "1",
},
expected: false,
},
{
name: "should not check when in Jenkins / TeamCity",
env: map[string]string{
"BUILD_NUMBER": "1",
},
expected: false,
},
{
name: "should not check when in TaskCluster / dsari",
env: map[string]string{
"RUN_ID": "1",
},
expected: false,
},
// TODO: Figure out how to refactor IsTerminal() to be testable
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
os.Clearenv()
for k, v := range tt.env {
os.Setenv(k, v)
}
actual := ShouldCheckForUpdate()
require.Equal(t, tt.expected, actual)
})
}
}
func TestShouldCheckForExtensionUpdate(t *testing.T) {
tests := []struct {
name string
env map[string]string
expected bool
}{
{
name: "should not check when user has explicitly disable notifications",
env: map[string]string{
"GH_NO_EXTENSION_UPDATE_NOTIFIER": "1",
},
expected: false,
},
{
name: "should not check when user is in codespace",
env: map[string]string{
"CODESPACES": "1",
},
expected: false,
},
{
name: "should not check when in GitHub Actions / Travis / Circle / Cirrus / GitLab / AppVeyor / CodeShip / dsari",
env: map[string]string{
"CI": "1",
},
expected: false,
},
{
name: "should not check when in Jenkins / TeamCity",
env: map[string]string{
"BUILD_NUMBER": "1",
},
expected: false,
},
{
name: "should not check when in TaskCluster / dsari",
env: map[string]string{
"RUN_ID": "1",
},
expected: false,
},
// TODO: Figure out how to refactor IsTerminal() to be testable
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
os.Clearenv()
for k, v := range tt.env {
os.Setenv(k, v)
}
actual := ShouldCheckForExtensionUpdate()
require.Equal(t, tt.expected, actual)
})
}
}
func tempFilePath() string {
file, err := os.CreateTemp("", "")
if err != nil {
log.Fatal(err)
}
os.Remove(file.Name())
return file.Name()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/update/update.go | internal/update/update.go | package update
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/hashicorp/go-version"
"github.com/mattn/go-isatty"
"gopkg.in/yaml.v3"
)
var gitDescribeSuffixRE = regexp.MustCompile(`\d+-\d+-g[a-f0-9]{8}$`)
// ReleaseInfo stores information about a release
type ReleaseInfo struct {
Version string `json:"tag_name"`
URL string `json:"html_url"`
PublishedAt time.Time `json:"published_at"`
}
type StateEntry struct {
CheckedForUpdateAt time.Time `yaml:"checked_for_update_at"`
LatestRelease ReleaseInfo `yaml:"latest_release"`
}
// ShouldCheckForExtensionUpdate decides whether we check for updates for GitHub CLI extensions based on user preferences and current execution context.
// During cli/cli#9934, this logic was split out from ShouldCheckForUpdate() because we envisioned it going in a different direction.
func ShouldCheckForExtensionUpdate() bool {
if os.Getenv("GH_NO_EXTENSION_UPDATE_NOTIFIER") != "" {
return false
}
if os.Getenv("CODESPACES") != "" {
return false
}
return !IsCI() && IsTerminal(os.Stdout) && IsTerminal(os.Stderr)
}
// CheckForExtensionUpdate checks whether an update exists for a specific extension based on extension type and recency of last check within past 24 hours.
func CheckForExtensionUpdate(em extensions.ExtensionManager, ext extensions.Extension, now time.Time) (*ReleaseInfo, error) {
// local extensions cannot have updates, so avoid work that ultimately returns nothing.
if ext.IsLocal() {
return nil, nil
}
stateFilePath := filepath.Join(em.UpdateDir(ext.Name()), "state.yml")
stateEntry, _ := getStateEntry(stateFilePath)
if stateEntry != nil && now.Sub(stateEntry.CheckedForUpdateAt).Hours() < 24 {
return nil, nil
}
releaseInfo := &ReleaseInfo{
Version: ext.LatestVersion(),
URL: ext.URL(),
}
err := setStateEntry(stateFilePath, now, *releaseInfo)
if err != nil {
return nil, err
}
if ext.UpdateAvailable() {
return releaseInfo, nil
}
return nil, nil
}
// ShouldCheckForUpdate decides whether we check for updates for the GitHub CLI based on user preferences and current execution context.
func ShouldCheckForUpdate() bool {
if os.Getenv("GH_NO_UPDATE_NOTIFIER") != "" {
return false
}
if os.Getenv("CODESPACES") != "" {
return false
}
return !IsCI() && IsTerminal(os.Stdout) && IsTerminal(os.Stderr)
}
// CheckForUpdate checks whether an update exists for the GitHub CLI based on recency of last check within past 24 hours.
func CheckForUpdate(ctx context.Context, client *http.Client, stateFilePath, repo, currentVersion string) (*ReleaseInfo, error) {
stateEntry, _ := getStateEntry(stateFilePath)
if stateEntry != nil && time.Since(stateEntry.CheckedForUpdateAt).Hours() < 24 {
return nil, nil
}
releaseInfo, err := getLatestReleaseInfo(ctx, client, repo)
if err != nil {
return nil, err
}
err = setStateEntry(stateFilePath, time.Now(), *releaseInfo)
if err != nil {
return nil, err
}
if versionGreaterThan(releaseInfo.Version, currentVersion) {
return releaseInfo, nil
}
return nil, nil
}
func getLatestReleaseInfo(ctx context.Context, client *http.Client, repo string) (*ReleaseInfo, error) {
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo), nil)
if err != nil {
return nil, err
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer func() {
_, _ = io.Copy(io.Discard, res.Body)
res.Body.Close()
}()
if res.StatusCode != 200 {
return nil, fmt.Errorf("unexpected HTTP %d", res.StatusCode)
}
dec := json.NewDecoder(res.Body)
var latestRelease ReleaseInfo
if err := dec.Decode(&latestRelease); err != nil {
return nil, err
}
return &latestRelease, nil
}
func getStateEntry(stateFilePath string) (*StateEntry, error) {
content, err := os.ReadFile(stateFilePath)
if err != nil {
return nil, err
}
var stateEntry StateEntry
err = yaml.Unmarshal(content, &stateEntry)
if err != nil {
return nil, err
}
return &stateEntry, nil
}
func setStateEntry(stateFilePath string, t time.Time, r ReleaseInfo) error {
data := StateEntry{CheckedForUpdateAt: t, LatestRelease: r}
content, err := yaml.Marshal(data)
if err != nil {
return err
}
err = os.MkdirAll(filepath.Dir(stateFilePath), 0755)
if err != nil {
return err
}
err = os.WriteFile(stateFilePath, content, 0600)
return err
}
func versionGreaterThan(v, w string) bool {
w = gitDescribeSuffixRE.ReplaceAllStringFunc(w, func(m string) string {
idx := strings.IndexRune(m, '-')
n, _ := strconv.Atoi(m[0:idx])
return fmt.Sprintf("%d-pre.0", n+1)
})
vv, ve := version.NewVersion(v)
vw, we := version.NewVersion(w)
return ve == nil && we == nil && vv.GreaterThan(vw)
}
// IsTerminal determines if a file descriptor is an interactive terminal / TTY.
func IsTerminal(f *os.File) bool {
return isatty.IsTerminal(f.Fd()) || isatty.IsCygwinTerminal(f.Fd())
}
// IsCI determines if the current execution context is within a known CI/CD system.
// This is based on https://github.com/watson/ci-info/blob/HEAD/index.js.
func IsCI() bool {
return os.Getenv("CI") != "" || // GitHub Actions, Travis CI, CircleCI, Cirrus CI, GitLab CI, AppVeyor, CodeShip, dsari
os.Getenv("BUILD_NUMBER") != "" || // Jenkins, TeamCity
os.Getenv("RUN_ID") != "" // TaskCluster, dsari
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/ssh.go | internal/codespaces/ssh.go | package codespaces
import (
"context"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/cli/safeexec"
)
type printer interface {
Printf(fmt string, v ...interface{})
}
// Shell runs an interactive secure shell over an existing
// port-forwarding session. It runs until the shell is terminated
// (including by cancellation of the context).
func Shell(
ctx context.Context, p printer, sshArgs []string, command []string, port int, destination string, printConnDetails bool,
) error {
cmd, connArgs, err := newSSHCommand(ctx, port, destination, sshArgs, command)
if err != nil {
return fmt.Errorf("failed to create ssh command: %w", err)
}
if printConnDetails {
p.Printf("Connection Details: ssh %s %s", destination, connArgs)
}
return cmd.Run()
}
// Copy runs an scp command over the specified port. scpArgs should contain both scp flags
// as well as the list of files to copy, with the flags first.
//
// Remote files indicated by a "remote:" prefix are resolved relative
// to the remote user's home directory, and are subject to shell expansion
// on the remote host; see https://lwn.net/Articles/835962/.
func Copy(ctx context.Context, scpArgs []string, port int, destination string) error {
cmd, err := newSCPCommand(ctx, port, destination, scpArgs)
if err != nil {
return fmt.Errorf("failed to create scp command: %w", err)
}
return cmd.Run()
}
// NewRemoteCommand returns an exec.Cmd that will securely run a shell
// command on the remote machine.
func NewRemoteCommand(ctx context.Context, tunnelPort int, destination string, sshArgs ...string) (*exec.Cmd, error) {
sshArgs, command, err := ParseSSHArgs(sshArgs)
if err != nil {
return nil, err
}
cmd, _, err := newSSHCommand(ctx, tunnelPort, destination, sshArgs, command)
return cmd, err
}
// newSSHCommand populates an exec.Cmd to run a command (or if blank,
// an interactive shell) over ssh.
func newSSHCommand(ctx context.Context, port int, dst string, cmdArgs []string, command []string) (*exec.Cmd, []string, error) {
connArgs := []string{
"-p", strconv.Itoa(port),
"-o", "NoHostAuthenticationForLocalhost=yes",
"-o", "PasswordAuthentication=no",
}
cmdArgs = append(cmdArgs, connArgs...)
cmdArgs = append(cmdArgs, "-C") // Compression
cmdArgs = append(cmdArgs, dst) // user@host
if command != nil {
cmdArgs = append(cmdArgs, command...)
}
exe, err := safeexec.LookPath("ssh")
if err != nil {
return nil, nil, fmt.Errorf("failed to execute ssh: %w", err)
}
cmd := exec.CommandContext(ctx, exe, cmdArgs...)
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
return cmd, connArgs, nil
}
// ParseSSHArgs parses the given array of arguments into two distinct slices of flags and command.
// The ssh command syntax is: ssh [flags] user@host command [args...]
// There is no way to specify the user@host destination as a flag.
// Unfortunately, that means we need to know which user-provided words are
// SSH flags and which are command arguments so that we can place
// them before or after the destination, and that means we need to know all
// the flags and their arities.
func ParseSSHArgs(args []string) (cmdArgs, command []string, err error) {
return parseArgs(args, "bcDeFIiLlmOopRSWw")
}
// newSCPCommand populates an exec.Cmd to run an scp command for the files specified in cmdArgs.
// cmdArgs is parsed such that scp flags precede the files to copy in the command.
// For example: scp -F ./config local/file remote:file
func newSCPCommand(ctx context.Context, port int, dst string, cmdArgs []string) (*exec.Cmd, error) {
connArgs := []string{
"-P", strconv.Itoa(port),
"-o", "NoHostAuthenticationForLocalhost=yes",
"-o", "PasswordAuthentication=no",
"-C", // compression
}
cmdArgs, command, err := parseSCPArgs(cmdArgs)
if err != nil {
return nil, err
}
cmdArgs = append(cmdArgs, connArgs...)
for _, arg := range command {
// Replace "remote:" prefix with (e.g.) "root@localhost:".
if rest := strings.TrimPrefix(arg, "remote:"); rest != arg {
arg = dst + ":" + rest
}
cmdArgs = append(cmdArgs, arg)
}
exe, err := safeexec.LookPath("scp")
if err != nil {
return nil, fmt.Errorf("failed to execute scp: %w", err)
}
// Beware: invalid syntax causes scp to exit 1 with
// no error message, so don't let that happen.
cmd := exec.CommandContext(ctx, exe, cmdArgs...)
cmd.Stdin = nil
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
return cmd, nil
}
func parseSCPArgs(args []string) (cmdArgs, command []string, err error) {
return parseArgs(args, "cFiJloPS")
}
// parseArgs parses arguments into two distinct slices of flags and command. Parsing stops
// as soon as a non-flag argument is found assuming the remaining arguments are the command.
// It returns an error if a unary flag is provided without an argument.
func parseArgs(args []string, unaryFlags string) (cmdArgs, command []string, err error) {
for i := 0; i < len(args); i++ {
arg := args[i]
// if we've started parsing the command, set it to the rest of the args
if !strings.HasPrefix(arg, "-") {
command = args[i:]
break
}
cmdArgs = append(cmdArgs, arg)
if len(arg) == 2 && strings.Contains(unaryFlags, arg[1:2]) {
if i++; i == len(args) {
return nil, nil, fmt.Errorf("flag: %s requires an argument", arg)
}
cmdArgs = append(cmdArgs, args[i])
}
}
return cmdArgs, command, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/codespaces_test.go | internal/codespaces/codespaces_test.go | package codespaces
import (
"context"
"net/http"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/internal/codespaces/api"
)
func init() {
// Set the backoff to 0 for testing so that they run quickly
codespaceStatePollingBackoff = backoff.NewConstantBackOff(time.Second * 0)
}
// This is just enough to trick `connectionReady`
var readyCodespace = &api.Codespace{
State: api.CodespaceStateAvailable,
Connection: api.CodespaceConnection{
TunnelProperties: api.TunnelProperties{
ConnectAccessToken: "test",
ManagePortsAccessToken: "test",
ServiceUri: "test",
TunnelId: "test",
ClusterId: "test",
Domain: "test",
},
},
}
func TestWaitUntilCodespaceConnectionReady_WhenAlreadyReady(t *testing.T) {
t.Parallel()
apiClient := &mockApiClient{}
result, err := waitUntilCodespaceConnectionReady(context.Background(), &mockProgressIndicator{}, apiClient, readyCodespace)
if err != nil {
t.Fatalf("Expected nil error, but was %v", err)
}
if result.State != api.CodespaceStateAvailable {
t.Fatalf("Expected final state to be %s, but was %s", api.CodespaceStateAvailable, result.State)
}
}
func TestWaitUntilCodespaceConnectionReady_PollsApi(t *testing.T) {
t.Parallel()
apiClient := &mockApiClient{
onGetCodespace: func() (*api.Codespace, error) {
return readyCodespace, nil
},
}
result, err := waitUntilCodespaceConnectionReady(context.Background(), &mockProgressIndicator{}, apiClient, &api.Codespace{State: api.CodespaceStateStarting})
if err != nil {
t.Fatalf("Expected nil error, but was %v", err)
}
if result.State != api.CodespaceStateAvailable {
t.Fatalf("Expected final state to be %s, but was %s", api.CodespaceStateAvailable, result.State)
}
}
func TestWaitUntilCodespaceConnectionReady_StartsCodespace(t *testing.T) {
t.Parallel()
codespace := &api.Codespace{State: api.CodespaceStateShutdown}
apiClient := &mockApiClient{
onGetCodespace: func() (*api.Codespace, error) {
return codespace, nil
},
onStartCodespace: func() error {
*codespace = *readyCodespace
return nil
},
}
result, err := waitUntilCodespaceConnectionReady(context.Background(), &mockProgressIndicator{}, apiClient, codespace)
if err != nil {
t.Fatalf("Expected nil error, but was %v", err)
}
if result.State != api.CodespaceStateAvailable {
t.Fatalf("Expected final state to be %s, but was %s", api.CodespaceStateAvailable, result.State)
}
}
func TestWaitUntilCodespaceConnectionReady_PollsCodespaceUntilReady(t *testing.T) {
t.Parallel()
codespace := &api.Codespace{State: api.CodespaceStateShutdown}
hasPolled := false
apiClient := &mockApiClient{
onGetCodespace: func() (*api.Codespace, error) {
if hasPolled {
*codespace = *readyCodespace
}
hasPolled = true
return codespace, nil
},
onStartCodespace: func() error {
codespace.State = api.CodespaceStateStarting
return nil
},
}
result, err := waitUntilCodespaceConnectionReady(context.Background(), &mockProgressIndicator{}, apiClient, codespace)
if err != nil {
t.Fatalf("Expected nil error, but was %v", err)
}
if result.State != api.CodespaceStateAvailable {
t.Fatalf("Expected final state to be %s, but was %s", api.CodespaceStateAvailable, result.State)
}
}
func TestWaitUntilCodespaceConnectionReady_WaitsForShutdownBeforeStarting(t *testing.T) {
t.Parallel()
codespace := &api.Codespace{State: api.CodespaceStateShuttingDown}
apiClient := &mockApiClient{
onGetCodespace: func() (*api.Codespace, error) {
// Make sure that we poll at least once before going to shutdown
if codespace.State == api.CodespaceStateShuttingDown {
codespace.State = api.CodespaceStateShutdown
}
return codespace, nil
},
onStartCodespace: func() error {
if codespace.State != api.CodespaceStateShutdown {
t.Fatalf("Codespace started from non-shutdown state: %s", codespace.State)
}
*codespace = *readyCodespace
return nil
},
}
result, err := waitUntilCodespaceConnectionReady(context.Background(), &mockProgressIndicator{}, apiClient, codespace)
if err != nil {
t.Fatalf("Expected nil error, but was %v", err)
}
if result.State != api.CodespaceStateAvailable {
t.Fatalf("Expected final state to be %s, but was %s", api.CodespaceStateAvailable, result.State)
}
}
func TestUntilCodespaceConnectionReady_DoesntStartTwice(t *testing.T) {
t.Parallel()
codespace := &api.Codespace{State: api.CodespaceStateShutdown}
didStart := false
didPollAfterStart := false
apiClient := &mockApiClient{
onGetCodespace: func() (*api.Codespace, error) {
// Make sure that we are in shutdown state for one poll after starting to make sure we don't try to start again
if didPollAfterStart {
*codespace = *readyCodespace
}
if didStart {
didPollAfterStart = true
}
return codespace, nil
},
onStartCodespace: func() error {
if didStart {
t.Fatal("Should not start multiple times")
}
didStart = true
return nil
},
}
result, err := waitUntilCodespaceConnectionReady(context.Background(), &mockProgressIndicator{}, apiClient, codespace)
if err != nil {
t.Fatalf("Expected nil error, but was %v", err)
}
if result.State != api.CodespaceStateAvailable {
t.Fatalf("Expected final state to be %s, but was %s", api.CodespaceStateAvailable, result.State)
}
}
type mockApiClient struct {
onStartCodespace func() error
onGetCodespace func() (*api.Codespace, error)
}
func (m *mockApiClient) StartCodespace(ctx context.Context, name string) error {
if m.onStartCodespace == nil {
panic("onStartCodespace not set and StartCodespace was called")
}
return m.onStartCodespace()
}
func (m *mockApiClient) GetCodespace(ctx context.Context, name string, includeConnection bool) (*api.Codespace, error) {
if m.onGetCodespace == nil {
panic("onGetCodespace not set and GetCodespace was called")
}
return m.onGetCodespace()
}
func (m *mockApiClient) HTTPClient() (*http.Client, error) {
panic("Not implemented")
}
type mockProgressIndicator struct{}
func (m *mockProgressIndicator) StartProgressIndicatorWithLabel(s string) {}
func (m *mockProgressIndicator) StopProgressIndicator() {}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/ssh_test.go | internal/codespaces/ssh_test.go | package codespaces
import (
"fmt"
"testing"
)
type parseTestCase struct {
Args []string
ParsedArgs []string
Command []string
Error string
}
func TestParseSSHArgs(t *testing.T) {
testCases := []parseTestCase{
{}, // empty test case
{
Args: []string{"-X", "-Y"},
ParsedArgs: []string{"-X", "-Y"},
Command: nil,
},
{
Args: []string{"-X", "-Y", "-o", "someoption=test"},
ParsedArgs: []string{"-X", "-Y", "-o", "someoption=test"},
Command: nil,
},
{
Args: []string{"-X", "-Y", "-o", "someoption=test", "somecommand"},
ParsedArgs: []string{"-X", "-Y", "-o", "someoption=test"},
Command: []string{"somecommand"},
},
{
Args: []string{"-X", "-Y", "-o", "someoption=test", "echo", "test"},
ParsedArgs: []string{"-X", "-Y", "-o", "someoption=test"},
Command: []string{"echo", "test"},
},
{
Args: []string{"somecommand"},
ParsedArgs: []string{},
Command: []string{"somecommand"},
},
{
Args: []string{"echo", "test"},
ParsedArgs: []string{},
Command: []string{"echo", "test"},
},
{
Args: []string{"-v", "echo", "hello", "world"},
ParsedArgs: []string{"-v"},
Command: []string{"echo", "hello", "world"},
},
{
Args: []string{"-L", "-l"},
ParsedArgs: []string{"-L", "-l"},
Command: nil,
},
{
Args: []string{"-v", "echo", "-n", "test"},
ParsedArgs: []string{"-v"},
Command: []string{"echo", "-n", "test"},
},
{
Args: []string{"-v", "echo", "-b", "test"},
ParsedArgs: []string{"-v"},
Command: []string{"echo", "-b", "test"},
},
{
Args: []string{"-b"},
ParsedArgs: nil,
Command: nil,
Error: "flag: -b requires an argument",
},
}
for _, tcase := range testCases {
args, command, err := ParseSSHArgs(tcase.Args)
checkParseResult(t, tcase, args, command, err)
}
}
func TestParseSCPArgs(t *testing.T) {
testCases := []parseTestCase{
{}, // empty test case
{
Args: []string{"-X", "-Y"},
ParsedArgs: []string{"-X", "-Y"},
Command: nil,
},
{
Args: []string{"-X", "-Y", "-o", "someoption=test"},
ParsedArgs: []string{"-X", "-Y", "-o", "someoption=test"},
Command: nil,
},
{
Args: []string{"-X", "-Y", "-o", "someoption=test", "local/file", "remote:file"},
ParsedArgs: []string{"-X", "-Y", "-o", "someoption=test"},
Command: []string{"local/file", "remote:file"},
},
{
Args: []string{"-X", "-Y", "-o", "someoption=test", "local/file", "remote:file"},
ParsedArgs: []string{"-X", "-Y", "-o", "someoption=test"},
Command: []string{"local/file", "remote:file"},
},
{
Args: []string{"local/file", "remote:file"},
ParsedArgs: []string{},
Command: []string{"local/file", "remote:file"},
},
{
Args: []string{"-c"},
ParsedArgs: nil,
Command: nil,
Error: "flag: -c requires an argument",
},
}
for _, tcase := range testCases {
args, command, err := parseSCPArgs(tcase.Args)
checkParseResult(t, tcase, args, command, err)
}
}
func checkParseResult(t *testing.T, tcase parseTestCase, gotArgs, gotCmd []string, gotErr error) {
if tcase.Error != "" {
if gotErr == nil {
t.Errorf("expected error and got nil: %#v", tcase)
}
if gotErr.Error() != tcase.Error {
t.Errorf("error does not match expected error, got: '%s', expected: '%s'", gotErr.Error(), tcase.Error)
}
return
}
if gotErr != nil {
t.Errorf("unexpected error: %v on test case: %#v", gotErr, tcase)
return
}
argsStr, parsedArgsStr := fmt.Sprintf("%s", gotArgs), fmt.Sprintf("%s", tcase.ParsedArgs)
if argsStr != parsedArgsStr {
t.Errorf("args do not match parsed args. got: '%s', expected: '%s'", argsStr, parsedArgsStr)
}
commandStr, parsedCommandStr := fmt.Sprintf("%s", gotCmd), fmt.Sprintf("%s", tcase.Command)
if commandStr != parsedCommandStr {
t.Errorf("command does not match parsed command. got: '%s', expected: '%s'", commandStr, parsedCommandStr)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/codespaces.go | internal/codespaces/codespaces.go | package codespaces
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/codespaces/connection"
)
// codespaceStatePollingBackoff is the delay between state polls while waiting for codespaces to become
// available. It's only exposed so that it can be shortened for testing, otherwise it should not be changed
var codespaceStatePollingBackoff backoff.BackOff = backoff.NewExponentialBackOff(
backoff.WithInitialInterval(1*time.Second),
backoff.WithMultiplier(1.02),
backoff.WithMaxInterval(10*time.Second),
backoff.WithMaxElapsedTime(5*time.Minute),
)
func connectionReady(codespace *api.Codespace) bool {
// If the codespace is not available, it is not ready
if codespace.State != api.CodespaceStateAvailable {
return false
}
return codespace.Connection.TunnelProperties.ConnectAccessToken != "" &&
codespace.Connection.TunnelProperties.ManagePortsAccessToken != "" &&
codespace.Connection.TunnelProperties.ServiceUri != "" &&
codespace.Connection.TunnelProperties.TunnelId != "" &&
codespace.Connection.TunnelProperties.ClusterId != "" &&
codespace.Connection.TunnelProperties.Domain != ""
}
type apiClient interface {
GetCodespace(ctx context.Context, name string, includeConnection bool) (*api.Codespace, error)
StartCodespace(ctx context.Context, name string) error
HTTPClient() (*http.Client, error)
}
type progressIndicator interface {
StartProgressIndicatorWithLabel(s string)
StopProgressIndicator()
}
type TimeoutError struct {
message string
}
func (e *TimeoutError) Error() string {
return e.message
}
// GetCodespaceConnection waits until a codespace is able
// to be connected to and initializes a connection to it.
func GetCodespaceConnection(ctx context.Context, progress progressIndicator, apiClient apiClient, codespace *api.Codespace) (*connection.CodespaceConnection, error) {
codespace, err := waitUntilCodespaceConnectionReady(ctx, progress, apiClient, codespace)
if err != nil {
return nil, err
}
progress.StartProgressIndicatorWithLabel("Connecting to codespace")
defer progress.StopProgressIndicator()
httpClient, err := apiClient.HTTPClient()
if err != nil {
return nil, fmt.Errorf("error getting http client: %w", err)
}
return connection.NewCodespaceConnection(ctx, codespace, httpClient)
}
// waitUntilCodespaceConnectionReady waits for a Codespace to be running and is able to be connected to.
func waitUntilCodespaceConnectionReady(ctx context.Context, progress progressIndicator, apiClient apiClient, codespace *api.Codespace) (*api.Codespace, error) {
if connectionReady(codespace) {
return codespace, nil
}
progress.StartProgressIndicatorWithLabel("Waiting for codespace to become ready")
defer progress.StopProgressIndicator()
lastState := ""
firstRetry := true
err := backoff.Retry(func() error {
var err error
if firstRetry {
firstRetry = false
} else {
codespace, err = apiClient.GetCodespace(ctx, codespace.Name, true)
if err != nil {
return backoff.Permanent(fmt.Errorf("error getting codespace: %w", err))
}
}
if connectionReady(codespace) {
return nil
}
// Only react to changes in the state (so that we don't try to start the codespace twice)
if codespace.State != lastState {
if codespace.State == api.CodespaceStateShutdown {
err = apiClient.StartCodespace(ctx, codespace.Name)
if err != nil {
return backoff.Permanent(fmt.Errorf("error starting codespace: %w", err))
}
}
}
lastState = codespace.State
return &TimeoutError{message: "codespace not ready yet"}
}, backoff.WithContext(codespaceStatePollingBackoff, ctx))
if err != nil {
var timeoutErr *TimeoutError
if errors.As(err, &timeoutErr) {
return nil, errors.New("timed out while waiting for the codespace to start")
}
return nil, err
}
return codespace, nil
}
// ListenTCP starts a localhost tcp listener on 127.0.0.1 (unless allInterfaces is true) and returns the listener and bound port
func ListenTCP(port int, allInterfaces bool) (*net.TCPListener, int, error) {
host := "127.0.0.1"
if allInterfaces {
host = ""
}
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", host, port))
if err != nil {
return nil, 0, fmt.Errorf("failed to build tcp address: %w", err)
}
listener, err := net.ListenTCP("tcp", addr)
if err != nil {
return nil, 0, fmt.Errorf("failed to listen to local port over tcp: %w", err)
}
port = listener.Addr().(*net.TCPAddr).Port
return listener, port, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/states.go | internal/codespaces/states.go | package codespaces
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"time"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/codespaces/rpc"
"github.com/cli/cli/v2/internal/text"
)
// PostCreateStateStatus is a string value representing the different statuses a state can have.
type PostCreateStateStatus string
func (p PostCreateStateStatus) String() string {
return text.Title(string(p))
}
const (
PostCreateStateRunning PostCreateStateStatus = "running"
PostCreateStateSuccess PostCreateStateStatus = "succeeded"
PostCreateStateFailed PostCreateStateStatus = "failed"
)
// PostCreateState is a combination of a state and status value that is captured
// during codespace creation.
type PostCreateState struct {
Name string `json:"name"`
Status PostCreateStateStatus `json:"status"`
}
// PollPostCreateStates watches for state changes in a codespace,
// and calls the supplied poller for each batch of state changes.
// It runs until it encounters an error, including cancellation of the context.
func PollPostCreateStates(ctx context.Context, progress progressIndicator, apiClient apiClient, codespace *api.Codespace, poller func([]PostCreateState)) (err error) {
codespaceConnection, err := GetCodespaceConnection(ctx, progress, apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
// Ensure local port is listening before client (getPostCreateOutput) connects.
listen, localPort, err := ListenTCP(0, false)
if err != nil {
return err
}
progress.StartProgressIndicatorWithLabel("Fetching SSH Details")
invoker, err := rpc.CreateInvoker(ctx, fwd)
if err != nil {
return err
}
defer safeClose(invoker, &err)
remoteSSHServerPort, sshUser, err := invoker.StartSSHServer(ctx)
if err != nil {
return fmt.Errorf("error getting ssh server details: %w", err)
}
progress.StopProgressIndicator()
progress.StartProgressIndicatorWithLabel("Fetching status")
tunnelClosed := make(chan error, 1) // buffered to avoid sender stuckness
go func() {
opts := portforwarder.ForwardPortOpts{
Port: remoteSSHServerPort,
Internal: true,
}
tunnelClosed <- fwd.ForwardPortToListener(ctx, opts, listen)
}()
t := time.NewTicker(1 * time.Second)
defer t.Stop()
for ticks := 0; ; ticks++ {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-tunnelClosed:
return fmt.Errorf("connection failed: %w", err)
case <-t.C:
states, err := getPostCreateOutput(ctx, localPort, sshUser)
// There is an active progress indicator before the first tick
// to show that we are fetching statuses.
// Once the first tick happens, we stop the indicator and let
// the subsequent post create states manage their own progress.
if ticks == 0 {
progress.StopProgressIndicator()
}
if err != nil {
return fmt.Errorf("get post create output: %w", err)
}
poller(states)
}
}
}
func getPostCreateOutput(ctx context.Context, tunnelPort int, user string) ([]PostCreateState, error) {
cmd, err := NewRemoteCommand(
ctx, tunnelPort, fmt.Sprintf("%s@localhost", user),
"cat /workspaces/.codespaces/shared/postCreateOutput.json",
)
if err != nil {
return nil, fmt.Errorf("remote command: %w", err)
}
stdout := new(bytes.Buffer)
cmd.Stdout = stdout
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("run command: %w", err)
}
var output struct {
Steps []PostCreateState `json:"steps"`
}
if err := json.Unmarshal(stdout.Bytes(), &output); err != nil {
return nil, fmt.Errorf("unmarshal output: %w", err)
}
return output.Steps, nil
}
func safeClose(closer io.Closer, err *error) {
if closeErr := closer.Close(); *err == nil {
*err = closeErr
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/invoker_test.go | internal/codespaces/rpc/invoker_test.go | package rpc
import (
"context"
"fmt"
"net"
"strconv"
"testing"
"github.com/cli/cli/v2/internal/codespaces/rpc/codespace"
"github.com/cli/cli/v2/internal/codespaces/rpc/jupyter"
"github.com/cli/cli/v2/internal/codespaces/rpc/ssh"
rpctest "github.com/cli/cli/v2/internal/codespaces/rpc/test"
"google.golang.org/grpc"
)
type mockServer struct {
jupyter.JupyterServerHostServerMock
codespace.CodespaceHostServerMock
ssh.SshServerHostServerMock
}
func newMockServer() *mockServer {
server := &mockServer{}
server.CodespaceHostServerMock.NotifyCodespaceOfClientActivityFunc = func(context.Context, *codespace.NotifyCodespaceOfClientActivityRequest) (*codespace.NotifyCodespaceOfClientActivityResponse, error) {
return &codespace.NotifyCodespaceOfClientActivityResponse{
Message: "",
Result: true,
}, nil
}
return server
}
// runTestGrpcServer serves grpc requests over the provided Listener using the mockServer for mocked callbacks.
// It does not return until the Context is cancelled and the server fully shuts down.
func runTestGrpcServer(ctx context.Context, listener net.Listener, server *mockServer) error {
s := grpc.NewServer()
jupyter.RegisterJupyterServerHostServer(s, server)
codespace.RegisterCodespaceHostServer(s, server)
ssh.RegisterSshServerHostServer(s, server)
ch := make(chan error, 1)
go func() { ch <- s.Serve(listener) }()
select {
case <-ctx.Done():
s.Stop()
<-ch
return nil
case err := <-ch:
return err
}
}
// createTestInvoker is the main test setup function. It returns an Invoker using the provided mockServer, as well as a shutdown function.
// The Invoker does not need to be closed directly, that will be handled by the shutdown function.
func createTestInvoker(t *testing.T, server *mockServer) (Invoker, func(), error) {
listener, err := net.Listen("tcp", "127.0.0.1:16634")
if err != nil {
return nil, nil, fmt.Errorf("failed to listen: %w", err)
}
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan error)
go func() { ch <- runTestGrpcServer(ctx, listener, server) }()
close := func() {
cancel()
<-ch
listener.Close()
}
// Create a new invoker with a mock port forwarder
invoker, err := CreateInvoker(context.Background(), rpctest.PortForwarder{})
if err != nil {
close()
return nil, nil, fmt.Errorf("error connecting to internal server: %w", err)
}
return invoker, func() {
invoker.Close()
close()
}, nil
}
// Test that the RPC invoker notifies the codespace of client activity on connection
func verifyNotifyCodespaceOfClientActivity(t *testing.T, server *mockServer) {
calls := server.CodespaceHostServerMock.NotifyCodespaceOfClientActivityCalls()
if len(calls) == 0 {
t.Fatalf("no client activity calls")
}
for _, call := range calls {
activities := call.NotifyCodespaceOfClientActivityRequest.GetClientActivities()
if activities[0] == connectedEventName {
return
}
}
t.Fatalf("no activity named %s", connectedEventName)
}
// Test that the RPC invoker returns the correct port and URL when the JupyterLab server starts successfully
func TestStartJupyterServerSuccess(t *testing.T) {
resp := jupyter.GetRunningServerResponse{
Port: strconv.Itoa(1234),
ServerUrl: "http://localhost:1234?token=1234",
Message: "",
Result: true,
}
server := newMockServer()
server.JupyterServerHostServerMock.GetRunningServerFunc = func(context.Context, *jupyter.GetRunningServerRequest) (*jupyter.GetRunningServerResponse, error) {
return &resp, nil
}
invoker, stop, err := createTestInvoker(t, server)
if err != nil {
t.Fatalf("error connecting to internal server: %v", err)
}
defer stop()
port, url, err := invoker.StartJupyterServer(context.Background())
if err != nil {
t.Fatalf("expected %v, got %v", nil, err)
}
if strconv.Itoa(port) != resp.Port {
t.Fatalf("expected %s, got %d", resp.Port, port)
}
if url != resp.ServerUrl {
t.Fatalf("expected %s, got %s", resp.ServerUrl, url)
}
verifyNotifyCodespaceOfClientActivity(t, server)
}
// Test that the RPC invoker returns an error when the JupyterLab server fails to start
func TestStartJupyterServerFailure(t *testing.T) {
resp := jupyter.GetRunningServerResponse{
Port: strconv.Itoa(1234),
ServerUrl: "http://localhost:1234?token=1234",
Message: "error message",
Result: false,
}
server := newMockServer()
server.JupyterServerHostServerMock.GetRunningServerFunc = func(context.Context, *jupyter.GetRunningServerRequest) (*jupyter.GetRunningServerResponse, error) {
return &resp, nil
}
invoker, stop, err := createTestInvoker(t, server)
if err != nil {
t.Fatalf("error connecting to internal server: %v", err)
}
defer stop()
errorMessage := fmt.Sprintf("failed to start JupyterLab: %s", resp.Message)
port, url, err := invoker.StartJupyterServer(context.Background())
if err.Error() != errorMessage {
t.Fatalf("expected %v, got %v", errorMessage, err)
}
if port != 0 {
t.Fatalf("expected %d, got %d", 0, port)
}
if url != "" {
t.Fatalf("expected %s, got %s", "", url)
}
verifyNotifyCodespaceOfClientActivity(t, server)
}
// Test that the RPC invoker doesn't throw an error when requesting an incremental rebuild
func TestRebuildContainerIncremental(t *testing.T) {
resp := codespace.RebuildContainerResponse{
RebuildContainer: true,
}
server := newMockServer()
server.RebuildContainerAsyncFunc = func(context.Context, *codespace.RebuildContainerRequest) (*codespace.RebuildContainerResponse, error) {
return &resp, nil
}
invoker, stop, err := createTestInvoker(t, server)
if err != nil {
t.Fatalf("error connecting to internal server: %v", err)
}
defer stop()
err = invoker.RebuildContainer(context.Background(), false)
if err != nil {
t.Fatalf("expected %v, got %v", nil, err)
}
verifyNotifyCodespaceOfClientActivity(t, server)
}
// Test that the RPC invoker doesn't throw an error when requesting a full rebuild
func TestRebuildContainerFull(t *testing.T) {
resp := codespace.RebuildContainerResponse{
RebuildContainer: true,
}
server := newMockServer()
server.RebuildContainerAsyncFunc = func(context.Context, *codespace.RebuildContainerRequest) (*codespace.RebuildContainerResponse, error) {
return &resp, nil
}
invoker, stop, err := createTestInvoker(t, server)
if err != nil {
t.Fatalf("error connecting to internal server: %v", err)
}
defer stop()
err = invoker.RebuildContainer(context.Background(), true)
if err != nil {
t.Fatalf("expected %v, got %v", nil, err)
}
verifyNotifyCodespaceOfClientActivity(t, server)
}
// Test that the RPC invoker throws an error when the rebuild fails
func TestRebuildContainerFailure(t *testing.T) {
resp := codespace.RebuildContainerResponse{
RebuildContainer: false,
}
server := newMockServer()
server.RebuildContainerAsyncFunc = func(context.Context, *codespace.RebuildContainerRequest) (*codespace.RebuildContainerResponse, error) {
return &resp, nil
}
invoker, stop, err := createTestInvoker(t, server)
if err != nil {
t.Fatalf("error connecting to internal server: %v", err)
}
defer stop()
errorMessage := "couldn't rebuild codespace"
err = invoker.RebuildContainer(context.Background(), true)
if err.Error() != errorMessage {
t.Fatalf("expected %v, got %v", errorMessage, err)
}
}
// Test that the RPC invoker returns the correct port and user when the SSH server starts successfully
func TestStartSSHServerSuccess(t *testing.T) {
resp := ssh.StartRemoteServerResponse{
ServerPort: strconv.Itoa(1234),
User: "test",
Message: "",
Result: true,
}
server := newMockServer()
server.StartRemoteServerAsyncFunc = func(context.Context, *ssh.StartRemoteServerRequest) (*ssh.StartRemoteServerResponse, error) {
return &resp, nil
}
invoker, stop, err := createTestInvoker(t, server)
if err != nil {
t.Fatalf("error connecting to internal server: %v", err)
}
defer stop()
port, user, err := invoker.StartSSHServer(context.Background())
if err != nil {
t.Fatalf("expected %v, got %v", nil, err)
}
if strconv.Itoa(port) != resp.ServerPort {
t.Fatalf("expected %s, got %d", resp.ServerPort, port)
}
if user != resp.User {
t.Fatalf("expected %s, got %s", resp.User, user)
}
verifyNotifyCodespaceOfClientActivity(t, server)
}
// Test that the RPC invoker returns an error when the SSH server fails to start
func TestStartSSHServerFailure(t *testing.T) {
resp := ssh.StartRemoteServerResponse{
ServerPort: strconv.Itoa(1234),
User: "test",
Message: "error message",
Result: false,
}
server := newMockServer()
server.StartRemoteServerAsyncFunc = func(context.Context, *ssh.StartRemoteServerRequest) (*ssh.StartRemoteServerResponse, error) {
return &resp, nil
}
invoker, stop, err := createTestInvoker(t, server)
if err != nil {
t.Fatalf("error connecting to internal server: %v", err)
}
defer stop()
errorMessage := fmt.Sprintf("failed to start SSH server: %s", resp.Message)
port, user, err := invoker.StartSSHServer(context.Background())
if err.Error() != errorMessage {
t.Fatalf("expected %v, got %v", errorMessage, err)
}
if port != 0 {
t.Fatalf("expected %d, got %d", 0, port)
}
if user != "" {
t.Fatalf("expected %s, got %s", "", user)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/invoker.go | internal/codespaces/rpc/invoker.go | package rpc
// gRPC client implementation to be able to connect to the gRPC server and perform the following operations:
// - Start a remote JupyterLab server
import (
"context"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/codespaces/rpc/codespace"
"github.com/cli/cli/v2/internal/codespaces/rpc/jupyter"
"github.com/cli/cli/v2/internal/codespaces/rpc/ssh"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
)
const (
ConnectionTimeout = 5 * time.Second
requestTimeout = 30 * time.Second
)
const (
codespacesInternalPort = 16634
codespacesInternalSessionName = "CodespacesInternal"
clientName = "gh"
connectedEventName = "connected"
keepAliveEventName = "keepAlive"
)
type StartSSHServerOptions struct {
UserPublicKeyFile string
}
type Invoker interface {
Close() error
StartJupyterServer(ctx context.Context) (int, string, error)
RebuildContainer(ctx context.Context, full bool) error
StartSSHServer(ctx context.Context) (int, string, error)
StartSSHServerWithOptions(ctx context.Context, options StartSSHServerOptions) (int, string, error)
KeepAlive()
}
type invoker struct {
conn *grpc.ClientConn
fwd portforwarder.PortForwarder
listener net.Listener
jupyterClient jupyter.JupyterServerHostClient
codespaceClient codespace.CodespaceHostClient
sshClient ssh.SshServerHostClient
cancelPF context.CancelFunc
keepAliveOverride bool
}
// Connects to the internal RPC server and returns a new invoker for it
func CreateInvoker(ctx context.Context, fwd portforwarder.PortForwarder) (Invoker, error) {
ctx, cancel := context.WithTimeout(ctx, ConnectionTimeout)
defer cancel()
invoker, err := connect(ctx, fwd)
if err != nil {
return nil, fmt.Errorf("error connecting to internal server: %w", err)
}
return invoker, nil
}
// Finds a free port to listen on and creates a new RPC invoker that connects to that port
func connect(ctx context.Context, fwd portforwarder.PortForwarder) (Invoker, error) {
listener, err := listenTCP()
if err != nil {
return nil, err
}
localAddress := listener.Addr().String()
invoker := &invoker{
fwd: fwd,
listener: listener,
}
// Create a cancelable context to be able to cancel background tasks
// if we encounter an error while connecting to the gRPC server
connectctx, cancel := context.WithCancel(context.Background())
defer func() {
if err != nil {
cancel()
}
}()
ch := make(chan error, 2) // Buffered channel to ensure we don't block on the goroutine
// Ensure we close the port forwarder if we encounter an error
// or once the gRPC connection is closed. pfcancel is retained
// to close the PF whenever we close the gRPC connection.
pfctx, pfcancel := context.WithCancel(connectctx)
invoker.cancelPF = pfcancel
// Tunnel the remote gRPC server port to the local port
go func() {
// Start forwarding the port locally
opts := portforwarder.ForwardPortOpts{
Port: codespacesInternalPort,
Internal: true,
}
ch <- fwd.ForwardPortToListener(pfctx, opts, listener)
}()
var conn *grpc.ClientConn
go func() {
// Attempt to connect to the port
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
}
conn, err = grpc.NewClient(localAddress, opts...)
ch <- err // nil if we successfully connected
}()
// Wait for the connection to be established or for the context to be cancelled
select {
case <-ctx.Done():
return nil, ctx.Err()
case err := <-ch:
if err != nil {
return nil, err
}
}
invoker.conn = conn
invoker.jupyterClient = jupyter.NewJupyterServerHostClient(conn)
invoker.codespaceClient = codespace.NewCodespaceHostClient(conn)
invoker.sshClient = ssh.NewSshServerHostClient(conn)
// Send initial connection heartbeat (no need to throw if we fail to get a response from the server)
_ = invoker.notifyCodespaceOfClientActivity(ctx, connectedEventName)
// Start the activity heatbeats
go invoker.heartbeat(pfctx, 1*time.Minute)
return invoker, nil
}
// Closes the gRPC connection
func (i *invoker) Close() error {
i.cancelPF()
// Closing the local listener effectively closes the gRPC connection
if err := i.listener.Close(); err != nil {
i.conn.Close() // If we fail to close the listener, explicitly close the gRPC connection and ignore any error
return fmt.Errorf("failed to close local tcp port listener: %w", err)
}
return nil
}
// Appends the authentication token to the gRPC context
func (i *invoker) appendMetadata(ctx context.Context) context.Context {
return metadata.AppendToOutgoingContext(ctx, "Authorization", "Bearer token")
}
// Starts a remote JupyterLab server to allow the user to connect to the codespace via JupyterLab in their browser
func (i *invoker) StartJupyterServer(ctx context.Context) (port int, serverUrl string, err error) {
ctx = i.appendMetadata(ctx)
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
response, err := i.jupyterClient.GetRunningServer(ctx, &jupyter.GetRunningServerRequest{})
if err != nil {
return 0, "", fmt.Errorf("failed to invoke JupyterLab RPC: %w", err)
}
if !response.Result {
return 0, "", fmt.Errorf("failed to start JupyterLab: %s", response.Message)
}
port, err = strconv.Atoi(response.Port)
if err != nil {
return 0, "", fmt.Errorf("failed to parse JupyterLab port: %w", err)
}
return port, response.ServerUrl, err
}
// Rebuilds the container using cached layers by default or from scratch if full is true
func (i *invoker) RebuildContainer(ctx context.Context, full bool) error {
ctx = i.appendMetadata(ctx)
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
// If full is true, we want to pass false to the RPC call to indicate that we want to do a full rebuild
incremental := !full
response, err := i.codespaceClient.RebuildContainerAsync(ctx, &codespace.RebuildContainerRequest{Incremental: &incremental})
if err != nil {
return fmt.Errorf("failed to invoke rebuild RPC: %w", err)
}
if !response.RebuildContainer {
return fmt.Errorf("couldn't rebuild codespace")
}
return nil
}
// Starts a remote SSH server to allow the user to connect to the codespace via SSH
func (i *invoker) StartSSHServer(ctx context.Context) (int, string, error) {
return i.StartSSHServerWithOptions(ctx, StartSSHServerOptions{})
}
// Starts a remote SSH server to allow the user to connect to the codespace via SSH
func (i *invoker) StartSSHServerWithOptions(ctx context.Context, options StartSSHServerOptions) (int, string, error) {
ctx = i.appendMetadata(ctx)
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
userPublicKey := ""
if options.UserPublicKeyFile != "" {
publicKeyBytes, err := os.ReadFile(options.UserPublicKeyFile)
if err != nil {
return 0, "", fmt.Errorf("failed to read public key file: %w", err)
}
userPublicKey = strings.TrimSpace(string(publicKeyBytes))
}
response, err := i.sshClient.StartRemoteServerAsync(ctx, &ssh.StartRemoteServerRequest{UserPublicKey: userPublicKey})
if err != nil {
return 0, "", fmt.Errorf("failed to invoke SSH RPC: %w", err)
}
if !response.Result {
return 0, "", fmt.Errorf("failed to start SSH server: %s", response.Message)
}
port, err := strconv.Atoi(response.ServerPort)
if err != nil {
return 0, "", fmt.Errorf("failed to parse SSH server port: %w", err)
}
if !isUsernameValid(response.User) {
return 0, "", fmt.Errorf("invalid username: %s", response.User)
}
return port, response.User, nil
}
func listenTCP() (*net.TCPListener, error) {
// We will end up using this same address to connect, so specify the IP also or the connect will fail
addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
if err != nil {
return nil, fmt.Errorf("failed to build tcp address: %w", err)
}
listener, err := net.ListenTCP("tcp", addr)
if err != nil {
return nil, fmt.Errorf("failed to listen to local port over tcp: %w", err)
}
return listener, nil
}
// KeepAlive sets a flag to continuously send activity signals to
// the codespace even if there is no other activity (e.g. stdio)
func (i *invoker) KeepAlive() {
i.keepAliveOverride = true
}
// Periodically check whether there is a reason to keep the connection alive, and if so, notify the codespace to do so
func (i *invoker) heartbeat(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
reason := ""
// If the keep alive override flag is set, we don't need to check for activity on the forwarder
// Otherwise, grab the reason from the forwarder
if i.keepAliveOverride {
reason = keepAliveEventName
} else {
reason = i.fwd.GetKeepAliveReason()
}
_ = i.notifyCodespaceOfClientActivity(ctx, reason)
}
}
}
func (i *invoker) notifyCodespaceOfClientActivity(ctx context.Context, activity string) error {
ctx = i.appendMetadata(ctx)
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
_, err := i.codespaceClient.NotifyCodespaceOfClientActivity(ctx, &codespace.NotifyCodespaceOfClientActivityRequest{ClientId: clientName, ClientActivities: []string{activity}})
if err != nil {
return fmt.Errorf("failed to invoke notify RPC: %w", err)
}
return nil
}
func isUsernameValid(username string) bool {
// assuming valid usernames are alphanumeric, with these special characters allowed: . _ -
var validUsernamePattern = `^[a-zA-Z0-9_][-.a-zA-Z0-9_]*$`
re := regexp.MustCompile(validUsernamePattern)
return re.MatchString(username)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/jupyter/jupyter_server_host_service.v1_grpc.pb.go | internal/codespaces/rpc/jupyter/jupyter_server_host_service.v1_grpc.pb.go | // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v3.12.4
// source: jupyter/jupyter_server_host_service.v1.proto
package jupyter
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// JupyterServerHostClient is the client API for JupyterServerHost service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type JupyterServerHostClient interface {
GetRunningServer(ctx context.Context, in *GetRunningServerRequest, opts ...grpc.CallOption) (*GetRunningServerResponse, error)
}
type jupyterServerHostClient struct {
cc grpc.ClientConnInterface
}
func NewJupyterServerHostClient(cc grpc.ClientConnInterface) JupyterServerHostClient {
return &jupyterServerHostClient{cc}
}
func (c *jupyterServerHostClient) GetRunningServer(ctx context.Context, in *GetRunningServerRequest, opts ...grpc.CallOption) (*GetRunningServerResponse, error) {
out := new(GetRunningServerResponse)
err := c.cc.Invoke(ctx, "/Codespaces.Grpc.JupyterServerHostService.v1.JupyterServerHost/GetRunningServer", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// JupyterServerHostServer is the server API for JupyterServerHost service.
// All implementations must embed UnimplementedJupyterServerHostServer
// for forward compatibility
type JupyterServerHostServer interface {
GetRunningServer(context.Context, *GetRunningServerRequest) (*GetRunningServerResponse, error)
mustEmbedUnimplementedJupyterServerHostServer()
}
// UnimplementedJupyterServerHostServer must be embedded to have forward compatible implementations.
type UnimplementedJupyterServerHostServer struct {
}
func (UnimplementedJupyterServerHostServer) GetRunningServer(context.Context, *GetRunningServerRequest) (*GetRunningServerResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetRunningServer not implemented")
}
func (UnimplementedJupyterServerHostServer) mustEmbedUnimplementedJupyterServerHostServer() {}
// UnsafeJupyterServerHostServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to JupyterServerHostServer will
// result in compilation errors.
type UnsafeJupyterServerHostServer interface {
mustEmbedUnimplementedJupyterServerHostServer()
}
func RegisterJupyterServerHostServer(s grpc.ServiceRegistrar, srv JupyterServerHostServer) {
s.RegisterService(&JupyterServerHost_ServiceDesc, srv)
}
func _JupyterServerHost_GetRunningServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetRunningServerRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(JupyterServerHostServer).GetRunningServer(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/Codespaces.Grpc.JupyterServerHostService.v1.JupyterServerHost/GetRunningServer",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(JupyterServerHostServer).GetRunningServer(ctx, req.(*GetRunningServerRequest))
}
return interceptor(ctx, in, info, handler)
}
// JupyterServerHost_ServiceDesc is the grpc.ServiceDesc for JupyterServerHost service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var JupyterServerHost_ServiceDesc = grpc.ServiceDesc{
ServiceName: "Codespaces.Grpc.JupyterServerHostService.v1.JupyterServerHost",
HandlerType: (*JupyterServerHostServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetRunningServer",
Handler: _JupyterServerHost_GetRunningServer_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "jupyter/jupyter_server_host_service.v1.proto",
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/jupyter/jupyter_server_host_service.v1.proto.mock.go | internal/codespaces/rpc/jupyter/jupyter_server_host_service.v1.proto.mock.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package jupyter
import (
context "context"
sync "sync"
)
// Ensure, that JupyterServerHostServerMock does implement JupyterServerHostServer.
// If this is not the case, regenerate this file with moq.
var _ JupyterServerHostServer = &JupyterServerHostServerMock{}
// JupyterServerHostServerMock is a mock implementation of JupyterServerHostServer.
//
// func TestSomethingThatUsesJupyterServerHostServer(t *testing.T) {
//
// // make and configure a mocked JupyterServerHostServer
// mockedJupyterServerHostServer := &JupyterServerHostServerMock{
// GetRunningServerFunc: func(contextMoqParam context.Context, getRunningServerRequest *GetRunningServerRequest) (*GetRunningServerResponse, error) {
// panic("mock out the GetRunningServer method")
// },
// mustEmbedUnimplementedJupyterServerHostServerFunc: func() {
// panic("mock out the mustEmbedUnimplementedJupyterServerHostServer method")
// },
// }
//
// // use mockedJupyterServerHostServer in code that requires JupyterServerHostServer
// // and then make assertions.
//
// }
type JupyterServerHostServerMock struct {
// GetRunningServerFunc mocks the GetRunningServer method.
GetRunningServerFunc func(contextMoqParam context.Context, getRunningServerRequest *GetRunningServerRequest) (*GetRunningServerResponse, error)
// mustEmbedUnimplementedJupyterServerHostServerFunc mocks the mustEmbedUnimplementedJupyterServerHostServer method.
mustEmbedUnimplementedJupyterServerHostServerFunc func()
// calls tracks calls to the methods.
calls struct {
// GetRunningServer holds details about calls to the GetRunningServer method.
GetRunningServer []struct {
// ContextMoqParam is the contextMoqParam argument value.
ContextMoqParam context.Context
// GetRunningServerRequest is the getRunningServerRequest argument value.
GetRunningServerRequest *GetRunningServerRequest
}
// mustEmbedUnimplementedJupyterServerHostServer holds details about calls to the mustEmbedUnimplementedJupyterServerHostServer method.
mustEmbedUnimplementedJupyterServerHostServer []struct {
}
}
lockGetRunningServer sync.RWMutex
lockmustEmbedUnimplementedJupyterServerHostServer sync.RWMutex
}
// GetRunningServer calls GetRunningServerFunc.
func (mock *JupyterServerHostServerMock) GetRunningServer(contextMoqParam context.Context, getRunningServerRequest *GetRunningServerRequest) (*GetRunningServerResponse, error) {
if mock.GetRunningServerFunc == nil {
panic("JupyterServerHostServerMock.GetRunningServerFunc: method is nil but JupyterServerHostServer.GetRunningServer was just called")
}
callInfo := struct {
ContextMoqParam context.Context
GetRunningServerRequest *GetRunningServerRequest
}{
ContextMoqParam: contextMoqParam,
GetRunningServerRequest: getRunningServerRequest,
}
mock.lockGetRunningServer.Lock()
mock.calls.GetRunningServer = append(mock.calls.GetRunningServer, callInfo)
mock.lockGetRunningServer.Unlock()
return mock.GetRunningServerFunc(contextMoqParam, getRunningServerRequest)
}
// GetRunningServerCalls gets all the calls that were made to GetRunningServer.
// Check the length with:
//
// len(mockedJupyterServerHostServer.GetRunningServerCalls())
func (mock *JupyterServerHostServerMock) GetRunningServerCalls() []struct {
ContextMoqParam context.Context
GetRunningServerRequest *GetRunningServerRequest
} {
var calls []struct {
ContextMoqParam context.Context
GetRunningServerRequest *GetRunningServerRequest
}
mock.lockGetRunningServer.RLock()
calls = mock.calls.GetRunningServer
mock.lockGetRunningServer.RUnlock()
return calls
}
// mustEmbedUnimplementedJupyterServerHostServer calls mustEmbedUnimplementedJupyterServerHostServerFunc.
func (mock *JupyterServerHostServerMock) mustEmbedUnimplementedJupyterServerHostServer() {
if mock.mustEmbedUnimplementedJupyterServerHostServerFunc == nil {
panic("JupyterServerHostServerMock.mustEmbedUnimplementedJupyterServerHostServerFunc: method is nil but JupyterServerHostServer.mustEmbedUnimplementedJupyterServerHostServer was just called")
}
callInfo := struct {
}{}
mock.lockmustEmbedUnimplementedJupyterServerHostServer.Lock()
mock.calls.mustEmbedUnimplementedJupyterServerHostServer = append(mock.calls.mustEmbedUnimplementedJupyterServerHostServer, callInfo)
mock.lockmustEmbedUnimplementedJupyterServerHostServer.Unlock()
mock.mustEmbedUnimplementedJupyterServerHostServerFunc()
}
// mustEmbedUnimplementedJupyterServerHostServerCalls gets all the calls that were made to mustEmbedUnimplementedJupyterServerHostServer.
// Check the length with:
//
// len(mockedJupyterServerHostServer.mustEmbedUnimplementedJupyterServerHostServerCalls())
func (mock *JupyterServerHostServerMock) mustEmbedUnimplementedJupyterServerHostServerCalls() []struct {
} {
var calls []struct {
}
mock.lockmustEmbedUnimplementedJupyterServerHostServer.RLock()
calls = mock.calls.mustEmbedUnimplementedJupyterServerHostServer
mock.lockmustEmbedUnimplementedJupyterServerHostServer.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/jupyter/jupyter_server_host_service.v1.pb.go | internal/codespaces/rpc/jupyter/jupyter_server_host_service.v1.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v3.12.4
// source: jupyter/jupyter_server_host_service.v1.proto
package jupyter
import (
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)
)
type GetRunningServerRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *GetRunningServerRequest) Reset() {
*x = GetRunningServerRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_jupyter_jupyter_server_host_service_v1_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GetRunningServerRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetRunningServerRequest) ProtoMessage() {}
func (x *GetRunningServerRequest) ProtoReflect() protoreflect.Message {
mi := &file_jupyter_jupyter_server_host_service_v1_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 GetRunningServerRequest.ProtoReflect.Descriptor instead.
func (*GetRunningServerRequest) Descriptor() ([]byte, []int) {
return file_jupyter_jupyter_server_host_service_v1_proto_rawDescGZIP(), []int{0}
}
type GetRunningServerResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Result bool `protobuf:"varint,1,opt,name=Result,proto3" json:"Result,omitempty"`
Message string `protobuf:"bytes,2,opt,name=Message,proto3" json:"Message,omitempty"`
Port string `protobuf:"bytes,3,opt,name=Port,proto3" json:"Port,omitempty"`
ServerUrl string `protobuf:"bytes,4,opt,name=ServerUrl,proto3" json:"ServerUrl,omitempty"`
}
func (x *GetRunningServerResponse) Reset() {
*x = GetRunningServerResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_jupyter_jupyter_server_host_service_v1_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GetRunningServerResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetRunningServerResponse) ProtoMessage() {}
func (x *GetRunningServerResponse) ProtoReflect() protoreflect.Message {
mi := &file_jupyter_jupyter_server_host_service_v1_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 GetRunningServerResponse.ProtoReflect.Descriptor instead.
func (*GetRunningServerResponse) Descriptor() ([]byte, []int) {
return file_jupyter_jupyter_server_host_service_v1_proto_rawDescGZIP(), []int{1}
}
func (x *GetRunningServerResponse) GetResult() bool {
if x != nil {
return x.Result
}
return false
}
func (x *GetRunningServerResponse) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
func (x *GetRunningServerResponse) GetPort() string {
if x != nil {
return x.Port
}
return ""
}
func (x *GetRunningServerResponse) GetServerUrl() string {
if x != nil {
return x.ServerUrl
}
return ""
}
var File_jupyter_jupyter_server_host_service_v1_proto protoreflect.FileDescriptor
var file_jupyter_jupyter_server_host_service_v1_proto_rawDesc = []byte{
0x0a, 0x2c, 0x6a, 0x75, 0x70, 0x79, 0x74, 0x65, 0x72, 0x2f, 0x6a, 0x75, 0x70, 0x79, 0x74, 0x65,
0x72, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x5f, 0x73, 0x65,
0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x2b,
0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x2e,
0x4a, 0x75, 0x70, 0x79, 0x74, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x48, 0x6f, 0x73,
0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x22, 0x19, 0x0a, 0x17, 0x47,
0x65, 0x74, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x7e, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x52, 0x75, 0x6e,
0x6e, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x01, 0x20, 0x01,
0x28, 0x08, 0x52, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x4d, 0x65,
0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x4d, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x50, 0x6f, 0x72, 0x74, 0x18, 0x03, 0x20, 0x01,
0x28, 0x09, 0x52, 0x04, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x53, 0x65, 0x72, 0x76,
0x65, 0x72, 0x55, 0x72, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x53, 0x65, 0x72,
0x76, 0x65, 0x72, 0x55, 0x72, 0x6c, 0x32, 0xb5, 0x01, 0x0a, 0x11, 0x4a, 0x75, 0x70, 0x79, 0x74,
0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x48, 0x6f, 0x73, 0x74, 0x12, 0x9f, 0x01, 0x0a,
0x10, 0x47, 0x65, 0x74, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x65,
0x72, 0x12, 0x44, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x2e, 0x47,
0x72, 0x70, 0x63, 0x2e, 0x4a, 0x75, 0x70, 0x79, 0x74, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x65,
0x72, 0x48, 0x6f, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e,
0x47, 0x65, 0x74, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x45, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70,
0x61, 0x63, 0x65, 0x73, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x4a, 0x75, 0x70, 0x79, 0x74, 0x65,
0x72, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x48, 0x6f, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69,
0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67,
0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x0b,
0x5a, 0x09, 0x2e, 0x2f, 0x6a, 0x75, 0x70, 0x79, 0x74, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var (
file_jupyter_jupyter_server_host_service_v1_proto_rawDescOnce sync.Once
file_jupyter_jupyter_server_host_service_v1_proto_rawDescData = file_jupyter_jupyter_server_host_service_v1_proto_rawDesc
)
func file_jupyter_jupyter_server_host_service_v1_proto_rawDescGZIP() []byte {
file_jupyter_jupyter_server_host_service_v1_proto_rawDescOnce.Do(func() {
file_jupyter_jupyter_server_host_service_v1_proto_rawDescData = protoimpl.X.CompressGZIP(file_jupyter_jupyter_server_host_service_v1_proto_rawDescData)
})
return file_jupyter_jupyter_server_host_service_v1_proto_rawDescData
}
var file_jupyter_jupyter_server_host_service_v1_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_jupyter_jupyter_server_host_service_v1_proto_goTypes = []interface{}{
(*GetRunningServerRequest)(nil), // 0: Codespaces.Grpc.JupyterServerHostService.v1.GetRunningServerRequest
(*GetRunningServerResponse)(nil), // 1: Codespaces.Grpc.JupyterServerHostService.v1.GetRunningServerResponse
}
var file_jupyter_jupyter_server_host_service_v1_proto_depIdxs = []int32{
0, // 0: Codespaces.Grpc.JupyterServerHostService.v1.JupyterServerHost.GetRunningServer:input_type -> Codespaces.Grpc.JupyterServerHostService.v1.GetRunningServerRequest
1, // 1: Codespaces.Grpc.JupyterServerHostService.v1.JupyterServerHost.GetRunningServer:output_type -> Codespaces.Grpc.JupyterServerHostService.v1.GetRunningServerResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] 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_jupyter_jupyter_server_host_service_v1_proto_init() }
func file_jupyter_jupyter_server_host_service_v1_proto_init() {
if File_jupyter_jupyter_server_host_service_v1_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_jupyter_jupyter_server_host_service_v1_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GetRunningServerRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_jupyter_jupyter_server_host_service_v1_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GetRunningServerResponse); 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_jupyter_jupyter_server_host_service_v1_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_jupyter_jupyter_server_host_service_v1_proto_goTypes,
DependencyIndexes: file_jupyter_jupyter_server_host_service_v1_proto_depIdxs,
MessageInfos: file_jupyter_jupyter_server_host_service_v1_proto_msgTypes,
}.Build()
File_jupyter_jupyter_server_host_service_v1_proto = out.File
file_jupyter_jupyter_server_host_service_v1_proto_rawDesc = nil
file_jupyter_jupyter_server_host_service_v1_proto_goTypes = nil
file_jupyter_jupyter_server_host_service_v1_proto_depIdxs = nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/test/port_forwarder.go | internal/codespaces/rpc/test/port_forwarder.go | package test
import (
"context"
"fmt"
"io"
"net"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/microsoft/dev-tunnels/go/tunnels"
)
type PortForwarder struct{}
// Close implements portforwarder.PortForwarder.
func (PortForwarder) Close() error {
return nil
}
// ConnectToForwardedPort implements portforwarder.PortForwarder.
func (PortForwarder) ConnectToForwardedPort(ctx context.Context, conn io.ReadWriteCloser, opts portforwarder.ForwardPortOpts) error {
panic("unimplemented")
}
// ForwardPort implements portforwarder.PortForwarder.
func (PortForwarder) ForwardPort(ctx context.Context, opts portforwarder.ForwardPortOpts) error {
panic("unimplemented")
}
// GetKeepAliveReason implements portforwarder.PortForwarder.
func (PortForwarder) GetKeepAliveReason() string {
panic("unimplemented")
}
// KeepAlive implements portforwarder.PortForwarder.
func (PortForwarder) KeepAlive(reason string) {
panic("unimplemented")
}
// ForwardPortToListener implements portforwarder.PortForwarder.
func (PortForwarder) ForwardPortToListener(ctx context.Context, opts portforwarder.ForwardPortOpts, listener *net.TCPListener) error {
// Start forwarding the port locally
hostConn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", opts.Port))
if err != nil {
return err
}
// Accept the connection from the listener
listenerConn, err := listener.Accept()
if err != nil {
return err
}
// Copy data between the two connections
go func() {
_, _ = io.Copy(hostConn, listenerConn)
hostConn.Close()
}()
go func() {
_, _ = io.Copy(listenerConn, hostConn)
listenerConn.Close()
}()
// ForwardPortToListener typically blocks until the context is cancelled so we need to do the same
<-ctx.Done()
return nil
}
// ListPorts implements portforwarder.PortForwarder.
func (PortForwarder) ListPorts(ctx context.Context) ([]*tunnels.TunnelPort, error) {
panic("unimplemented")
}
// UpdatePortVisibility implements portforwarder.PortForwarder.
func (PortForwarder) UpdatePortVisibility(ctx context.Context, remotePort int, visibility string) error {
panic("unimplemented")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/codespace/codespace_host_service.v1.pb.go | internal/codespaces/rpc/codespace/codespace_host_service.v1.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v3.12.4
// source: codespace/codespace_host_service.v1.proto
package codespace
import (
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)
)
type NotifyCodespaceOfClientActivityRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
ClientId string `protobuf:"bytes,1,opt,name=ClientId,proto3" json:"ClientId,omitempty"`
ClientActivities []string `protobuf:"bytes,2,rep,name=ClientActivities,proto3" json:"ClientActivities,omitempty"`
}
func (x *NotifyCodespaceOfClientActivityRequest) Reset() {
*x = NotifyCodespaceOfClientActivityRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_codespace_codespace_host_service_v1_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *NotifyCodespaceOfClientActivityRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*NotifyCodespaceOfClientActivityRequest) ProtoMessage() {}
func (x *NotifyCodespaceOfClientActivityRequest) ProtoReflect() protoreflect.Message {
mi := &file_codespace_codespace_host_service_v1_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 NotifyCodespaceOfClientActivityRequest.ProtoReflect.Descriptor instead.
func (*NotifyCodespaceOfClientActivityRequest) Descriptor() ([]byte, []int) {
return file_codespace_codespace_host_service_v1_proto_rawDescGZIP(), []int{0}
}
func (x *NotifyCodespaceOfClientActivityRequest) GetClientId() string {
if x != nil {
return x.ClientId
}
return ""
}
func (x *NotifyCodespaceOfClientActivityRequest) GetClientActivities() []string {
if x != nil {
return x.ClientActivities
}
return nil
}
type NotifyCodespaceOfClientActivityResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Result bool `protobuf:"varint,1,opt,name=Result,proto3" json:"Result,omitempty"`
Message string `protobuf:"bytes,2,opt,name=Message,proto3" json:"Message,omitempty"`
}
func (x *NotifyCodespaceOfClientActivityResponse) Reset() {
*x = NotifyCodespaceOfClientActivityResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_codespace_codespace_host_service_v1_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *NotifyCodespaceOfClientActivityResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*NotifyCodespaceOfClientActivityResponse) ProtoMessage() {}
func (x *NotifyCodespaceOfClientActivityResponse) ProtoReflect() protoreflect.Message {
mi := &file_codespace_codespace_host_service_v1_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 NotifyCodespaceOfClientActivityResponse.ProtoReflect.Descriptor instead.
func (*NotifyCodespaceOfClientActivityResponse) Descriptor() ([]byte, []int) {
return file_codespace_codespace_host_service_v1_proto_rawDescGZIP(), []int{1}
}
func (x *NotifyCodespaceOfClientActivityResponse) GetResult() bool {
if x != nil {
return x.Result
}
return false
}
func (x *NotifyCodespaceOfClientActivityResponse) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
type RebuildContainerRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Incremental *bool `protobuf:"varint,1,opt,name=Incremental,proto3,oneof" json:"Incremental,omitempty"`
}
func (x *RebuildContainerRequest) Reset() {
*x = RebuildContainerRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_codespace_codespace_host_service_v1_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RebuildContainerRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RebuildContainerRequest) ProtoMessage() {}
func (x *RebuildContainerRequest) ProtoReflect() protoreflect.Message {
mi := &file_codespace_codespace_host_service_v1_proto_msgTypes[2]
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 RebuildContainerRequest.ProtoReflect.Descriptor instead.
func (*RebuildContainerRequest) Descriptor() ([]byte, []int) {
return file_codespace_codespace_host_service_v1_proto_rawDescGZIP(), []int{2}
}
func (x *RebuildContainerRequest) GetIncremental() bool {
if x != nil && x.Incremental != nil {
return *x.Incremental
}
return false
}
type RebuildContainerResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
RebuildContainer bool `protobuf:"varint,1,opt,name=RebuildContainer,proto3" json:"RebuildContainer,omitempty"`
}
func (x *RebuildContainerResponse) Reset() {
*x = RebuildContainerResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_codespace_codespace_host_service_v1_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RebuildContainerResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RebuildContainerResponse) ProtoMessage() {}
func (x *RebuildContainerResponse) ProtoReflect() protoreflect.Message {
mi := &file_codespace_codespace_host_service_v1_proto_msgTypes[3]
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 RebuildContainerResponse.ProtoReflect.Descriptor instead.
func (*RebuildContainerResponse) Descriptor() ([]byte, []int) {
return file_codespace_codespace_host_service_v1_proto_rawDescGZIP(), []int{3}
}
func (x *RebuildContainerResponse) GetRebuildContainer() bool {
if x != nil {
return x.RebuildContainer
}
return false
}
var File_codespace_codespace_host_service_v1_proto protoreflect.FileDescriptor
var file_codespace_codespace_host_service_v1_proto_rawDesc = []byte{
0x0a, 0x29, 0x63, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x2f, 0x63, 0x6f, 0x64, 0x65,
0x73, 0x70, 0x61, 0x63, 0x65, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69,
0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x27, 0x43, 0x6f, 0x64,
0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x64,
0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x48, 0x6f, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63,
0x65, 0x2e, 0x76, 0x31, 0x22, 0x70, 0x0a, 0x26, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x43, 0x6f,
0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x4f, 0x66, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x41,
0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a,
0x0a, 0x08, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x08, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x10, 0x43, 0x6c,
0x69, 0x65, 0x6e, 0x74, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x69, 0x65, 0x73, 0x18, 0x02,
0x20, 0x03, 0x28, 0x09, 0x52, 0x10, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x41, 0x63, 0x74, 0x69,
0x76, 0x69, 0x74, 0x69, 0x65, 0x73, 0x22, 0x5b, 0x0a, 0x27, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79,
0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x4f, 0x66, 0x43, 0x6c, 0x69, 0x65, 0x6e,
0x74, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
0x65, 0x12, 0x16, 0x0a, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28,
0x08, 0x52, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x4d, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x4d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x22, 0x50, 0x0a, 0x17, 0x52, 0x65, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x43, 0x6f,
0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x25,
0x0a, 0x0b, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x18, 0x01, 0x20,
0x01, 0x28, 0x08, 0x48, 0x00, 0x52, 0x0b, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74,
0x61, 0x6c, 0x88, 0x01, 0x01, 0x42, 0x0e, 0x0a, 0x0c, 0x5f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d,
0x65, 0x6e, 0x74, 0x61, 0x6c, 0x22, 0x46, 0x0a, 0x18, 0x52, 0x65, 0x62, 0x75, 0x69, 0x6c, 0x64,
0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
0x65, 0x12, 0x2a, 0x0a, 0x10, 0x52, 0x65, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x43, 0x6f, 0x6e, 0x74,
0x61, 0x69, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x10, 0x52, 0x65, 0x62,
0x75, 0x69, 0x6c, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x32, 0xf5, 0x02,
0x0a, 0x0d, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x48, 0x6f, 0x73, 0x74, 0x12,
0xc4, 0x01, 0x0a, 0x1f, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70,
0x61, 0x63, 0x65, 0x4f, 0x66, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x41, 0x63, 0x74, 0x69, 0x76,
0x69, 0x74, 0x79, 0x12, 0x4f, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73,
0x2e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x48,
0x6f, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x4e, 0x6f,
0x74, 0x69, 0x66, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x4f, 0x66, 0x43,
0x6c, 0x69, 0x65, 0x6e, 0x74, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x52, 0x65, 0x71,
0x75, 0x65, 0x73, 0x74, 0x1a, 0x50, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65,
0x73, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65,
0x48, 0x6f, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x4e,
0x6f, 0x74, 0x69, 0x66, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x4f, 0x66,
0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x9c, 0x01, 0x0a, 0x15, 0x52, 0x65, 0x62, 0x75, 0x69,
0x6c, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x41, 0x73, 0x79, 0x6e, 0x63,
0x12, 0x40, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x2e, 0x47, 0x72,
0x70, 0x63, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x48, 0x6f, 0x73, 0x74,
0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x62, 0x75, 0x69,
0x6c, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x1a, 0x41, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x2e,
0x47, 0x72, 0x70, 0x63, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x48, 0x6f,
0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x62,
0x75, 0x69, 0x6c, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x52, 0x65, 0x73,
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x0d, 0x5a, 0x0b, 0x2e, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x73,
0x70, 0x61, 0x63, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_codespace_codespace_host_service_v1_proto_rawDescOnce sync.Once
file_codespace_codespace_host_service_v1_proto_rawDescData = file_codespace_codespace_host_service_v1_proto_rawDesc
)
func file_codespace_codespace_host_service_v1_proto_rawDescGZIP() []byte {
file_codespace_codespace_host_service_v1_proto_rawDescOnce.Do(func() {
file_codespace_codespace_host_service_v1_proto_rawDescData = protoimpl.X.CompressGZIP(file_codespace_codespace_host_service_v1_proto_rawDescData)
})
return file_codespace_codespace_host_service_v1_proto_rawDescData
}
var file_codespace_codespace_host_service_v1_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_codespace_codespace_host_service_v1_proto_goTypes = []interface{}{
(*NotifyCodespaceOfClientActivityRequest)(nil), // 0: Codespaces.Grpc.CodespaceHostService.v1.NotifyCodespaceOfClientActivityRequest
(*NotifyCodespaceOfClientActivityResponse)(nil), // 1: Codespaces.Grpc.CodespaceHostService.v1.NotifyCodespaceOfClientActivityResponse
(*RebuildContainerRequest)(nil), // 2: Codespaces.Grpc.CodespaceHostService.v1.RebuildContainerRequest
(*RebuildContainerResponse)(nil), // 3: Codespaces.Grpc.CodespaceHostService.v1.RebuildContainerResponse
}
var file_codespace_codespace_host_service_v1_proto_depIdxs = []int32{
0, // 0: Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost.NotifyCodespaceOfClientActivity:input_type -> Codespaces.Grpc.CodespaceHostService.v1.NotifyCodespaceOfClientActivityRequest
2, // 1: Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost.RebuildContainerAsync:input_type -> Codespaces.Grpc.CodespaceHostService.v1.RebuildContainerRequest
1, // 2: Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost.NotifyCodespaceOfClientActivity:output_type -> Codespaces.Grpc.CodespaceHostService.v1.NotifyCodespaceOfClientActivityResponse
3, // 3: Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost.RebuildContainerAsync:output_type -> Codespaces.Grpc.CodespaceHostService.v1.RebuildContainerResponse
2, // [2:4] is the sub-list for method output_type
0, // [0:2] 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_codespace_codespace_host_service_v1_proto_init() }
func file_codespace_codespace_host_service_v1_proto_init() {
if File_codespace_codespace_host_service_v1_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_codespace_codespace_host_service_v1_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*NotifyCodespaceOfClientActivityRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_codespace_codespace_host_service_v1_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*NotifyCodespaceOfClientActivityResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_codespace_codespace_host_service_v1_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RebuildContainerRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_codespace_codespace_host_service_v1_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RebuildContainerResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_codespace_codespace_host_service_v1_proto_msgTypes[2].OneofWrappers = []interface{}{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_codespace_codespace_host_service_v1_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_codespace_codespace_host_service_v1_proto_goTypes,
DependencyIndexes: file_codespace_codespace_host_service_v1_proto_depIdxs,
MessageInfos: file_codespace_codespace_host_service_v1_proto_msgTypes,
}.Build()
File_codespace_codespace_host_service_v1_proto = out.File
file_codespace_codespace_host_service_v1_proto_rawDesc = nil
file_codespace_codespace_host_service_v1_proto_goTypes = nil
file_codespace_codespace_host_service_v1_proto_depIdxs = nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/codespace/codespace_host_service.v1_grpc.pb.go | internal/codespaces/rpc/codespace/codespace_host_service.v1_grpc.pb.go | // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v3.12.4
// source: codespace/codespace_host_service.v1.proto
package codespace
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// CodespaceHostClient is the client API for CodespaceHost service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type CodespaceHostClient interface {
NotifyCodespaceOfClientActivity(ctx context.Context, in *NotifyCodespaceOfClientActivityRequest, opts ...grpc.CallOption) (*NotifyCodespaceOfClientActivityResponse, error)
RebuildContainerAsync(ctx context.Context, in *RebuildContainerRequest, opts ...grpc.CallOption) (*RebuildContainerResponse, error)
}
type codespaceHostClient struct {
cc grpc.ClientConnInterface
}
func NewCodespaceHostClient(cc grpc.ClientConnInterface) CodespaceHostClient {
return &codespaceHostClient{cc}
}
func (c *codespaceHostClient) NotifyCodespaceOfClientActivity(ctx context.Context, in *NotifyCodespaceOfClientActivityRequest, opts ...grpc.CallOption) (*NotifyCodespaceOfClientActivityResponse, error) {
out := new(NotifyCodespaceOfClientActivityResponse)
err := c.cc.Invoke(ctx, "/Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost/NotifyCodespaceOfClientActivity", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *codespaceHostClient) RebuildContainerAsync(ctx context.Context, in *RebuildContainerRequest, opts ...grpc.CallOption) (*RebuildContainerResponse, error) {
out := new(RebuildContainerResponse)
err := c.cc.Invoke(ctx, "/Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost/RebuildContainerAsync", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// CodespaceHostServer is the server API for CodespaceHost service.
// All implementations must embed UnimplementedCodespaceHostServer
// for forward compatibility
type CodespaceHostServer interface {
NotifyCodespaceOfClientActivity(context.Context, *NotifyCodespaceOfClientActivityRequest) (*NotifyCodespaceOfClientActivityResponse, error)
RebuildContainerAsync(context.Context, *RebuildContainerRequest) (*RebuildContainerResponse, error)
mustEmbedUnimplementedCodespaceHostServer()
}
// UnimplementedCodespaceHostServer must be embedded to have forward compatible implementations.
type UnimplementedCodespaceHostServer struct {
}
func (UnimplementedCodespaceHostServer) NotifyCodespaceOfClientActivity(context.Context, *NotifyCodespaceOfClientActivityRequest) (*NotifyCodespaceOfClientActivityResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method NotifyCodespaceOfClientActivity not implemented")
}
func (UnimplementedCodespaceHostServer) RebuildContainerAsync(context.Context, *RebuildContainerRequest) (*RebuildContainerResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RebuildContainerAsync not implemented")
}
func (UnimplementedCodespaceHostServer) mustEmbedUnimplementedCodespaceHostServer() {}
// UnsafeCodespaceHostServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to CodespaceHostServer will
// result in compilation errors.
type UnsafeCodespaceHostServer interface {
mustEmbedUnimplementedCodespaceHostServer()
}
func RegisterCodespaceHostServer(s grpc.ServiceRegistrar, srv CodespaceHostServer) {
s.RegisterService(&CodespaceHost_ServiceDesc, srv)
}
func _CodespaceHost_NotifyCodespaceOfClientActivity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(NotifyCodespaceOfClientActivityRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CodespaceHostServer).NotifyCodespaceOfClientActivity(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost/NotifyCodespaceOfClientActivity",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CodespaceHostServer).NotifyCodespaceOfClientActivity(ctx, req.(*NotifyCodespaceOfClientActivityRequest))
}
return interceptor(ctx, in, info, handler)
}
func _CodespaceHost_RebuildContainerAsync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RebuildContainerRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CodespaceHostServer).RebuildContainerAsync(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost/RebuildContainerAsync",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CodespaceHostServer).RebuildContainerAsync(ctx, req.(*RebuildContainerRequest))
}
return interceptor(ctx, in, info, handler)
}
// CodespaceHost_ServiceDesc is the grpc.ServiceDesc for CodespaceHost service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var CodespaceHost_ServiceDesc = grpc.ServiceDesc{
ServiceName: "Codespaces.Grpc.CodespaceHostService.v1.CodespaceHost",
HandlerType: (*CodespaceHostServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "NotifyCodespaceOfClientActivity",
Handler: _CodespaceHost_NotifyCodespaceOfClientActivity_Handler,
},
{
MethodName: "RebuildContainerAsync",
Handler: _CodespaceHost_RebuildContainerAsync_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "codespace/codespace_host_service.v1.proto",
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/codespace/codespace_host_service.v1.proto.mock.go | internal/codespaces/rpc/codespace/codespace_host_service.v1.proto.mock.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package codespace
import (
context "context"
sync "sync"
)
// Ensure, that CodespaceHostServerMock does implement CodespaceHostServer.
// If this is not the case, regenerate this file with moq.
var _ CodespaceHostServer = &CodespaceHostServerMock{}
// CodespaceHostServerMock is a mock implementation of CodespaceHostServer.
//
// func TestSomethingThatUsesCodespaceHostServer(t *testing.T) {
//
// // make and configure a mocked CodespaceHostServer
// mockedCodespaceHostServer := &CodespaceHostServerMock{
// NotifyCodespaceOfClientActivityFunc: func(contextMoqParam context.Context, notifyCodespaceOfClientActivityRequest *NotifyCodespaceOfClientActivityRequest) (*NotifyCodespaceOfClientActivityResponse, error) {
// panic("mock out the NotifyCodespaceOfClientActivity method")
// },
// RebuildContainerAsyncFunc: func(contextMoqParam context.Context, rebuildContainerRequest *RebuildContainerRequest) (*RebuildContainerResponse, error) {
// panic("mock out the RebuildContainerAsync method")
// },
// mustEmbedUnimplementedCodespaceHostServerFunc: func() {
// panic("mock out the mustEmbedUnimplementedCodespaceHostServer method")
// },
// }
//
// // use mockedCodespaceHostServer in code that requires CodespaceHostServer
// // and then make assertions.
//
// }
type CodespaceHostServerMock struct {
// NotifyCodespaceOfClientActivityFunc mocks the NotifyCodespaceOfClientActivity method.
NotifyCodespaceOfClientActivityFunc func(contextMoqParam context.Context, notifyCodespaceOfClientActivityRequest *NotifyCodespaceOfClientActivityRequest) (*NotifyCodespaceOfClientActivityResponse, error)
// RebuildContainerAsyncFunc mocks the RebuildContainerAsync method.
RebuildContainerAsyncFunc func(contextMoqParam context.Context, rebuildContainerRequest *RebuildContainerRequest) (*RebuildContainerResponse, error)
// mustEmbedUnimplementedCodespaceHostServerFunc mocks the mustEmbedUnimplementedCodespaceHostServer method.
mustEmbedUnimplementedCodespaceHostServerFunc func()
// calls tracks calls to the methods.
calls struct {
// NotifyCodespaceOfClientActivity holds details about calls to the NotifyCodespaceOfClientActivity method.
NotifyCodespaceOfClientActivity []struct {
// ContextMoqParam is the contextMoqParam argument value.
ContextMoqParam context.Context
// NotifyCodespaceOfClientActivityRequest is the notifyCodespaceOfClientActivityRequest argument value.
NotifyCodespaceOfClientActivityRequest *NotifyCodespaceOfClientActivityRequest
}
// RebuildContainerAsync holds details about calls to the RebuildContainerAsync method.
RebuildContainerAsync []struct {
// ContextMoqParam is the contextMoqParam argument value.
ContextMoqParam context.Context
// RebuildContainerRequest is the rebuildContainerRequest argument value.
RebuildContainerRequest *RebuildContainerRequest
}
// mustEmbedUnimplementedCodespaceHostServer holds details about calls to the mustEmbedUnimplementedCodespaceHostServer method.
mustEmbedUnimplementedCodespaceHostServer []struct {
}
}
lockNotifyCodespaceOfClientActivity sync.RWMutex
lockRebuildContainerAsync sync.RWMutex
lockmustEmbedUnimplementedCodespaceHostServer sync.RWMutex
}
// NotifyCodespaceOfClientActivity calls NotifyCodespaceOfClientActivityFunc.
func (mock *CodespaceHostServerMock) NotifyCodespaceOfClientActivity(contextMoqParam context.Context, notifyCodespaceOfClientActivityRequest *NotifyCodespaceOfClientActivityRequest) (*NotifyCodespaceOfClientActivityResponse, error) {
if mock.NotifyCodespaceOfClientActivityFunc == nil {
panic("CodespaceHostServerMock.NotifyCodespaceOfClientActivityFunc: method is nil but CodespaceHostServer.NotifyCodespaceOfClientActivity was just called")
}
callInfo := struct {
ContextMoqParam context.Context
NotifyCodespaceOfClientActivityRequest *NotifyCodespaceOfClientActivityRequest
}{
ContextMoqParam: contextMoqParam,
NotifyCodespaceOfClientActivityRequest: notifyCodespaceOfClientActivityRequest,
}
mock.lockNotifyCodespaceOfClientActivity.Lock()
mock.calls.NotifyCodespaceOfClientActivity = append(mock.calls.NotifyCodespaceOfClientActivity, callInfo)
mock.lockNotifyCodespaceOfClientActivity.Unlock()
return mock.NotifyCodespaceOfClientActivityFunc(contextMoqParam, notifyCodespaceOfClientActivityRequest)
}
// NotifyCodespaceOfClientActivityCalls gets all the calls that were made to NotifyCodespaceOfClientActivity.
// Check the length with:
//
// len(mockedCodespaceHostServer.NotifyCodespaceOfClientActivityCalls())
func (mock *CodespaceHostServerMock) NotifyCodespaceOfClientActivityCalls() []struct {
ContextMoqParam context.Context
NotifyCodespaceOfClientActivityRequest *NotifyCodespaceOfClientActivityRequest
} {
var calls []struct {
ContextMoqParam context.Context
NotifyCodespaceOfClientActivityRequest *NotifyCodespaceOfClientActivityRequest
}
mock.lockNotifyCodespaceOfClientActivity.RLock()
calls = mock.calls.NotifyCodespaceOfClientActivity
mock.lockNotifyCodespaceOfClientActivity.RUnlock()
return calls
}
// RebuildContainerAsync calls RebuildContainerAsyncFunc.
func (mock *CodespaceHostServerMock) RebuildContainerAsync(contextMoqParam context.Context, rebuildContainerRequest *RebuildContainerRequest) (*RebuildContainerResponse, error) {
if mock.RebuildContainerAsyncFunc == nil {
panic("CodespaceHostServerMock.RebuildContainerAsyncFunc: method is nil but CodespaceHostServer.RebuildContainerAsync was just called")
}
callInfo := struct {
ContextMoqParam context.Context
RebuildContainerRequest *RebuildContainerRequest
}{
ContextMoqParam: contextMoqParam,
RebuildContainerRequest: rebuildContainerRequest,
}
mock.lockRebuildContainerAsync.Lock()
mock.calls.RebuildContainerAsync = append(mock.calls.RebuildContainerAsync, callInfo)
mock.lockRebuildContainerAsync.Unlock()
return mock.RebuildContainerAsyncFunc(contextMoqParam, rebuildContainerRequest)
}
// RebuildContainerAsyncCalls gets all the calls that were made to RebuildContainerAsync.
// Check the length with:
//
// len(mockedCodespaceHostServer.RebuildContainerAsyncCalls())
func (mock *CodespaceHostServerMock) RebuildContainerAsyncCalls() []struct {
ContextMoqParam context.Context
RebuildContainerRequest *RebuildContainerRequest
} {
var calls []struct {
ContextMoqParam context.Context
RebuildContainerRequest *RebuildContainerRequest
}
mock.lockRebuildContainerAsync.RLock()
calls = mock.calls.RebuildContainerAsync
mock.lockRebuildContainerAsync.RUnlock()
return calls
}
// mustEmbedUnimplementedCodespaceHostServer calls mustEmbedUnimplementedCodespaceHostServerFunc.
func (mock *CodespaceHostServerMock) mustEmbedUnimplementedCodespaceHostServer() {
if mock.mustEmbedUnimplementedCodespaceHostServerFunc == nil {
panic("CodespaceHostServerMock.mustEmbedUnimplementedCodespaceHostServerFunc: method is nil but CodespaceHostServer.mustEmbedUnimplementedCodespaceHostServer was just called")
}
callInfo := struct {
}{}
mock.lockmustEmbedUnimplementedCodespaceHostServer.Lock()
mock.calls.mustEmbedUnimplementedCodespaceHostServer = append(mock.calls.mustEmbedUnimplementedCodespaceHostServer, callInfo)
mock.lockmustEmbedUnimplementedCodespaceHostServer.Unlock()
mock.mustEmbedUnimplementedCodespaceHostServerFunc()
}
// mustEmbedUnimplementedCodespaceHostServerCalls gets all the calls that were made to mustEmbedUnimplementedCodespaceHostServer.
// Check the length with:
//
// len(mockedCodespaceHostServer.mustEmbedUnimplementedCodespaceHostServerCalls())
func (mock *CodespaceHostServerMock) mustEmbedUnimplementedCodespaceHostServerCalls() []struct {
} {
var calls []struct {
}
mock.lockmustEmbedUnimplementedCodespaceHostServer.RLock()
calls = mock.calls.mustEmbedUnimplementedCodespaceHostServer
mock.lockmustEmbedUnimplementedCodespaceHostServer.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/ssh/ssh_server_host_service.v1.proto.mock.go | internal/codespaces/rpc/ssh/ssh_server_host_service.v1.proto.mock.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package ssh
import (
context "context"
sync "sync"
)
// Ensure, that SshServerHostServerMock does implement SshServerHostServer.
// If this is not the case, regenerate this file with moq.
var _ SshServerHostServer = &SshServerHostServerMock{}
// SshServerHostServerMock is a mock implementation of SshServerHostServer.
//
// func TestSomethingThatUsesSshServerHostServer(t *testing.T) {
//
// // make and configure a mocked SshServerHostServer
// mockedSshServerHostServer := &SshServerHostServerMock{
// StartRemoteServerAsyncFunc: func(contextMoqParam context.Context, startRemoteServerRequest *StartRemoteServerRequest) (*StartRemoteServerResponse, error) {
// panic("mock out the StartRemoteServerAsync method")
// },
// mustEmbedUnimplementedSshServerHostServerFunc: func() {
// panic("mock out the mustEmbedUnimplementedSshServerHostServer method")
// },
// }
//
// // use mockedSshServerHostServer in code that requires SshServerHostServer
// // and then make assertions.
//
// }
type SshServerHostServerMock struct {
// StartRemoteServerAsyncFunc mocks the StartRemoteServerAsync method.
StartRemoteServerAsyncFunc func(contextMoqParam context.Context, startRemoteServerRequest *StartRemoteServerRequest) (*StartRemoteServerResponse, error)
// mustEmbedUnimplementedSshServerHostServerFunc mocks the mustEmbedUnimplementedSshServerHostServer method.
mustEmbedUnimplementedSshServerHostServerFunc func()
// calls tracks calls to the methods.
calls struct {
// StartRemoteServerAsync holds details about calls to the StartRemoteServerAsync method.
StartRemoteServerAsync []struct {
// ContextMoqParam is the contextMoqParam argument value.
ContextMoqParam context.Context
// StartRemoteServerRequest is the startRemoteServerRequest argument value.
StartRemoteServerRequest *StartRemoteServerRequest
}
// mustEmbedUnimplementedSshServerHostServer holds details about calls to the mustEmbedUnimplementedSshServerHostServer method.
mustEmbedUnimplementedSshServerHostServer []struct {
}
}
lockStartRemoteServerAsync sync.RWMutex
lockmustEmbedUnimplementedSshServerHostServer sync.RWMutex
}
// StartRemoteServerAsync calls StartRemoteServerAsyncFunc.
func (mock *SshServerHostServerMock) StartRemoteServerAsync(contextMoqParam context.Context, startRemoteServerRequest *StartRemoteServerRequest) (*StartRemoteServerResponse, error) {
if mock.StartRemoteServerAsyncFunc == nil {
panic("SshServerHostServerMock.StartRemoteServerAsyncFunc: method is nil but SshServerHostServer.StartRemoteServerAsync was just called")
}
callInfo := struct {
ContextMoqParam context.Context
StartRemoteServerRequest *StartRemoteServerRequest
}{
ContextMoqParam: contextMoqParam,
StartRemoteServerRequest: startRemoteServerRequest,
}
mock.lockStartRemoteServerAsync.Lock()
mock.calls.StartRemoteServerAsync = append(mock.calls.StartRemoteServerAsync, callInfo)
mock.lockStartRemoteServerAsync.Unlock()
return mock.StartRemoteServerAsyncFunc(contextMoqParam, startRemoteServerRequest)
}
// StartRemoteServerAsyncCalls gets all the calls that were made to StartRemoteServerAsync.
// Check the length with:
//
// len(mockedSshServerHostServer.StartRemoteServerAsyncCalls())
func (mock *SshServerHostServerMock) StartRemoteServerAsyncCalls() []struct {
ContextMoqParam context.Context
StartRemoteServerRequest *StartRemoteServerRequest
} {
var calls []struct {
ContextMoqParam context.Context
StartRemoteServerRequest *StartRemoteServerRequest
}
mock.lockStartRemoteServerAsync.RLock()
calls = mock.calls.StartRemoteServerAsync
mock.lockStartRemoteServerAsync.RUnlock()
return calls
}
// mustEmbedUnimplementedSshServerHostServer calls mustEmbedUnimplementedSshServerHostServerFunc.
func (mock *SshServerHostServerMock) mustEmbedUnimplementedSshServerHostServer() {
if mock.mustEmbedUnimplementedSshServerHostServerFunc == nil {
panic("SshServerHostServerMock.mustEmbedUnimplementedSshServerHostServerFunc: method is nil but SshServerHostServer.mustEmbedUnimplementedSshServerHostServer was just called")
}
callInfo := struct {
}{}
mock.lockmustEmbedUnimplementedSshServerHostServer.Lock()
mock.calls.mustEmbedUnimplementedSshServerHostServer = append(mock.calls.mustEmbedUnimplementedSshServerHostServer, callInfo)
mock.lockmustEmbedUnimplementedSshServerHostServer.Unlock()
mock.mustEmbedUnimplementedSshServerHostServerFunc()
}
// mustEmbedUnimplementedSshServerHostServerCalls gets all the calls that were made to mustEmbedUnimplementedSshServerHostServer.
// Check the length with:
//
// len(mockedSshServerHostServer.mustEmbedUnimplementedSshServerHostServerCalls())
func (mock *SshServerHostServerMock) mustEmbedUnimplementedSshServerHostServerCalls() []struct {
} {
var calls []struct {
}
mock.lockmustEmbedUnimplementedSshServerHostServer.RLock()
calls = mock.calls.mustEmbedUnimplementedSshServerHostServer
mock.lockmustEmbedUnimplementedSshServerHostServer.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/ssh/ssh_server_host_service.v1.pb.go | internal/codespaces/rpc/ssh/ssh_server_host_service.v1.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v3.12.4
// source: ssh/ssh_server_host_service.v1.proto
package ssh
import (
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)
)
type StartRemoteServerRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
UserPublicKey string `protobuf:"bytes,1,opt,name=UserPublicKey,proto3" json:"UserPublicKey,omitempty"`
}
func (x *StartRemoteServerRequest) Reset() {
*x = StartRemoteServerRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_ssh_ssh_server_host_service_v1_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StartRemoteServerRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StartRemoteServerRequest) ProtoMessage() {}
func (x *StartRemoteServerRequest) ProtoReflect() protoreflect.Message {
mi := &file_ssh_ssh_server_host_service_v1_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 StartRemoteServerRequest.ProtoReflect.Descriptor instead.
func (*StartRemoteServerRequest) Descriptor() ([]byte, []int) {
return file_ssh_ssh_server_host_service_v1_proto_rawDescGZIP(), []int{0}
}
func (x *StartRemoteServerRequest) GetUserPublicKey() string {
if x != nil {
return x.UserPublicKey
}
return ""
}
type StartRemoteServerResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Result bool `protobuf:"varint,1,opt,name=Result,proto3" json:"Result,omitempty"`
ServerPort string `protobuf:"bytes,2,opt,name=ServerPort,proto3" json:"ServerPort,omitempty"`
User string `protobuf:"bytes,3,opt,name=User,proto3" json:"User,omitempty"`
Message string `protobuf:"bytes,4,opt,name=Message,proto3" json:"Message,omitempty"`
}
func (x *StartRemoteServerResponse) Reset() {
*x = StartRemoteServerResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_ssh_ssh_server_host_service_v1_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StartRemoteServerResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StartRemoteServerResponse) ProtoMessage() {}
func (x *StartRemoteServerResponse) ProtoReflect() protoreflect.Message {
mi := &file_ssh_ssh_server_host_service_v1_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 StartRemoteServerResponse.ProtoReflect.Descriptor instead.
func (*StartRemoteServerResponse) Descriptor() ([]byte, []int) {
return file_ssh_ssh_server_host_service_v1_proto_rawDescGZIP(), []int{1}
}
func (x *StartRemoteServerResponse) GetResult() bool {
if x != nil {
return x.Result
}
return false
}
func (x *StartRemoteServerResponse) GetServerPort() string {
if x != nil {
return x.ServerPort
}
return ""
}
func (x *StartRemoteServerResponse) GetUser() string {
if x != nil {
return x.User
}
return ""
}
func (x *StartRemoteServerResponse) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
var File_ssh_ssh_server_host_service_v1_proto protoreflect.FileDescriptor
var file_ssh_ssh_server_host_service_v1_proto_rawDesc = []byte{
0x0a, 0x24, 0x73, 0x73, 0x68, 0x2f, 0x73, 0x73, 0x68, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72,
0x5f, 0x68, 0x6f, 0x73, 0x74, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x27, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63,
0x65, 0x73, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x73, 0x68, 0x53, 0x65, 0x72, 0x76, 0x65,
0x72, 0x48, 0x6f, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x22,
0x40, 0x0a, 0x18, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x53, 0x65,
0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x24, 0x0a, 0x0d, 0x55,
0x73, 0x65, 0x72, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
0x28, 0x09, 0x52, 0x0d, 0x55, 0x73, 0x65, 0x72, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65,
0x79, 0x22, 0x81, 0x01, 0x0a, 0x19, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x6d, 0x6f, 0x74,
0x65, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12,
0x16, 0x0a, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52,
0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x53, 0x65, 0x72, 0x76, 0x65,
0x72, 0x50, 0x6f, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x53, 0x65, 0x72,
0x76, 0x65, 0x72, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x55, 0x73, 0x65, 0x72, 0x18,
0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x55, 0x73, 0x65, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x4d,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x4d, 0x65,
0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0xb1, 0x01, 0x0a, 0x0d, 0x53, 0x73, 0x68, 0x53, 0x65, 0x72,
0x76, 0x65, 0x72, 0x48, 0x6f, 0x73, 0x74, 0x12, 0x9f, 0x01, 0x0a, 0x16, 0x53, 0x74, 0x61, 0x72,
0x74, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x73, 0x79,
0x6e, 0x63, 0x12, 0x41, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x2e,
0x47, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x73, 0x68, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x48, 0x6f,
0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61,
0x72, 0x74, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x42, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x70, 0x61, 0x63,
0x65, 0x73, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x73, 0x68, 0x53, 0x65, 0x72, 0x76, 0x65,
0x72, 0x48, 0x6f, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e,
0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x53, 0x65, 0x72, 0x76, 0x65,
0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x07, 0x5a, 0x05, 0x2e, 0x2f, 0x73,
0x73, 0x68, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_ssh_ssh_server_host_service_v1_proto_rawDescOnce sync.Once
file_ssh_ssh_server_host_service_v1_proto_rawDescData = file_ssh_ssh_server_host_service_v1_proto_rawDesc
)
func file_ssh_ssh_server_host_service_v1_proto_rawDescGZIP() []byte {
file_ssh_ssh_server_host_service_v1_proto_rawDescOnce.Do(func() {
file_ssh_ssh_server_host_service_v1_proto_rawDescData = protoimpl.X.CompressGZIP(file_ssh_ssh_server_host_service_v1_proto_rawDescData)
})
return file_ssh_ssh_server_host_service_v1_proto_rawDescData
}
var file_ssh_ssh_server_host_service_v1_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_ssh_ssh_server_host_service_v1_proto_goTypes = []interface{}{
(*StartRemoteServerRequest)(nil), // 0: Codespaces.Grpc.SshServerHostService.v1.StartRemoteServerRequest
(*StartRemoteServerResponse)(nil), // 1: Codespaces.Grpc.SshServerHostService.v1.StartRemoteServerResponse
}
var file_ssh_ssh_server_host_service_v1_proto_depIdxs = []int32{
0, // 0: Codespaces.Grpc.SshServerHostService.v1.SshServerHost.StartRemoteServerAsync:input_type -> Codespaces.Grpc.SshServerHostService.v1.StartRemoteServerRequest
1, // 1: Codespaces.Grpc.SshServerHostService.v1.SshServerHost.StartRemoteServerAsync:output_type -> Codespaces.Grpc.SshServerHostService.v1.StartRemoteServerResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] 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_ssh_ssh_server_host_service_v1_proto_init() }
func file_ssh_ssh_server_host_service_v1_proto_init() {
if File_ssh_ssh_server_host_service_v1_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_ssh_ssh_server_host_service_v1_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StartRemoteServerRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_ssh_ssh_server_host_service_v1_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StartRemoteServerResponse); 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_ssh_ssh_server_host_service_v1_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_ssh_ssh_server_host_service_v1_proto_goTypes,
DependencyIndexes: file_ssh_ssh_server_host_service_v1_proto_depIdxs,
MessageInfos: file_ssh_ssh_server_host_service_v1_proto_msgTypes,
}.Build()
File_ssh_ssh_server_host_service_v1_proto = out.File
file_ssh_ssh_server_host_service_v1_proto_rawDesc = nil
file_ssh_ssh_server_host_service_v1_proto_goTypes = nil
file_ssh_ssh_server_host_service_v1_proto_depIdxs = nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/rpc/ssh/ssh_server_host_service.v1_grpc.pb.go | internal/codespaces/rpc/ssh/ssh_server_host_service.v1_grpc.pb.go | // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v3.12.4
// source: ssh/ssh_server_host_service.v1.proto
package ssh
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// SshServerHostClient is the client API for SshServerHost service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type SshServerHostClient interface {
StartRemoteServerAsync(ctx context.Context, in *StartRemoteServerRequest, opts ...grpc.CallOption) (*StartRemoteServerResponse, error)
}
type sshServerHostClient struct {
cc grpc.ClientConnInterface
}
func NewSshServerHostClient(cc grpc.ClientConnInterface) SshServerHostClient {
return &sshServerHostClient{cc}
}
func (c *sshServerHostClient) StartRemoteServerAsync(ctx context.Context, in *StartRemoteServerRequest, opts ...grpc.CallOption) (*StartRemoteServerResponse, error) {
out := new(StartRemoteServerResponse)
err := c.cc.Invoke(ctx, "/Codespaces.Grpc.SshServerHostService.v1.SshServerHost/StartRemoteServerAsync", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// SshServerHostServer is the server API for SshServerHost service.
// All implementations must embed UnimplementedSshServerHostServer
// for forward compatibility
type SshServerHostServer interface {
StartRemoteServerAsync(context.Context, *StartRemoteServerRequest) (*StartRemoteServerResponse, error)
mustEmbedUnimplementedSshServerHostServer()
}
// UnimplementedSshServerHostServer must be embedded to have forward compatible implementations.
type UnimplementedSshServerHostServer struct {
}
func (UnimplementedSshServerHostServer) StartRemoteServerAsync(context.Context, *StartRemoteServerRequest) (*StartRemoteServerResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method StartRemoteServerAsync not implemented")
}
func (UnimplementedSshServerHostServer) mustEmbedUnimplementedSshServerHostServer() {}
// UnsafeSshServerHostServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to SshServerHostServer will
// result in compilation errors.
type UnsafeSshServerHostServer interface {
mustEmbedUnimplementedSshServerHostServer()
}
func RegisterSshServerHostServer(s grpc.ServiceRegistrar, srv SshServerHostServer) {
s.RegisterService(&SshServerHost_ServiceDesc, srv)
}
func _SshServerHost_StartRemoteServerAsync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(StartRemoteServerRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SshServerHostServer).StartRemoteServerAsync(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/Codespaces.Grpc.SshServerHostService.v1.SshServerHost/StartRemoteServerAsync",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SshServerHostServer).StartRemoteServerAsync(ctx, req.(*StartRemoteServerRequest))
}
return interceptor(ctx, in, info, handler)
}
// SshServerHost_ServiceDesc is the grpc.ServiceDesc for SshServerHost service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var SshServerHost_ServiceDesc = grpc.ServiceDesc{
ServiceName: "Codespaces.Grpc.SshServerHostService.v1.SshServerHost",
HandlerType: (*SshServerHostServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "StartRemoteServerAsync",
Handler: _SshServerHost_StartRemoteServerAsync_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "ssh/ssh_server_host_service.v1.proto",
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/connection/connection.go | internal/codespaces/connection/connection.go | package connection
import (
"context"
"fmt"
"io"
"log"
"net/http"
"net/url"
"sync"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/microsoft/dev-tunnels/go/tunnels"
)
const (
clientName = "gh"
)
type TunnelClient struct {
*tunnels.Client
connected bool
mu sync.Mutex
}
type CodespaceConnection struct {
tunnelProperties api.TunnelProperties
TunnelManager *tunnels.Manager
TunnelClient *TunnelClient
Options *tunnels.TunnelRequestOptions
Tunnel *tunnels.Tunnel
AllowedPortPrivacySettings []string
}
// NewCodespaceConnection initializes a connection to a codespace.
// This connections allows for port forwarding which enables the
// use of most features of the codespace command.
func NewCodespaceConnection(ctx context.Context, codespace *api.Codespace, httpClient *http.Client) (connection *CodespaceConnection, err error) {
// Get the tunnel properties
tunnelProperties := codespace.Connection.TunnelProperties
// Create the tunnel manager
tunnelManager, err := getTunnelManager(tunnelProperties, httpClient)
if err != nil {
return nil, fmt.Errorf("error getting tunnel management client: %w", err)
}
// Calculate allowed port privacy settings
allowedPortPrivacySettings := codespace.RuntimeConstraints.AllowedPortPrivacySettings
// Get the access tokens
connectToken := tunnelProperties.ConnectAccessToken
managementToken := tunnelProperties.ManagePortsAccessToken
// Create the tunnel definition
tunnel := &tunnels.Tunnel{
AccessTokens: map[tunnels.TunnelAccessScope]string{tunnels.TunnelAccessScopeConnect: connectToken, tunnels.TunnelAccessScopeManagePorts: managementToken},
TunnelID: tunnelProperties.TunnelId,
ClusterID: tunnelProperties.ClusterId,
Domain: tunnelProperties.Domain,
}
// Create options
options := &tunnels.TunnelRequestOptions{
IncludePorts: true,
}
// Create the tunnel client (not connected yet)
tunnelClient, err := getTunnelClient(ctx, tunnelManager, tunnel, options)
if err != nil {
return nil, fmt.Errorf("error getting tunnel client: %w", err)
}
return &CodespaceConnection{
tunnelProperties: tunnelProperties,
TunnelManager: tunnelManager,
TunnelClient: tunnelClient,
Options: options,
Tunnel: tunnel,
AllowedPortPrivacySettings: allowedPortPrivacySettings,
}, nil
}
// Connect connects the client to the tunnel.
func (c *CodespaceConnection) Connect(ctx context.Context) error {
// Lock the mutex to prevent race conditions with the underlying SSH connection
c.TunnelClient.mu.Lock()
defer c.TunnelClient.mu.Unlock()
// If already connected, return
if c.TunnelClient.connected {
return nil
}
// Connect to the tunnel
if err := c.TunnelClient.Client.Connect(ctx, ""); err != nil {
return fmt.Errorf("error connecting to tunnel: %w", err)
}
// Set the connected flag so we know we're connected
c.TunnelClient.connected = true
return nil
}
// Close closes the underlying tunnel client SSH connection.
func (c *CodespaceConnection) Close() error {
// Lock the mutex to prevent race conditions with the underlying SSH connection
c.TunnelClient.mu.Lock()
defer c.TunnelClient.mu.Unlock()
// Don't close if we're not connected
if c.TunnelClient != nil && c.TunnelClient.connected {
if err := c.TunnelClient.Close(); err != nil {
return fmt.Errorf("failed to close tunnel client connection: %w", err)
}
c.TunnelClient.connected = false
}
return nil
}
// getTunnelManager creates a tunnel manager for the given codespace.
// The tunnel manager is used to get the tunnel hosted in the codespace that we
// want to connect to and perform operations on ports (add, remove, list, etc.).
func getTunnelManager(tunnelProperties api.TunnelProperties, httpClient *http.Client) (tunnelManager *tunnels.Manager, err error) {
userAgent := []tunnels.UserAgent{{Name: clientName}}
url, err := url.Parse(tunnelProperties.ServiceUri)
if err != nil {
return nil, fmt.Errorf("error parsing tunnel service uri: %w", err)
}
// Create the tunnel manager
// This api version seems to be the only acceptable api version: https://github.com/microsoft/dev-tunnels/blob/bf96ae5a128041d1a23f81d53a47e9e6c26fdc8d/go/tunnels/manager.go#L66
apiVersion := "2023-09-27-preview"
tunnelManager, err = tunnels.NewManager(userAgent, nil, url, httpClient, apiVersion)
if err != nil {
return nil, fmt.Errorf("error creating tunnel manager: %w", err)
}
return tunnelManager, nil
}
// getTunnelClient creates a tunnel client for the given tunnel.
// The tunnel client is used to connect to the tunnel and allows
// for ports to be forwarded locally.
func getTunnelClient(ctx context.Context, tunnelManager *tunnels.Manager, tunnel *tunnels.Tunnel, options *tunnels.TunnelRequestOptions) (tunnelClient *TunnelClient, err error) {
// Get the tunnel that we want to connect to
codespaceTunnel, err := tunnelManager.GetTunnel(ctx, tunnel, options)
if err != nil {
return nil, fmt.Errorf("error getting tunnel: %w", err)
}
// Copy the access tokens from the tunnel definition
codespaceTunnel.AccessTokens = tunnel.AccessTokens
// We need to pass false for accept local connections because we don't want to automatically connect to all forwarded ports
client, err := tunnels.NewClient(log.New(io.Discard, "", log.LstdFlags), codespaceTunnel, false)
if err != nil {
return nil, fmt.Errorf("error creating tunnel client: %w", err)
}
tunnelClient = &TunnelClient{
Client: client,
connected: false,
}
return tunnelClient, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/connection/tunnels_api_server_mock.go | internal/codespaces/connection/tunnels_api_server_mock.go | package connection
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/microsoft/dev-tunnels/go/tunnels"
tunnelssh "github.com/microsoft/dev-tunnels/go/tunnels/ssh"
"github.com/microsoft/dev-tunnels/go/tunnels/ssh/messages"
"golang.org/x/crypto/ssh"
)
type mockClientOpts struct {
ports map[int]tunnels.TunnelPort // Port number to protocol
}
type mockClientOpt func(*mockClientOpts)
// WithSpecificPorts allows you to specify a map of ports to TunnelPorts that will be returned by the mock HTTP client.
// Note that this does not take a copy of the map, so you should not modify the map after passing it to this function.
func WithSpecificPorts(ports map[int]tunnels.TunnelPort) mockClientOpt {
return func(opts *mockClientOpts) {
opts.ports = ports
}
}
func NewMockHttpClient(opts ...mockClientOpt) (*http.Client, error) {
mockClientOpts := &mockClientOpts{}
for _, opt := range opts {
opt(mockClientOpts)
}
specifiedPorts := mockClientOpts.ports
accessToken := "tunnel access-token"
relayServer, err := newMockrelayServer(withAccessToken(accessToken))
if err != nil {
return nil, fmt.Errorf("NewrelayServer returned an error: %w", err)
}
hostURL := strings.Replace(relayServer.URL(), "http://", "ws://", 1)
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var response []byte
if r.URL.Path == "/tunnels/tunnel-id" {
tunnel := &tunnels.Tunnel{
AccessTokens: map[tunnels.TunnelAccessScope]string{
tunnels.TunnelAccessScopeConnect: accessToken,
},
Endpoints: []tunnels.TunnelEndpoint{
{
HostID: "host1",
TunnelRelayTunnelEndpoint: tunnels.TunnelRelayTunnelEndpoint{
ClientRelayURI: hostURL,
},
},
},
}
response, err = json.Marshal(*tunnel)
if err != nil {
log.Fatalf("json.Marshal returned an error: %v", err)
}
_, _ = w.Write(response)
return
} else if strings.HasPrefix(r.URL.Path, "/tunnels/tunnel-id/ports") {
// Use regex to capture the port number from the end of the path
re := regexp.MustCompile(`\/(\d+)$`)
matches := re.FindStringSubmatch(r.URL.Path)
targetingSpecificPort := len(matches) > 0
if targetingSpecificPort {
if r.Method == http.MethodDelete {
w.WriteHeader(http.StatusOK)
return
}
if r.Method == http.MethodGet {
// If no ports were configured, then we assume that every request for a port is valid.
if specifiedPorts == nil {
response, err := json.Marshal(tunnels.TunnelPort{
AccessControl: &tunnels.TunnelAccessControl{
Entries: []tunnels.TunnelAccessControlEntry{},
},
})
if err != nil {
log.Fatalf("json.Marshal returned an error: %v", err)
}
_, _ = w.Write(response)
return
} else {
// Otherwise we'll fetch the port from our configured ports and include the protocol in the response.
port, err := strconv.Atoi(matches[1])
if err != nil {
log.Fatalf("strconv.Atoi returned an error: %v", err)
}
tunnelPort, ok := specifiedPorts[port]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
response, err := json.Marshal(tunnelPort)
if err != nil {
log.Fatalf("json.Marshal returned an error: %v", err)
}
_, _ = w.Write(response)
return
}
}
// Else this is an unexpected request, fall through to 404 at the bottom
}
// If it's a PUT request, we assume it's for creating a new port so we'll do some validation
// and then return a stub.
if r.Method == http.MethodPut {
// If a port was already configured with this number, and the protocol has changed, return a 400 Bad Request.
if specifiedPorts != nil {
port, err := strconv.Atoi(matches[1])
if err != nil {
log.Fatalf("strconv.Atoi returned an error: %v", err)
}
var portRequest tunnels.TunnelPort
if err := json.NewDecoder(r.Body).Decode(&portRequest); err != nil {
log.Fatalf("json.NewDecoder returned an error: %v", err)
}
tunnelPort, ok := specifiedPorts[port]
if ok {
if tunnelPort.Protocol != portRequest.Protocol {
w.WriteHeader(http.StatusBadRequest)
return
}
}
// Create or update the new port entry.
specifiedPorts[port] = portRequest
}
response, err := json.Marshal(tunnels.TunnelPort{
AccessControl: &tunnels.TunnelAccessControl{
Entries: []tunnels.TunnelAccessControlEntry{},
},
})
if err != nil {
log.Fatalf("json.Marshal returned an error: %v", err)
}
_, _ = w.Write(response)
return
}
// Finally, if it's not targeting a specific port or a POST request, we return a list of ports, either
// totally stubbed, or whatever was configured in the mock client options.
if specifiedPorts == nil {
response, err := json.Marshal(tunnels.TunnelPortListResponse{
Value: []tunnels.TunnelPort{
{
AccessControl: &tunnels.TunnelAccessControl{
Entries: []tunnels.TunnelAccessControlEntry{},
},
},
},
})
if err != nil {
log.Fatalf("json.Marshal returned an error: %v", err)
}
_, _ = w.Write(response)
return
} else {
var ports []tunnels.TunnelPort
for _, tunnelPort := range specifiedPorts {
ports = append(ports, tunnelPort)
}
response, err := json.Marshal(tunnels.TunnelPortListResponse{
Value: ports,
})
if err != nil {
log.Fatalf("json.Marshal returned an error: %v", err)
}
_, _ = w.Write(response)
return
}
} else {
w.WriteHeader(http.StatusNotFound)
return
}
}))
url, err := url.Parse(mockServer.URL)
if err != nil {
return nil, fmt.Errorf("url.Parse returned an error: %w", err)
}
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(url),
},
}, nil
}
type relayServer struct {
httpServer *httptest.Server
errc chan error
sshConfig *ssh.ServerConfig
channels map[string]channelHandler
accessToken string
serverConn *ssh.ServerConn
}
type relayServerOption func(*relayServer)
type channelHandler func(context.Context, ssh.NewChannel) error
func newMockrelayServer(opts ...relayServerOption) (*relayServer, error) {
server := &relayServer{
errc: make(chan error),
sshConfig: &ssh.ServerConfig{
NoClientAuth: true,
},
}
// Create a private key with the crypto package
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("failed to generate key: %w", err)
}
privateKeyPEM := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
},
)
// Parse the private key
sshPrivateKey, err := ssh.ParsePrivateKey(privateKeyPEM)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %w", err)
}
server.sshConfig.AddHostKey(ssh.Signer(sshPrivateKey))
server.httpServer = httptest.NewServer(http.HandlerFunc(makeConnection(server)))
for _, opt := range opts {
opt(server)
}
return server, nil
}
func withAccessToken(accessToken string) func(*relayServer) {
return func(server *relayServer) {
server.accessToken = accessToken
}
}
func (rs *relayServer) URL() string {
return rs.httpServer.URL
}
func (rs *relayServer) Err() <-chan error {
return rs.errc
}
func (rs *relayServer) sendError(err error) {
select {
case rs.errc <- err:
default:
// channel is blocked with a previous error, so we ignore this one
}
}
func (rs *relayServer) ForwardPort(ctx context.Context, port uint16) error {
pfr := messages.NewPortForwardRequest("127.0.0.1", uint32(port))
b, err := pfr.Marshal()
if err != nil {
return fmt.Errorf("error marshaling port forward request: %w", err)
}
replied, data, err := rs.serverConn.SendRequest(messages.PortForwardRequestType, true, b)
if err != nil {
return fmt.Errorf("error sending port forward request: %w", err)
}
if !replied {
return fmt.Errorf("port forward request not replied")
}
if data == nil {
return fmt.Errorf("no data returned")
}
return nil
}
func makeConnection(server *relayServer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if server.accessToken != "" {
if r.Header.Get("Authorization") != server.accessToken {
server.sendError(fmt.Errorf("invalid access token"))
return
}
}
upgrader := websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
server.sendError(fmt.Errorf("error upgrading to websocket: %w", err))
return
}
defer func() {
if err := c.Close(); err != nil {
server.sendError(fmt.Errorf("error closing websocket: %w", err))
}
}()
socketConn := newSocketConn(c)
serverConn, chans, reqs, err := ssh.NewServerConn(socketConn, server.sshConfig)
if err != nil {
server.sendError(fmt.Errorf("error creating ssh server conn: %w", err))
return
}
go handleRequests(ctx, convertRequests(reqs))
server.serverConn = serverConn
if err := handleChannels(ctx, server, chans); err != nil {
server.sendError(fmt.Errorf("error handling channels: %w", err))
return
}
}
}
func (sr *sshRequest) Type() string {
return sr.request.Type
}
type sshRequest struct {
request *ssh.Request
}
// Reply method for sshRequest to satisfy the tunnelssh.SSHRequest interface
func (sr *sshRequest) Reply(success bool, message []byte) error {
return sr.request.Reply(success, message)
}
// convertRequests function
func convertRequests(reqs <-chan *ssh.Request) <-chan tunnelssh.SSHRequest {
out := make(chan tunnelssh.SSHRequest)
go func() {
for req := range reqs {
out <- &sshRequest{req}
}
close(out)
}()
return out
}
func handleChannels(ctx context.Context, server *relayServer, chans <-chan ssh.NewChannel) error {
errc := make(chan error, 1)
go func() {
for ch := range chans {
if handler, ok := server.channels[ch.ChannelType()]; ok {
if err := handler(ctx, ch); err != nil {
errc <- err
return
}
} else {
// generic accept of the channel to not block
_, _, err := ch.Accept()
if err != nil {
errc <- fmt.Errorf("error accepting channel: %w", err)
return
}
}
}
}()
return awaitError(ctx, errc)
}
func handleRequests(ctx context.Context, reqs <-chan tunnelssh.SSHRequest) {
for {
select {
case <-ctx.Done():
return
case req, ok := <-reqs:
if !ok {
return
}
if req.Type() == "RefreshPorts" {
_ = req.Reply(true, nil)
continue
} else {
_ = req.Reply(false, nil)
}
}
}
}
func awaitError(ctx context.Context, errc <-chan error) error {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errc:
return err
}
}
type socketConn struct {
*websocket.Conn
reader io.Reader
writeMutex sync.Mutex
readMutex sync.Mutex
}
func newSocketConn(conn *websocket.Conn) *socketConn {
return &socketConn{Conn: conn}
}
func (s *socketConn) Read(b []byte) (int, error) {
s.readMutex.Lock()
defer s.readMutex.Unlock()
if s.reader == nil {
msgType, r, err := s.Conn.NextReader()
if err != nil {
return 0, fmt.Errorf("error getting next reader: %w", err)
}
if msgType != websocket.BinaryMessage {
return 0, fmt.Errorf("invalid message type")
}
s.reader = r
}
bytesRead, err := s.reader.Read(b)
if err != nil {
s.reader = nil
if err == io.EOF {
err = nil
}
}
return bytesRead, err
}
func (s *socketConn) Write(b []byte) (int, error) {
s.writeMutex.Lock()
defer s.writeMutex.Unlock()
w, err := s.Conn.NextWriter(websocket.BinaryMessage)
if err != nil {
return 0, fmt.Errorf("error getting next writer: %w", err)
}
n, err := w.Write(b)
if err != nil {
return 0, fmt.Errorf("error writing: %w", err)
}
if err := w.Close(); err != nil {
return 0, fmt.Errorf("error closing writer: %w", err)
}
return n, nil
}
func (s *socketConn) SetDeadline(deadline time.Time) error {
if err := s.Conn.SetReadDeadline(deadline); err != nil {
return err
}
return s.Conn.SetWriteDeadline(deadline)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/connection/connection_test.go | internal/codespaces/connection/connection_test.go | package connection
import (
"context"
"reflect"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/microsoft/dev-tunnels/go/tunnels"
)
func TestNewCodespaceConnection(t *testing.T) {
ctx := context.Background()
// Create a mock codespace
connection := api.CodespaceConnection{
TunnelProperties: api.TunnelProperties{
ConnectAccessToken: "connect-token",
ManagePortsAccessToken: "manage-ports-token",
ServiceUri: "http://global.rel.tunnels.api.visualstudio.com/",
TunnelId: "tunnel-id",
ClusterId: "usw2",
Domain: "domain.com",
},
}
allowedPortPrivacySettings := []string{"public", "private"}
codespace := &api.Codespace{
Connection: connection,
RuntimeConstraints: api.RuntimeConstraints{AllowedPortPrivacySettings: allowedPortPrivacySettings},
}
// Create the mock HTTP client
httpClient, err := NewMockHttpClient()
if err != nil {
t.Fatalf("NewHttpClient returned an error: %v", err)
}
// Create the connection
conn, err := NewCodespaceConnection(ctx, codespace, httpClient)
if err != nil {
t.Fatalf("NewCodespaceConnection returned an error: %v", err)
}
// Verify closing before connected doesn't throw
err = conn.Close()
if err != nil {
t.Fatalf("Close returned an error: %v", err)
}
// Check that the connection was created successfully
if conn == nil {
t.Fatal("NewCodespaceConnection returned nil")
}
// Verify that the connection contains the expected tunnel properties
if conn.tunnelProperties != connection.TunnelProperties {
t.Fatalf("NewCodespaceConnection returned a connection with unexpected tunnel properties: %+v", conn.tunnelProperties)
}
// Verify that the connection contains the expected tunnel
expectedTunnel := &tunnels.Tunnel{
AccessTokens: map[tunnels.TunnelAccessScope]string{tunnels.TunnelAccessScopeConnect: connection.TunnelProperties.ConnectAccessToken, tunnels.TunnelAccessScopeManagePorts: connection.TunnelProperties.ManagePortsAccessToken},
TunnelID: connection.TunnelProperties.TunnelId,
ClusterID: connection.TunnelProperties.ClusterId,
Domain: connection.TunnelProperties.Domain,
}
if !reflect.DeepEqual(conn.Tunnel, expectedTunnel) {
t.Fatalf("NewCodespaceConnection returned a connection with unexpected tunnel: %+v", conn.Tunnel)
}
// Verify that the connection contains the expected tunnel options
expectedOptions := &tunnels.TunnelRequestOptions{IncludePorts: true}
if !reflect.DeepEqual(conn.Options, expectedOptions) {
t.Fatalf("NewCodespaceConnection returned a connection with unexpected options: %+v", conn.Options)
}
// Verify that the connection contains the expected allowed port privacy settings
if !reflect.DeepEqual(conn.AllowedPortPrivacySettings, allowedPortPrivacySettings) {
t.Fatalf("NewCodespaceConnection returned a connection with unexpected allowed port privacy settings: %+v", conn.AllowedPortPrivacySettings)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/portforwarder/port_forwarder_test.go | internal/codespaces/portforwarder/port_forwarder_test.go | package portforwarder
import (
"context"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/codespaces/connection"
"github.com/microsoft/dev-tunnels/go/tunnels"
)
func TestNewPortForwarder(t *testing.T) {
ctx := context.Background()
// Create a mock codespace
codespace := &api.Codespace{
Connection: api.CodespaceConnection{
TunnelProperties: api.TunnelProperties{
ConnectAccessToken: "connect-token",
ManagePortsAccessToken: "manage-ports-token",
ServiceUri: "http://global.rel.tunnels.api.visualstudio.com/",
TunnelId: "tunnel-id",
ClusterId: "usw2",
Domain: "domain.com",
},
},
RuntimeConstraints: api.RuntimeConstraints{
AllowedPortPrivacySettings: []string{"public", "private"},
},
}
// Create the mock HTTP client
httpClient, err := connection.NewMockHttpClient()
if err != nil {
t.Fatalf("NewHttpClient returned an error: %v", err)
}
// Call the function being tested
conn, err := connection.NewCodespaceConnection(ctx, codespace, httpClient)
if err != nil {
t.Fatalf("NewCodespaceConnection returned an error: %v", err)
}
// Create the new port forwarder
portForwarder, err := NewPortForwarder(ctx, conn)
if err != nil {
t.Fatalf("NewPortForwarder returned an error: %v", err)
}
// Check that the port forwarder was created successfully
if portForwarder == nil {
t.Fatal("NewPortForwarder returned nil")
}
}
func TestAccessControlEntriesToVisibility(t *testing.T) {
publicAccessControlEntry := []tunnels.TunnelAccessControlEntry{{
Type: tunnels.TunnelAccessControlEntryTypeAnonymous,
}}
orgAccessControlEntry := []tunnels.TunnelAccessControlEntry{{
Provider: string(tunnels.TunnelAuthenticationSchemeGitHub),
}}
privateAccessControlEntry := []tunnels.TunnelAccessControlEntry{}
orgIsDenyAccessControlEntry := []tunnels.TunnelAccessControlEntry{{
Provider: string(tunnels.TunnelAuthenticationSchemeGitHub),
IsDeny: true,
}}
tests := []struct {
name string
accessControlEntries []tunnels.TunnelAccessControlEntry
expected string
}{
{
name: "public",
accessControlEntries: publicAccessControlEntry,
expected: PublicPortVisibility,
},
{
name: "org",
accessControlEntries: orgAccessControlEntry,
expected: OrgPortVisibility,
},
{
name: "private",
accessControlEntries: privateAccessControlEntry,
expected: PrivatePortVisibility,
},
{
name: "orgIsDeny",
accessControlEntries: orgIsDenyAccessControlEntry,
expected: PrivatePortVisibility,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
visibility := AccessControlEntriesToVisibility(test.accessControlEntries)
if visibility != test.expected {
t.Errorf("expected %q, got %q", test.expected, visibility)
}
})
}
}
func TestIsInternalPort(t *testing.T) {
internalPort := &tunnels.TunnelPort{
Labels: []string{"InternalPort"},
}
userForwardedPort := &tunnels.TunnelPort{
Labels: []string{"UserForwardedPort"},
}
tests := []struct {
name string
port *tunnels.TunnelPort
expected bool
}{
{
name: "internal",
port: internalPort,
expected: true,
},
{
name: "user-forwarded",
port: userForwardedPort,
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
isInternal := IsInternalPort(test.port)
if isInternal != test.expected {
t.Errorf("expected %v, got %v", test.expected, isInternal)
}
})
}
}
func TestForwardPortDefaultsToHTTPProtocol(t *testing.T) {
codespace := &api.Codespace{
Name: "codespace-name",
State: api.CodespaceStateAvailable,
Connection: api.CodespaceConnection{
TunnelProperties: api.TunnelProperties{
ConnectAccessToken: "tunnel access-token",
ManagePortsAccessToken: "manage-ports-token",
ServiceUri: "http://global.rel.tunnels.api.visualstudio.com/",
TunnelId: "tunnel-id",
ClusterId: "usw2",
Domain: "domain.com",
},
},
RuntimeConstraints: api.RuntimeConstraints{
AllowedPortPrivacySettings: []string{"public", "private"},
},
}
// Given there are no forwarded ports.
tunnelPorts := map[int]tunnels.TunnelPort{}
httpClient, err := connection.NewMockHttpClient(
connection.WithSpecificPorts(tunnelPorts),
)
if err != nil {
t.Fatalf("NewMockHttpClient returned an error: %v", err)
}
connection, err := connection.NewCodespaceConnection(t.Context(), codespace, httpClient)
if err != nil {
t.Fatalf("NewCodespaceConnection returned an error: %v", err)
}
fwd, err := NewPortForwarder(t.Context(), connection)
if err != nil {
t.Fatalf("NewPortForwarder returned an error: %v", err)
}
// When we forward a port without an existing one to use for a protocol, it should default to HTTP.
if err := fwd.ForwardPort(t.Context(), ForwardPortOpts{
Port: 1337,
}); err != nil {
t.Fatalf("ForwardPort returned an error: %v", err)
}
ports, err := fwd.ListPorts(t.Context())
if err != nil {
t.Fatalf("ListPorts returned an error: %v", err)
}
if len(ports) != 1 {
t.Fatalf("expected 1 port, got %d", len(ports))
}
if ports[0].Protocol != string(tunnels.TunnelProtocolHttp) {
t.Fatalf("expected port protocol to be http, got %s", ports[0].Protocol)
}
}
func TestForwardPortRespectsProtocolOfExistingTunneledPorts(t *testing.T) {
codespace := &api.Codespace{
Name: "codespace-name",
State: api.CodespaceStateAvailable,
Connection: api.CodespaceConnection{
TunnelProperties: api.TunnelProperties{
ConnectAccessToken: "tunnel access-token",
ManagePortsAccessToken: "manage-ports-token",
ServiceUri: "http://global.rel.tunnels.api.visualstudio.com/",
TunnelId: "tunnel-id",
ClusterId: "usw2",
Domain: "domain.com",
},
},
RuntimeConstraints: api.RuntimeConstraints{
AllowedPortPrivacySettings: []string{"public", "private"},
},
}
// Given we already have a port forwarded with an HTTPS protocol.
tunnelPorts := map[int]tunnels.TunnelPort{
1337: {
Protocol: string(tunnels.TunnelProtocolHttps),
AccessControl: &tunnels.TunnelAccessControl{
Entries: []tunnels.TunnelAccessControlEntry{},
},
},
}
httpClient, err := connection.NewMockHttpClient(
connection.WithSpecificPorts(tunnelPorts),
)
if err != nil {
t.Fatalf("NewMockHttpClient returned an error: %v", err)
}
connection, err := connection.NewCodespaceConnection(t.Context(), codespace, httpClient)
if err != nil {
t.Fatalf("NewCodespaceConnection returned an error: %v", err)
}
fwd, err := NewPortForwarder(t.Context(), connection)
if err != nil {
t.Fatalf("NewPortForwarder returned an error: %v", err)
}
// When we forward a port, it would typically default to HTTP, to which the mock server would respond with a 400,
// but it should respect the existing port's protocol and forward it as HTTPS.
if err := fwd.ForwardPort(t.Context(), ForwardPortOpts{
Port: 1337,
}); err != nil {
t.Fatalf("ForwardPort returned an error: %v", err)
}
ports, err := fwd.ListPorts(t.Context())
if err != nil {
t.Fatalf("ListPorts returned an error: %v", err)
}
if len(ports) != 1 {
t.Fatalf("expected 1 port, got %d", len(ports))
}
if ports[0].Protocol != string(tunnels.TunnelProtocolHttps) {
t.Fatalf("expected port protocol to be https, got %s", ports[0].Protocol)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/portforwarder/port_forwarder.go | internal/codespaces/portforwarder/port_forwarder.go | package portforwarder
import (
"context"
"fmt"
"io"
"net"
"strings"
"github.com/cli/cli/v2/internal/codespaces/connection"
"github.com/microsoft/dev-tunnels/go/tunnels"
)
const (
githubSubjectId = "1"
InternalPortLabel = "InternalPort"
UserForwardedPortLabel = "UserForwardedPort"
)
const (
PrivatePortVisibility = "private"
OrgPortVisibility = "org"
PublicPortVisibility = "public"
)
const (
trafficTypeInput = "input"
trafficTypeOutput = "output"
)
type ForwardPortOpts struct {
Port int
Internal bool
KeepAlive bool
Visibility string
}
type CodespacesPortForwarder struct {
connection connection.CodespaceConnection
keepAliveReason chan string
}
type PortForwarder interface {
ForwardPortToListener(ctx context.Context, opts ForwardPortOpts, listener *net.TCPListener) error
ForwardPort(ctx context.Context, opts ForwardPortOpts) error
ConnectToForwardedPort(ctx context.Context, conn io.ReadWriteCloser, opts ForwardPortOpts) error
ListPorts(ctx context.Context) ([]*tunnels.TunnelPort, error)
UpdatePortVisibility(ctx context.Context, remotePort int, visibility string) error
KeepAlive(reason string)
GetKeepAliveReason() string
Close() error
}
// NewPortForwarder returns a new PortForwarder for the specified codespace.
func NewPortForwarder(ctx context.Context, codespaceConnection *connection.CodespaceConnection) (fwd PortForwarder, err error) {
return &CodespacesPortForwarder{
connection: *codespaceConnection,
keepAliveReason: make(chan string, 1),
}, nil
}
// ForwardPortToListener forwards the specified port to the given TCP listener.
func (fwd *CodespacesPortForwarder) ForwardPortToListener(ctx context.Context, opts ForwardPortOpts, listener *net.TCPListener) error {
err := fwd.ForwardPort(ctx, opts)
if err != nil {
return fmt.Errorf("error forwarding port: %w", err)
}
done := make(chan error)
go func() {
// Convert the port number to a uint16
port, err := convertIntToUint16(opts.Port)
if err != nil {
done <- fmt.Errorf("error converting port: %w", err)
return
}
// Ensure the port is forwarded before connecting
err = fwd.connection.TunnelClient.WaitForForwardedPort(ctx, port)
if err != nil {
done <- fmt.Errorf("wait for forwarded port failed: %v", err)
return
}
// Connect to the forwarded port
err = fwd.connectListenerToForwardedPort(ctx, opts, listener)
if err != nil {
done <- fmt.Errorf("connect to forwarded port failed: %v", err)
}
}()
select {
case err := <-done:
if err != nil {
return fmt.Errorf("error connecting to tunnel: %w", err)
}
return nil
case <-ctx.Done():
return nil
}
}
// ForwardPort informs the host that we would like to forward the given port.
func (fwd *CodespacesPortForwarder) ForwardPort(ctx context.Context, opts ForwardPortOpts) error {
// Convert the port number to a uint16
port, err := convertIntToUint16(opts.Port)
if err != nil {
return fmt.Errorf("error converting port: %w", err)
}
// In v0.0.25 of dev-tunnels, the dev-tunnel manager `CreateTunnelPort` would "accept" requests that
// change the port protocol but they would not result in any actual change. This has changed, resulting in
// an error `Invalid arguments. The tunnel port protocol cannot be changed.`. It's not clear why the previous
// behaviour existed, whether it was truly the API version, or whether the `If-Not-Match` header being set inside
// `CreateTunnelPort` avoided the server accepting the request to change the protocol and that has since regressed.
//
// In any case, now we check whether a port exists with the given port number, if it does, we use the existing protocol.
// If it doesn't exist, we default to HTTP, which was the previous behaviour for all ports.
protocol := tunnels.TunnelProtocolHttp
existingPort, err := fwd.connection.TunnelManager.GetTunnelPort(ctx, fwd.connection.Tunnel, opts.Port, fwd.connection.Options)
if err != nil && !strings.Contains(err.Error(), "404") {
return fmt.Errorf("error checking whether tunnel port already exists: %v", err)
}
if existingPort != nil {
protocol = tunnels.TunnelProtocol(existingPort.Protocol)
}
tunnelPort := tunnels.NewTunnelPort(port, "", "", protocol)
// If no visibility is provided, Dev Tunnels will use the default (private)
if opts.Visibility != "" {
// Check if the requested visibility is allowed
allowed := false
for _, allowedVisibility := range fwd.connection.AllowedPortPrivacySettings {
if allowedVisibility == opts.Visibility {
allowed = true
break
}
}
// If the requested visibility is not allowed, return an error
if !allowed {
return fmt.Errorf("visibility %s is not allowed", opts.Visibility)
}
accessControlEntries := visibilityToAccessControlEntries(opts.Visibility)
if len(accessControlEntries) > 0 {
tunnelPort.AccessControl = &tunnels.TunnelAccessControl{
Entries: accessControlEntries,
}
}
}
// Tag the port as internal or user forwarded so we know if it needs to be shown in the UI
if opts.Internal {
tunnelPort.Labels = []string{InternalPortLabel}
} else {
tunnelPort.Labels = []string{UserForwardedPortLabel}
}
// Create the tunnel port
_, err = fwd.connection.TunnelManager.CreateTunnelPort(ctx, fwd.connection.Tunnel, tunnelPort, fwd.connection.Options)
if err != nil && !strings.Contains(err.Error(), "409") {
return fmt.Errorf("create tunnel port failed: %v", err)
}
// Connect to the tunnel
err = fwd.connection.Connect(ctx)
if err != nil {
return fmt.Errorf("connect failed: %v", err)
}
// Inform the host that we've forwarded the port locally
err = fwd.connection.TunnelClient.RefreshPorts(ctx)
if err != nil {
return fmt.Errorf("refresh ports failed: %v", err)
}
return nil
}
// connectListenerToForwardedPort connects to the forwarded port via a local TCP port.
func (fwd *CodespacesPortForwarder) connectListenerToForwardedPort(ctx context.Context, opts ForwardPortOpts, listener *net.TCPListener) (err error) {
errc := make(chan error, 1)
sendError := func(err error) {
// Use non-blocking send, to avoid goroutines getting
// stuck in case of concurrent or sequential errors.
select {
case errc <- err:
default:
}
}
go func() {
for {
conn, err := listener.AcceptTCP()
if err != nil {
sendError(err)
return
}
// Connect to the forwarded port in a goroutine so we can accept new connections
go func() {
if err := fwd.ConnectToForwardedPort(ctx, conn, opts); err != nil {
sendError(err)
}
}()
}
}()
// Wait for an error or for the context to be cancelled
select {
case err := <-errc:
return err
case <-ctx.Done():
return ctx.Err() // canceled
}
}
// ConnectToForwardedPort connects to the forwarded port via a given ReadWriteCloser.
// Optionally, it detects traffic over the connection and sends activity signals to the server to keep the codespace from shutting down.
func (fwd *CodespacesPortForwarder) ConnectToForwardedPort(ctx context.Context, conn io.ReadWriteCloser, opts ForwardPortOpts) error {
// Create a traffic monitor to keep the session alive
if opts.KeepAlive {
conn = newTrafficMonitor(conn, fwd)
}
// Convert the port number to a uint16
port, err := convertIntToUint16(opts.Port)
if err != nil {
return fmt.Errorf("error converting port: %w", err)
}
// Connect to the forwarded port
err = fwd.connection.TunnelClient.ConnectToForwardedPort(ctx, conn, port)
if err != nil {
return fmt.Errorf("error connecting to forwarded port: %w", err)
}
return nil
}
// ListPorts fetches the list of ports that are currently forwarded.
func (fwd *CodespacesPortForwarder) ListPorts(ctx context.Context) (ports []*tunnels.TunnelPort, err error) {
ports, err = fwd.connection.TunnelManager.ListTunnelPorts(ctx, fwd.connection.Tunnel, fwd.connection.Options)
if err != nil {
return nil, fmt.Errorf("error listing ports: %w", err)
}
return ports, nil
}
// UpdatePortVisibility changes the visibility (private, org, public) of the specified port.
func (fwd *CodespacesPortForwarder) UpdatePortVisibility(ctx context.Context, remotePort int, visibility string) error {
tunnelPort, err := fwd.connection.TunnelManager.GetTunnelPort(ctx, fwd.connection.Tunnel, remotePort, fwd.connection.Options)
if err != nil {
return fmt.Errorf("error getting tunnel port: %w", err)
}
// If the port visibility isn't changing, don't do anything
if AccessControlEntriesToVisibility(tunnelPort.AccessControl.Entries) == visibility {
return nil
}
// Delete the existing tunnel port to update
err = fwd.connection.TunnelManager.DeleteTunnelPort(ctx, fwd.connection.Tunnel, uint16(remotePort), fwd.connection.Options)
if err != nil {
return fmt.Errorf("error deleting tunnel port: %w", err)
}
done := make(chan error)
go func() {
// Connect to the tunnel
err = fwd.connection.Connect(ctx)
if err != nil {
done <- fmt.Errorf("connect failed: %v", err)
return
}
// Inform the host that we've deleted the port
err = fwd.connection.TunnelClient.RefreshPorts(ctx)
if err != nil {
done <- fmt.Errorf("refresh ports failed: %v", err)
return
}
// Re-forward the port with the updated visibility
err = fwd.ForwardPort(ctx, ForwardPortOpts{Port: remotePort, Visibility: visibility})
if err != nil {
done <- fmt.Errorf("error forwarding port: %w", err)
return
}
done <- nil
}()
// Wait for the done channel to be closed
select {
case err := <-done:
if err != nil {
// If we fail to re-forward the port, we need to forward again with the original visibility so the port is still accessible
_ = fwd.ForwardPort(ctx, ForwardPortOpts{Port: remotePort, Visibility: AccessControlEntriesToVisibility(tunnelPort.AccessControl.Entries)})
return fmt.Errorf("error connecting to tunnel: %w", err)
}
return nil
case <-ctx.Done():
return nil
}
}
// KeepAlive accepts a reason that is retained if there is no active reason
// to send to the server.
func (fwd *CodespacesPortForwarder) KeepAlive(reason string) {
select {
case fwd.keepAliveReason <- reason:
default:
// there is already an active keep alive reason
// so we can ignore this one
}
}
// GetKeepAliveReason fetches the keep alive reason from the channel and returns it.
func (fwd *CodespacesPortForwarder) GetKeepAliveReason() string {
return <-fwd.keepAliveReason
}
// Close closes the port forwarder's tunnel client connection.
func (fwd *CodespacesPortForwarder) Close() error {
return fwd.connection.Close()
}
// AccessControlEntriesToVisibility converts the access control entries used by Dev Tunnels to a friendly visibility value.
func AccessControlEntriesToVisibility(accessControlEntries []tunnels.TunnelAccessControlEntry) string {
for _, entry := range accessControlEntries {
// If we have the anonymous type (and we're not denying it), it's public
if (entry.Type == tunnels.TunnelAccessControlEntryTypeAnonymous) && (!entry.IsDeny) {
return PublicPortVisibility
}
// If we have the organizations type (and we're not denying it), it's org
if (entry.Provider == string(tunnels.TunnelAuthenticationSchemeGitHub)) && (!entry.IsDeny) {
return OrgPortVisibility
}
}
// Else, it's private
return PrivatePortVisibility
}
// visibilityToAccessControlEntries converts the given visibility to access control entries that can be used by Dev Tunnels.
func visibilityToAccessControlEntries(visibility string) []tunnels.TunnelAccessControlEntry {
switch visibility {
case PublicPortVisibility:
return []tunnels.TunnelAccessControlEntry{{
Type: tunnels.TunnelAccessControlEntryTypeAnonymous,
Subjects: []string{},
Scopes: []string{string(tunnels.TunnelAccessScopeConnect)},
}}
case OrgPortVisibility:
return []tunnels.TunnelAccessControlEntry{{
Type: tunnels.TunnelAccessControlEntryTypeOrganizations,
Subjects: []string{githubSubjectId},
Scopes: []string{
string(tunnels.TunnelAccessScopeConnect),
},
Provider: string(tunnels.TunnelAuthenticationSchemeGitHub),
}}
default:
// The tunnel manager doesn't accept empty access control entries, so we need to return a deny entry
return []tunnels.TunnelAccessControlEntry{{
Type: tunnels.TunnelAccessControlEntryTypeOrganizations,
Subjects: []string{githubSubjectId},
Scopes: []string{},
IsDeny: true,
}}
}
}
// IsInternalPort returns true if the port is internal.
func IsInternalPort(port *tunnels.TunnelPort) bool {
for _, label := range port.Labels {
if strings.EqualFold(label, InternalPortLabel) {
return true
}
}
return false
}
// convertIntToUint16 converts the given int to a uint16.
func convertIntToUint16(port int) (uint16, error) {
var updatedPort uint16
if port >= 0 && port <= 65535 {
updatedPort = uint16(port)
} else {
return 0, fmt.Errorf("invalid port number: %d", port)
}
return updatedPort, nil
}
// trafficMonitor implements io.Reader. It keeps the session alive by notifying
// it of the traffic type during Read operations.
type trafficMonitor struct {
rwc io.ReadWriteCloser
fwd PortForwarder
}
// newTrafficMonitor returns a trafficMonitor for the specified codespace connection.
// It wraps the provided io.ReaderWriteCloser with its own Read/Write/Close methods.
func newTrafficMonitor(rwc io.ReadWriteCloser, fwd PortForwarder) *trafficMonitor {
return &trafficMonitor{rwc, fwd}
}
// Read wraps the underlying ReadWriteCloser's Read method and keeps the session alive with the "input" traffic type.
func (t *trafficMonitor) Read(p []byte) (n int, err error) {
t.fwd.KeepAlive(trafficTypeInput)
return t.rwc.Read(p)
}
// Write wraps the underlying ReadWriteCloser's Write method and keeps the session alive with the "output" traffic type.
func (t *trafficMonitor) Write(p []byte) (n int, err error) {
t.fwd.KeepAlive(trafficTypeOutput)
return t.rwc.Write(p)
}
// Close closes the underlying ReadWriteCloser.
func (t *trafficMonitor) Close() error {
return t.rwc.Close()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/api/api.go | internal/codespaces/api/api.go | package api
// For descriptions of service interfaces, see:
// - https://docs.github.com/en/rest/reference/repos (for api.github.com)
// - https://github.com/github/github/blob/master/app/api/codespaces.rb (for vscs_internal)
// TODO(adonovan): replace the last link with a public doc URL when available.
// TODO(adonovan): a possible reorganization would be to split this
// file into two internal packages, one per backend service, and to
// rename api.API to github.Client:
//
// - github.GetUser(github.Client)
// - github.GetRepository(Client)
// - github.ReadFile(Client, nwo, branch, path) // was GetCodespaceRepositoryContents
// - codespaces.Create(Client, user, repo, sku, branch, location)
// - codespaces.Delete(Client, user, token, name)
// - codespaces.Get(Client, token, owner, name)
// - codespaces.GetMachineTypes(Client, user, repo, branch, location)
// - codespaces.GetToken(Client, login, name)
// - codespaces.List(Client, user)
// - codespaces.Start(Client, token, codespace)
//
// This would make the meaning of each operation clearer.
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/opentracing/opentracing-go"
)
const (
defaultAPIURL = "https://api.github.com"
defaultServerURL = "https://github.com"
)
const (
VSCSTargetLocal = "local"
VSCSTargetDevelopment = "development"
VSCSTargetPPE = "ppe"
VSCSTargetProduction = "production"
)
// API is the interface to the codespace service.
type API struct {
client func() (*http.Client, error)
githubAPI string
githubServer string
retryBackoff time.Duration
}
// New creates a new API client connecting to the configured endpoints with the HTTP client.
func New(f *cmdutil.Factory) *API {
apiURL := os.Getenv("GITHUB_API_URL")
if apiURL == "" {
cfg, err := f.Config()
if err != nil {
// fallback to the default api endpoint
apiURL = defaultAPIURL
} else {
host, _ := cfg.Authentication().DefaultHost()
apiURL = ghinstance.RESTPrefix(host)
}
}
serverURL := os.Getenv("GITHUB_SERVER_URL")
if serverURL == "" {
cfg, err := f.Config()
if err != nil {
// fallback to the default server endpoint
serverURL = defaultServerURL
} else {
host, _ := cfg.Authentication().DefaultHost()
serverURL = ghinstance.HostPrefix(host)
}
}
return &API{
client: f.HttpClient,
githubAPI: strings.TrimSuffix(apiURL, "/"),
githubServer: strings.TrimSuffix(serverURL, "/"),
retryBackoff: 100 * time.Millisecond,
}
}
// User represents a GitHub user.
type User struct {
Login string `json:"login"`
Type string `json:"type"`
}
// ServerURL returns the server url (not the API url), such as https://github.com
func (a *API) ServerURL() string {
return a.githubServer
}
// GetUser returns the user associated with the given token.
func (a *API) GetUser(ctx context.Context) (*User, error) {
req, err := http.NewRequest(http.MethodGet, a.githubAPI+"/user", nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, "/user")
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response User
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
return &response, nil
}
// RepositoryOwner represents owner of a repository
type RepositoryOwner struct {
Type string `json:"type"`
Login string `json:"login"`
}
// Repository represents a GitHub repository.
type Repository struct {
ID int `json:"id"`
FullName string `json:"full_name"`
DefaultBranch string `json:"default_branch"`
Owner RepositoryOwner `json:"owner"`
}
// GetRepository returns the repository associated with the given owner and name.
func (a *API) GetRepository(ctx context.Context, nwo string) (*Repository, error) {
req, err := http.NewRequest(http.MethodGet, a.githubAPI+"/repos/"+strings.ToLower(nwo), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, "/repos/*")
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response Repository
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
return &response, nil
}
// Codespace represents a codespace.
// You can see more about the fields in this type in the codespaces api docs:
// https://docs.github.com/en/rest/reference/codespaces
type Codespace struct {
Name string `json:"name"`
CreatedAt string `json:"created_at"`
DisplayName string `json:"display_name"`
LastUsedAt string `json:"last_used_at"`
Owner User `json:"owner"`
Repository Repository `json:"repository"`
State string `json:"state"`
GitStatus CodespaceGitStatus `json:"git_status"`
Connection CodespaceConnection `json:"connection"`
Machine CodespaceMachine `json:"machine"`
RuntimeConstraints RuntimeConstraints `json:"runtime_constraints"`
VSCSTarget string `json:"vscs_target"`
PendingOperation bool `json:"pending_operation"`
PendingOperationDisabledReason string `json:"pending_operation_disabled_reason"`
IdleTimeoutNotice string `json:"idle_timeout_notice"`
WebURL string `json:"web_url"`
DevContainerPath string `json:"devcontainer_path"`
Prebuild bool `json:"prebuild"`
Location string `json:"location"`
IdleTimeoutMinutes int `json:"idle_timeout_minutes"`
RetentionPeriodMinutes int `json:"retention_period_minutes"`
RetentionExpiresAt string `json:"retention_expires_at"`
RecentFolders []string `json:"recent_folders"`
BillableOwner User `json:"billable_owner"`
EnvironmentId string `json:"environment_id"`
}
type CodespaceGitStatus struct {
Ahead int `json:"ahead"`
Behind int `json:"behind"`
Ref string `json:"ref"`
HasUnpushedChanges bool `json:"has_unpushed_changes"`
HasUncommittedChanges bool `json:"has_uncommitted_changes"`
}
type CodespaceMachine struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
OperatingSystem string `json:"operating_system"`
StorageInBytes uint64 `json:"storage_in_bytes"`
MemoryInBytes uint64 `json:"memory_in_bytes"`
CPUCount int `json:"cpus"`
}
const (
// CodespaceStateAvailable is the state for a running codespace environment.
CodespaceStateAvailable = "Available"
// CodespaceStateShutdown is the state for a shutdown codespace environment.
CodespaceStateShutdown = "Shutdown"
// CodespaceStateShuttingDown is the state for a shutting down codespace environment.
CodespaceStateShuttingDown = "ShuttingDown"
// CodespaceStateStarting is the state for a starting codespace environment.
CodespaceStateStarting = "Starting"
// CodespaceStateRebuilding is the state for a rebuilding codespace environment.
CodespaceStateRebuilding = "Rebuilding"
)
type CodespaceConnection struct {
TunnelProperties TunnelProperties `json:"tunnelProperties"`
}
type TunnelProperties struct {
ConnectAccessToken string `json:"connectAccessToken"`
ManagePortsAccessToken string `json:"managePortsAccessToken"`
ServiceUri string `json:"serviceUri"`
TunnelId string `json:"tunnelId"`
ClusterId string `json:"clusterId"`
Domain string `json:"domain"`
}
type RuntimeConstraints struct {
AllowedPortPrivacySettings []string `json:"allowed_port_privacy_settings"`
}
// ListCodespaceFields is the list of exportable fields for a codespace when using the `gh cs list` command.
var ListCodespaceFields = []string{
"displayName",
"name",
"owner",
"repository",
"state",
"gitStatus",
"createdAt",
"lastUsedAt",
"machineName",
"vscsTarget",
}
// ViewCodespaceFields is the list of exportable fields for a codespace when using the `gh cs view` command.
var ViewCodespaceFields = []string{
"name",
"displayName",
"state",
"owner",
"billableOwner",
"location",
"repository",
"gitStatus",
"devcontainerPath",
"machineName",
"machineDisplayName",
"prebuild",
"createdAt",
"lastUsedAt",
"idleTimeoutMinutes",
"retentionPeriodDays",
"retentionExpiresAt",
"recentFolders",
"vscsTarget",
"environmentId",
}
func (c *Codespace) ExportData(fields []string) map[string]interface{} {
v := reflect.ValueOf(c).Elem()
data := map[string]interface{}{}
for _, f := range fields {
switch f {
case "owner":
data[f] = c.Owner.Login
case "repository":
data[f] = c.Repository.FullName
case "machineName":
data[f] = c.Machine.Name
case "machineDisplayName":
data[f] = c.Machine.DisplayName
case "retentionPeriodDays":
data[f] = c.RetentionPeriodMinutes / 1440
case "gitStatus":
data[f] = map[string]interface{}{
"ref": c.GitStatus.Ref,
"hasUnpushedChanges": c.GitStatus.HasUnpushedChanges,
"hasUncommittedChanges": c.GitStatus.HasUncommittedChanges,
"ahead": c.GitStatus.Ahead,
"behind": c.GitStatus.Behind,
}
case "vscsTarget":
if c.VSCSTarget != "" && c.VSCSTarget != VSCSTargetProduction {
data[f] = c.VSCSTarget
}
default:
sf := v.FieldByNameFunc(func(s string) bool {
return strings.EqualFold(f, s)
})
data[f] = sf.Interface()
}
}
return data
}
type ListCodespacesOptions struct {
OrgName string
UserName string
RepoName string
Limit int
}
// ListCodespaces returns a list of codespaces for the user. Pass a negative limit to request all pages from
// the API until all codespaces have been fetched.
func (a *API) ListCodespaces(ctx context.Context, opts ListCodespacesOptions) (codespaces []*Codespace, err error) {
var (
perPage = 100
limit = opts.Limit
)
if limit > 0 && limit < 100 {
perPage = limit
}
var (
listURL string
spanName string
)
if opts.RepoName != "" {
listURL = fmt.Sprintf("%s/repos/%s/codespaces?per_page=%d", a.githubAPI, opts.RepoName, perPage)
spanName = "/repos/*/codespaces"
} else if opts.OrgName != "" {
// the endpoints below can only be called by the organization admins
orgName := opts.OrgName
if opts.UserName != "" {
userName := opts.UserName
listURL = fmt.Sprintf("%s/orgs/%s/members/%s/codespaces?per_page=%d", a.githubAPI, orgName, userName, perPage)
spanName = "/orgs/*/members/*/codespaces"
} else {
listURL = fmt.Sprintf("%s/orgs/%s/codespaces?per_page=%d", a.githubAPI, orgName, perPage)
spanName = "/orgs/*/codespaces"
}
} else {
listURL = fmt.Sprintf("%s/user/codespaces?per_page=%d", a.githubAPI, perPage)
spanName = "/user/codespaces"
}
for {
req, err := http.NewRequest(http.MethodGet, listURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, spanName)
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
var response struct {
Codespaces []*Codespace `json:"codespaces"`
}
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(&response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
nextURL := findNextPage(resp.Header.Get("Link"))
codespaces = append(codespaces, response.Codespaces...)
if nextURL == "" || (limit > 0 && len(codespaces) >= limit) {
break
}
if newPerPage := limit - len(codespaces); limit > 0 && newPerPage < 100 {
u, _ := url.Parse(nextURL)
q := u.Query()
q.Set("per_page", strconv.Itoa(newPerPage))
u.RawQuery = q.Encode()
listURL = u.String()
} else {
listURL = nextURL
}
}
return codespaces, nil
}
var linkRE = regexp.MustCompile(`<([^>]+)>;\s*rel="([^"]+)"`)
func findNextPage(linkValue string) string {
for _, m := range linkRE.FindAllStringSubmatch(linkValue, -1) {
if len(m) > 2 && m[2] == "next" {
return m[1]
}
}
return ""
}
func (a *API) GetOrgMemberCodespace(ctx context.Context, orgName string, userName string, codespaceName string) (*Codespace, error) {
perPage := 100
listURL := fmt.Sprintf("%s/orgs/%s/members/%s/codespaces?per_page=%d", a.githubAPI, orgName, userName, perPage)
for {
req, err := http.NewRequest(http.MethodGet, listURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, "/orgs/*/members/*/codespaces")
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
var response struct {
Codespaces []*Codespace `json:"codespaces"`
}
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(&response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
for _, cs := range response.Codespaces {
if cs.Name == codespaceName {
return cs, nil
}
}
nextURL := findNextPage(resp.Header.Get("Link"))
if nextURL == "" {
break
}
listURL = nextURL
}
return nil, fmt.Errorf("codespace not found for user %s with name %s", userName, codespaceName)
}
// GetCodespace returns the user codespace based on the provided name.
// If the codespace is not found, an error is returned.
// If includeConnection is true, it will return the connection information for the codespace.
func (a *API) GetCodespace(ctx context.Context, codespaceName string, includeConnection bool) (*Codespace, error) {
resp, err := a.withRetry(func() (*http.Response, error) {
req, err := http.NewRequest(
http.MethodGet,
a.githubAPI+"/user/codespaces/"+codespaceName,
nil,
)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
if includeConnection {
q := req.URL.Query()
q.Add("internal", "true")
q.Add("refresh", "true")
req.URL.RawQuery = q.Encode()
}
a.setHeaders(req)
return a.do(ctx, req, "/user/codespaces/*")
})
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response Codespace
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
return &response, nil
}
// StartCodespace starts a codespace for the user.
// If the codespace is already running, the returned error from the API is ignored.
func (a *API) StartCodespace(ctx context.Context, codespaceName string) error {
resp, err := a.withRetry(func() (*http.Response, error) {
req, err := http.NewRequest(
http.MethodPost,
a.githubAPI+"/user/codespaces/"+codespaceName+"/start",
nil,
)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
return a.do(ctx, req, "/user/codespaces/*/start")
})
if err != nil {
return fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusConflict {
// 409 means the codespace is already running which we can safely ignore
return nil
}
return api.HandleHTTPError(resp)
}
return nil
}
func (a *API) StopCodespace(ctx context.Context, codespaceName string, orgName string, userName string) error {
var stopURL string
var spanName string
if orgName != "" {
stopURL = fmt.Sprintf("%s/orgs/%s/members/%s/codespaces/%s/stop", a.githubAPI, orgName, userName, codespaceName)
spanName = "/orgs/*/members/*/codespaces/*/stop"
} else {
stopURL = fmt.Sprintf("%s/user/codespaces/%s/stop", a.githubAPI, codespaceName)
spanName = "/user/codespaces/*/stop"
}
req, err := http.NewRequest(http.MethodPost, stopURL, nil)
if err != nil {
return fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, spanName)
if err != nil {
return fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return api.HandleHTTPError(resp)
}
return nil
}
type Machine struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
PrebuildAvailability string `json:"prebuild_availability"`
}
// GetCodespacesMachines returns the codespaces machines for the given repo, branch and location.
func (a *API) GetCodespacesMachines(ctx context.Context, repoID int, branch, location string, devcontainerPath string) ([]*Machine, error) {
reqURL := fmt.Sprintf("%s/repositories/%d/codespaces/machines", a.githubAPI, repoID)
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
q := req.URL.Query()
q.Add("location", location)
q.Add("ref", branch)
q.Add("devcontainer_path", devcontainerPath)
req.URL.RawQuery = q.Encode()
a.setHeaders(req)
resp, err := a.do(ctx, req, "/repositories/*/codespaces/machines")
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response struct {
Machines []*Machine `json:"machines"`
}
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
return response.Machines, nil
}
// GetCodespacesPermissionsCheck returns a bool indicating whether the user has accepted permissions for the given repo and devcontainer path.
func (a *API) GetCodespacesPermissionsCheck(ctx context.Context, repoID int, branch string, devcontainerPath string) (bool, error) {
reqURL := fmt.Sprintf("%s/repositories/%d/codespaces/permissions_check", a.githubAPI, repoID)
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return false, fmt.Errorf("error creating request: %w", err)
}
q := req.URL.Query()
q.Add("ref", branch)
q.Add("devcontainer_path", devcontainerPath)
req.URL.RawQuery = q.Encode()
a.setHeaders(req)
resp, err := a.do(ctx, req, "/repositories/*/codespaces/permissions_check")
if err != nil {
return false, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return false, fmt.Errorf("error reading response body: %w", err)
}
var response struct {
Accepted bool `json:"accepted"`
}
if err := json.Unmarshal(b, &response); err != nil {
return false, fmt.Errorf("error unmarshalling response: %w", err)
}
return response.Accepted, nil
}
// RepoSearchParameters are the optional parameters for searching for repositories.
type RepoSearchParameters struct {
// The maximum number of repos to return. At most 100 repos are returned even if this value is greater than 100.
MaxRepos int
// The sort order for returned repos. Possible values are 'stars', 'forks', 'help-wanted-issues', or 'updated'. If empty the API's default ordering is used.
Sort string
}
// GetCodespaceRepoSuggestions searches for and returns repo names based on the provided search text.
func (a *API) GetCodespaceRepoSuggestions(ctx context.Context, partialSearch string, parameters RepoSearchParameters) ([]string, error) {
reqURL := fmt.Sprintf("%s/search/repositories", a.githubAPI)
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
parts := strings.SplitN(partialSearch, "/", 2)
var nameSearch string
if len(parts) == 2 {
user := parts[0]
repo := parts[1]
nameSearch = fmt.Sprintf("%s user:%s", repo, user)
} else {
/*
* This results in searching for the text within the owner or the name. It's possible to
* do an owner search and then look up some repos for those owners, but that adds a
* good amount of latency to the fetch which slows down showing the suggestions.
*/
nameSearch = partialSearch
}
queryStr := fmt.Sprintf("%s in:name", nameSearch)
q := req.URL.Query()
q.Add("q", queryStr)
if len(parameters.Sort) > 0 {
q.Add("sort", parameters.Sort)
}
if parameters.MaxRepos > 0 {
q.Add("per_page", strconv.Itoa(parameters.MaxRepos))
}
req.URL.RawQuery = q.Encode()
a.setHeaders(req)
resp, err := a.do(ctx, req, "/search/repositories/*")
if err != nil {
return nil, fmt.Errorf("error searching repositories: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response struct {
Items []*Repository `json:"items"`
}
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
repoNames := make([]string, len(response.Items))
for i, repo := range response.Items {
repoNames[i] = repo.FullName
}
return repoNames, nil
}
// GetCodespaceBillableOwner returns the billable owner and expected default values for
// codespaces created by the user for a given repository.
func (a *API) GetCodespaceBillableOwner(ctx context.Context, nwo string) (*User, error) {
req, err := http.NewRequest(http.MethodGet, a.githubAPI+"/repos/"+nwo+"/codespaces/new", nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, "/repos/*/codespaces/new")
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, nil
} else if resp.StatusCode == http.StatusForbidden {
return nil, fmt.Errorf("you cannot create codespaces with that repository")
} else if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response struct {
BillableOwner User `json:"billable_owner"`
Defaults struct {
DevcontainerPath string `json:"devcontainer_path"`
Location string `json:"location"`
}
}
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
// While this response contains further helpful information ahead of codespace creation,
// we're only referencing the billable owner today.
return &response.BillableOwner, nil
}
// CreateCodespaceParams are the required parameters for provisioning a Codespace.
type CreateCodespaceParams struct {
RepositoryID int
IdleTimeoutMinutes int
RetentionPeriodMinutes *int
Branch string
Machine string
Location string
DevContainerPath string
VSCSTarget string
VSCSTargetURL string
PermissionsOptOut bool
DisplayName string
}
// CreateCodespace creates a codespace with the given parameters and returns a non-nil error if it
// fails to create.
func (a *API) CreateCodespace(ctx context.Context, params *CreateCodespaceParams) (*Codespace, error) {
codespace, err := a.startCreate(ctx, params)
if !errors.Is(err, errProvisioningInProgress) {
return codespace, err
}
// errProvisioningInProgress indicates that codespace creation did not complete
// within the GitHub API RPC time limit (10s), so it continues asynchronously.
// We must poll the server to discover the outcome.
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
codespace, err = a.GetCodespace(ctx, codespace.Name, false)
if err != nil {
return nil, fmt.Errorf("failed to get codespace: %w", err)
}
// we continue to poll until the codespace shows as provisioned
if codespace.State != CodespaceStateAvailable {
continue
}
return codespace, nil
}
}
}
type startCreateRequest struct {
RepositoryID int `json:"repository_id"`
IdleTimeoutMinutes int `json:"idle_timeout_minutes,omitempty"`
RetentionPeriodMinutes *int `json:"retention_period_minutes,omitempty"`
Ref string `json:"ref"`
Location string `json:"location"`
Machine string `json:"machine"`
DevContainerPath string `json:"devcontainer_path,omitempty"`
VSCSTarget string `json:"vscs_target,omitempty"`
VSCSTargetURL string `json:"vscs_target_url,omitempty"`
PermissionsOptOut bool `json:"multi_repo_permissions_opt_out"`
DisplayName string `json:"display_name"`
}
var errProvisioningInProgress = errors.New("provisioning in progress")
type AcceptPermissionsRequiredError struct {
Message string `json:"message"`
AllowPermissionsURL string `json:"allow_permissions_url"`
}
func (e AcceptPermissionsRequiredError) Error() string {
return e.Message
}
// startCreate starts the creation of a codespace.
// It may return success or an error, or errProvisioningInProgress indicating that the operation
// did not complete before the GitHub API's time limit for RPCs (10s), in which case the caller
// must poll the server to learn the outcome.
func (a *API) startCreate(ctx context.Context, params *CreateCodespaceParams) (*Codespace, error) {
if params == nil {
return nil, errors.New("startCreate missing parameters")
}
requestBody, err := json.Marshal(startCreateRequest{
RepositoryID: params.RepositoryID,
IdleTimeoutMinutes: params.IdleTimeoutMinutes,
RetentionPeriodMinutes: params.RetentionPeriodMinutes,
Ref: params.Branch,
Location: params.Location,
Machine: params.Machine,
DevContainerPath: params.DevContainerPath,
VSCSTarget: params.VSCSTarget,
VSCSTargetURL: params.VSCSTargetURL,
PermissionsOptOut: params.PermissionsOptOut,
DisplayName: params.DisplayName,
})
if err != nil {
return nil, fmt.Errorf("error marshaling request: %w", err)
}
req, err := http.NewRequest(http.MethodPost, a.githubAPI+"/user/codespaces", bytes.NewBuffer(requestBody))
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, "/user/codespaces")
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusAccepted {
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response Codespace
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
return &response, errProvisioningInProgress // RPC finished before result of creation known
} else if resp.StatusCode == http.StatusUnauthorized {
var (
ue AcceptPermissionsRequiredError
bodyCopy = &bytes.Buffer{}
r = io.TeeReader(resp.Body, bodyCopy)
)
b, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
if err := json.Unmarshal(b, &ue); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
if ue.AllowPermissionsURL != "" {
return nil, ue
}
resp.Body = io.NopCloser(bodyCopy)
return nil, api.HandleHTTPError(resp)
} else if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
var response Codespace
if err := json.Unmarshal(b, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
return &response, nil
}
// DeleteCodespace deletes the given codespace.
func (a *API) DeleteCodespace(ctx context.Context, codespaceName string, orgName string, userName string) error {
var deleteURL string
var spanName string
if orgName != "" && userName != "" {
deleteURL = fmt.Sprintf("%s/orgs/%s/members/%s/codespaces/%s", a.githubAPI, orgName, userName, codespaceName)
spanName = "/orgs/*/members/*/codespaces/*"
} else {
deleteURL = a.githubAPI + "/user/codespaces/" + codespaceName
spanName = "/user/codespaces/*"
}
req, err := http.NewRequest(http.MethodDelete, deleteURL, nil)
if err != nil {
return fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, spanName)
if err != nil {
return fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
return api.HandleHTTPError(resp)
}
return nil
}
type DevContainerEntry struct {
Path string `json:"path"`
Name string `json:"name,omitempty"`
}
// ListDevContainers returns a list of valid devcontainer.json files for the repo. Pass a negative limit to request all pages from
// the API until all devcontainer.json files have been fetched.
func (a *API) ListDevContainers(ctx context.Context, repoID int, branch string, limit int) (devcontainers []DevContainerEntry, err error) {
perPage := 100
if limit > 0 && limit < 100 {
perPage = limit
}
v := url.Values{}
v.Set("per_page", strconv.Itoa(perPage))
if branch != "" {
v.Set("ref", branch)
}
listURL := fmt.Sprintf("%s/repositories/%d/codespaces/devcontainers?%s", a.githubAPI, repoID, v.Encode())
for {
req, err := http.NewRequest(http.MethodGet, listURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
a.setHeaders(req)
resp, err := a.do(ctx, req, fmt.Sprintf("/repositories/%d/codespaces/devcontainers", repoID))
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, api.HandleHTTPError(resp)
}
var response struct {
Devcontainers []DevContainerEntry `json:"devcontainers"`
}
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(&response); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
nextURL := findNextPage(resp.Header.Get("Link"))
devcontainers = append(devcontainers, response.Devcontainers...)
if nextURL == "" || (limit > 0 && len(devcontainers) >= limit) {
break
}
if newPerPage := limit - len(devcontainers); limit > 0 && newPerPage < 100 {
u, _ := url.Parse(nextURL)
q := u.Query()
q.Set("per_page", strconv.Itoa(newPerPage))
u.RawQuery = q.Encode()
listURL = u.String()
} else {
listURL = nextURL
}
}
return devcontainers, nil
}
type EditCodespaceParams struct {
DisplayName string `json:"display_name,omitempty"`
IdleTimeoutMinutes int `json:"idle_timeout_minutes,omitempty"`
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/codespaces/api/api_test.go | internal/codespaces/api/api_test.go | package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
ghmock "github.com/cli/cli/v2/internal/gh/mock"
"github.com/cli/cli/v2/pkg/cmdutil"
)
func generateCodespaceList(start int, end int) []*Codespace {
codespacesList := []*Codespace{}
for i := start; i < end; i++ {
codespacesList = append(codespacesList, &Codespace{
Name: fmt.Sprintf("codespace-%d", i),
})
}
return codespacesList
}
func createFakeListEndpointServer(t *testing.T, initialTotal int, finalTotal int) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/user/codespaces" {
t.Fatal("Incorrect path")
}
page := 1
if r.URL.Query().Get("page") != "" {
page, _ = strconv.Atoi(r.URL.Query().Get("page"))
}
per_page := 0
if r.URL.Query().Get("per_page") != "" {
per_page, _ = strconv.Atoi(r.URL.Query().Get("per_page"))
}
response := struct {
Codespaces []*Codespace `json:"codespaces"`
TotalCount int `json:"total_count"`
}{
Codespaces: []*Codespace{},
TotalCount: finalTotal,
}
switch page {
case 1:
response.Codespaces = generateCodespaceList(0, per_page)
response.TotalCount = initialTotal
w.Header().Set("Link", fmt.Sprintf(`<http://%[1]s/user/codespaces?page=3&per_page=%[2]d>; rel="last", <http://%[1]s/user/codespaces?page=2&per_page=%[2]d>; rel="next"`, r.Host, per_page))
case 2:
response.Codespaces = generateCodespaceList(per_page, per_page*2)
response.TotalCount = finalTotal
w.Header().Set("Link", fmt.Sprintf(`<http://%s/user/codespaces?page=3&per_page=%d>; rel="next"`, r.Host, per_page))
case 3:
response.Codespaces = generateCodespaceList(per_page*2, per_page*3-per_page/2)
response.TotalCount = finalTotal
default:
t.Fatal("Should not check extra page")
}
data, _ := json.Marshal(response)
fmt.Fprint(w, string(data))
}))
}
func createFakeCreateEndpointServer(t *testing.T, wantStatus int) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// create endpoint
if r.URL.Path == "/user/codespaces" {
body := r.Body
if body == nil {
t.Fatal("No body")
}
defer body.Close()
var params startCreateRequest
err := json.NewDecoder(body).Decode(¶ms)
if err != nil {
t.Fatal("error:", err)
}
if params.RepositoryID != 1 {
t.Fatal("Expected RepositoryID to be 1. Got: ", params.RepositoryID)
}
if params.IdleTimeoutMinutes != 10 {
t.Fatal("Expected IdleTimeoutMinutes to be 10. Got: ", params.IdleTimeoutMinutes)
}
if *params.RetentionPeriodMinutes != 0 {
t.Fatal("Expected RetentionPeriodMinutes to be 0. Got: ", *params.RetentionPeriodMinutes)
}
response := Codespace{
Name: "codespace-1",
DisplayName: params.DisplayName,
}
if wantStatus == 0 {
wantStatus = http.StatusCreated
}
w.WriteHeader(wantStatus)
enc := json.NewEncoder(w)
_ = enc.Encode(&response)
return
}
// get endpoint hit for testing pending status
if r.URL.Path == "/user/codespaces/codespace-1" {
response := Codespace{
Name: "codespace-1",
State: CodespaceStateAvailable,
}
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
_ = enc.Encode(&response)
return
}
t.Fatal("Incorrect path")
}))
}
func createHttpClient() (*http.Client, error) {
return &http.Client{}, nil
}
func TestNew_APIURL_dotcomConfig(t *testing.T) {
t.Setenv("GITHUB_API_URL", "")
t.Setenv("GITHUB_SERVER_URL", "https://github.com")
cfg := &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
return &config.AuthConfig{}
},
}
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return cfg, nil
},
}
api := New(f)
if api.githubAPI != "https://api.github.com" {
t.Fatalf("expected https://api.github.com, got %s", api.githubAPI)
}
if len(cfg.AuthenticationCalls()) != 1 {
t.Fatalf("API url was not pulled from the config")
}
}
func TestNew_APIURL_customConfig(t *testing.T) {
t.Setenv("GITHUB_API_URL", "")
t.Setenv("GITHUB_SERVER_URL", "https://github.mycompany.com")
cfg := &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
authCfg := &config.AuthConfig{}
authCfg.SetDefaultHost("github.mycompany.com", "GH_HOST")
return authCfg
},
}
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return cfg, nil
},
}
api := New(f)
if api.githubAPI != "https://github.mycompany.com/api/v3" {
t.Fatalf("expected https://github.mycompany.com/api/v3, got %s", api.githubAPI)
}
if len(cfg.AuthenticationCalls()) != 1 {
t.Fatalf("API url was not pulled from the config")
}
}
func TestNew_APIURL_env(t *testing.T) {
t.Setenv("GITHUB_API_URL", "https://api.mycompany.com")
t.Setenv("GITHUB_SERVER_URL", "https://mycompany.com")
cfg := &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
return &config.AuthConfig{}
},
}
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return cfg, nil
},
}
api := New(f)
if api.githubAPI != "https://api.mycompany.com" {
t.Fatalf("expected https://api.mycompany.com, got %s", api.githubAPI)
}
if len(cfg.AuthenticationCalls()) != 0 {
t.Fatalf("Configuration was checked instead of using the GITHUB_API_URL environment variable")
}
}
func TestNew_APIURL_dotcomFallback(t *testing.T) {
t.Setenv("GITHUB_API_URL", "")
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return nil, errors.New("Failed to load")
},
}
api := New(f)
if api.githubAPI != "https://api.github.com" {
t.Fatalf("expected https://api.github.com, got %s", api.githubAPI)
}
}
func TestNew_ServerURL_dotcomConfig(t *testing.T) {
t.Setenv("GITHUB_SERVER_URL", "")
t.Setenv("GITHUB_API_URL", "https://api.github.com")
cfg := &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
return &config.AuthConfig{}
},
}
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return cfg, nil
},
}
api := New(f)
if api.githubServer != "https://github.com" {
t.Fatalf("expected https://github.com, got %s", api.githubServer)
}
if len(cfg.AuthenticationCalls()) != 1 {
t.Fatalf("Server url was not pulled from the config")
}
}
func TestNew_ServerURL_customConfig(t *testing.T) {
t.Setenv("GITHUB_SERVER_URL", "")
t.Setenv("GITHUB_API_URL", "https://github.mycompany.com/api/v3")
cfg := &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
authCfg := &config.AuthConfig{}
authCfg.SetDefaultHost("github.mycompany.com", "GH_HOST")
return authCfg
},
}
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return cfg, nil
},
}
api := New(f)
if api.githubServer != "https://github.mycompany.com" {
t.Fatalf("expected https://github.mycompany.com, got %s", api.githubServer)
}
if len(cfg.AuthenticationCalls()) != 1 {
t.Fatalf("Server url was not pulled from the config")
}
}
func TestNew_ServerURL_env(t *testing.T) {
t.Setenv("GITHUB_SERVER_URL", "https://mycompany.com")
t.Setenv("GITHUB_API_URL", "https://api.mycompany.com")
cfg := &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
return &config.AuthConfig{}
},
}
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return cfg, nil
},
}
api := New(f)
if api.githubServer != "https://mycompany.com" {
t.Fatalf("expected https://mycompany.com, got %s", api.githubServer)
}
if len(cfg.AuthenticationCalls()) != 0 {
t.Fatalf("Configuration was checked instead of using the GITHUB_SERVER_URL environment variable")
}
}
func TestNew_ServerURL_dotcomFallback(t *testing.T) {
t.Setenv("GITHUB_SERVER_URL", "")
f := &cmdutil.Factory{
Config: func() (gh.Config, error) {
return nil, errors.New("Failed to load")
},
}
api := New(f)
if api.githubServer != "https://github.com" {
t.Fatalf("expected https://github.com, got %s", api.githubServer)
}
}
func TestCreateCodespaces(t *testing.T) {
svr := createFakeCreateEndpointServer(t, http.StatusCreated)
defer svr.Close()
api := API{
githubAPI: svr.URL,
client: createHttpClient,
}
ctx := context.TODO()
retentionPeriod := 0
params := &CreateCodespaceParams{
RepositoryID: 1,
IdleTimeoutMinutes: 10,
RetentionPeriodMinutes: &retentionPeriod,
}
codespace, err := api.CreateCodespace(ctx, params)
if err != nil {
t.Fatal(err)
}
if codespace.Name != "codespace-1" {
t.Fatalf("expected codespace-1, got %s", codespace.Name)
}
if codespace.DisplayName != "" {
t.Fatalf("expected display name empty, got %q", codespace.DisplayName)
}
}
func TestCreateCodespaces_displayName(t *testing.T) {
svr := createFakeCreateEndpointServer(t, http.StatusCreated)
defer svr.Close()
api := API{
githubAPI: svr.URL,
client: createHttpClient,
}
retentionPeriod := 0
codespace, err := api.CreateCodespace(context.Background(), &CreateCodespaceParams{
RepositoryID: 1,
IdleTimeoutMinutes: 10,
RetentionPeriodMinutes: &retentionPeriod,
DisplayName: "clucky cuckoo",
})
if err != nil {
t.Fatal(err)
}
if codespace.DisplayName != "clucky cuckoo" {
t.Fatalf("expected display name %q, got %q", "clucky cuckoo", codespace.DisplayName)
}
}
func TestCreateCodespaces_Pending(t *testing.T) {
svr := createFakeCreateEndpointServer(t, http.StatusAccepted)
defer svr.Close()
api := API{
githubAPI: svr.URL,
client: createHttpClient,
retryBackoff: 0,
}
ctx := context.TODO()
retentionPeriod := 0
params := &CreateCodespaceParams{
RepositoryID: 1,
IdleTimeoutMinutes: 10,
RetentionPeriodMinutes: &retentionPeriod,
}
codespace, err := api.CreateCodespace(ctx, params)
if err != nil {
t.Fatal(err)
}
if codespace.Name != "codespace-1" {
t.Fatalf("expected codespace-1, got %s", codespace.Name)
}
}
func TestListCodespaces_limited(t *testing.T) {
svr := createFakeListEndpointServer(t, 200, 200)
defer svr.Close()
api := API{
githubAPI: svr.URL,
client: createHttpClient,
}
ctx := context.TODO()
codespaces, err := api.ListCodespaces(ctx, ListCodespacesOptions{Limit: 200})
if err != nil {
t.Fatal(err)
}
if len(codespaces) != 200 {
t.Fatalf("expected 200 codespace, got %d", len(codespaces))
}
if codespaces[0].Name != "codespace-0" {
t.Fatalf("expected codespace-0, got %s", codespaces[0].Name)
}
if codespaces[199].Name != "codespace-199" {
t.Fatalf("expected codespace-199, got %s", codespaces[0].Name)
}
}
func TestListCodespaces_unlimited(t *testing.T) {
svr := createFakeListEndpointServer(t, 200, 200)
defer svr.Close()
api := API{
githubAPI: svr.URL,
client: createHttpClient,
}
ctx := context.TODO()
codespaces, err := api.ListCodespaces(ctx, ListCodespacesOptions{})
if err != nil {
t.Fatal(err)
}
if len(codespaces) != 250 {
t.Fatalf("expected 250 codespace, got %d", len(codespaces))
}
if codespaces[0].Name != "codespace-0" {
t.Fatalf("expected codespace-0, got %s", codespaces[0].Name)
}
if codespaces[249].Name != "codespace-249" {
t.Fatalf("expected codespace-249, got %s", codespaces[0].Name)
}
}
func TestGetRepoSuggestions(t *testing.T) {
tests := []struct {
searchText string // The input search string
queryText string // The wanted query string (based off searchText)
sort string // (Optional) The RepoSearchParameters.Sort param
maxRepos string // (Optional) The RepoSearchParameters.MaxRepos param
}{
{
searchText: "test",
queryText: "test",
},
{
searchText: "org/repo",
queryText: "repo user:org",
},
{
searchText: "org/repo/extra",
queryText: "repo/extra user:org",
},
{
searchText: "test",
queryText: "test",
sort: "stars",
maxRepos: "1000",
},
}
for _, tt := range tests {
runRepoSearchTest(t, tt.searchText, tt.queryText, tt.sort, tt.maxRepos)
}
}
func createFakeSearchReposServer(t *testing.T, wantSearchText string, wantSort string, wantPerPage string, responseRepos []*Repository) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/search/repositories" {
t.Error("Incorrect path")
return
}
query := r.URL.Query()
got := fmt.Sprintf("q=%q sort=%s per_page=%s", query.Get("q"), query.Get("sort"), query.Get("per_page"))
want := fmt.Sprintf("q=%q sort=%s per_page=%s", wantSearchText+" in:name", wantSort, wantPerPage)
if got != want {
t.Errorf("for query, got %s, want %s", got, want)
return
}
response := struct {
Items []*Repository `json:"items"`
}{
responseRepos,
}
if err := json.NewEncoder(w).Encode(response); err != nil {
t.Error(err)
}
}))
}
func runRepoSearchTest(t *testing.T, searchText, wantQueryText, wantSort, wantMaxRepos string) {
wantRepoNames := []string{"repo1", "repo2"}
apiResponseRepositories := make([]*Repository, 0)
for _, name := range wantRepoNames {
apiResponseRepositories = append(apiResponseRepositories, &Repository{FullName: name})
}
svr := createFakeSearchReposServer(t, wantQueryText, wantSort, wantMaxRepos, apiResponseRepositories)
defer svr.Close()
api := API{
githubAPI: svr.URL,
client: createHttpClient,
}
ctx := context.Background()
searchParameters := RepoSearchParameters{}
if len(wantSort) > 0 {
searchParameters.Sort = wantSort
}
if len(wantMaxRepos) > 0 {
searchParameters.MaxRepos, _ = strconv.Atoi(wantMaxRepos)
}
gotRepoNames, err := api.GetCodespaceRepoSuggestions(ctx, searchText, searchParameters)
if err != nil {
t.Fatal(err)
}
gotNamesStr := fmt.Sprintf("%v", gotRepoNames)
wantNamesStr := fmt.Sprintf("%v", wantRepoNames)
if gotNamesStr != wantNamesStr {
t.Fatalf("got repo names %s, want %s", gotNamesStr, wantNamesStr)
}
}
func TestRetries(t *testing.T) {
var callCount int
csName := "test_codespace"
handler := func(w http.ResponseWriter, r *http.Request) {
if callCount == 3 {
err := json.NewEncoder(w).Encode(Codespace{
Name: csName,
})
if err != nil {
t.Fatal(err)
}
return
}
callCount++
w.WriteHeader(502)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler(w, r) }))
t.Cleanup(srv.Close)
a := &API{
githubAPI: srv.URL,
client: createHttpClient,
}
cs, err := a.GetCodespace(context.Background(), "test", false)
if err != nil {
t.Fatal(err)
}
if callCount != 3 {
t.Fatalf("expected at least 2 retries but got %d", callCount)
}
if cs.Name != csName {
t.Fatalf("expected codespace name to be %q but got %q", csName, cs.Name)
}
callCount = 0
handler = func(w http.ResponseWriter, _ *http.Request) {
callCount++
err := json.NewEncoder(w).Encode(Codespace{
Name: csName,
})
if err != nil {
t.Fatal(err)
}
}
cs, err = a.GetCodespace(context.Background(), "test", false)
if err != nil {
t.Fatal(err)
}
if callCount != 1 {
t.Fatalf("expected no retries but got %d calls", callCount)
}
if cs.Name != csName {
t.Fatalf("expected codespace name to be %q but got %q", csName, cs.Name)
}
}
func TestCodespace_ExportData(t *testing.T) {
type fields struct {
Name string
CreatedAt string
DisplayName string
LastUsedAt string
Owner User
Repository Repository
State string
GitStatus CodespaceGitStatus
Connection CodespaceConnection
Machine CodespaceMachine
}
type args struct {
fields []string
}
tests := []struct {
name string
fields fields
args args
want map[string]interface{}
}{
{
name: "just name",
fields: fields{
Name: "test",
},
args: args{
fields: []string{"name"},
},
want: map[string]interface{}{
"name": "test",
},
},
{
name: "just owner",
fields: fields{
Owner: User{
Login: "test",
},
},
args: args{
fields: []string{"owner"},
},
want: map[string]interface{}{
"owner": "test",
},
},
{
name: "just machine",
fields: fields{
Machine: CodespaceMachine{
Name: "test",
},
},
args: args{
fields: []string{"machineName"},
},
want: map[string]interface{}{
"machineName": "test",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &Codespace{
Name: tt.fields.Name,
CreatedAt: tt.fields.CreatedAt,
DisplayName: tt.fields.DisplayName,
LastUsedAt: tt.fields.LastUsedAt,
Owner: tt.fields.Owner,
Repository: tt.fields.Repository,
State: tt.fields.State,
GitStatus: tt.fields.GitStatus,
Connection: tt.fields.Connection,
Machine: tt.fields.Machine,
}
if got := c.ExportData(tt.args.fields); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Codespace.ExportData() = %v, want %v", got, tt.want)
}
})
}
}
func createFakeEditServer(t *testing.T, codespaceName string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
checkPath := "/user/codespaces/" + codespaceName
if r.URL.Path != checkPath {
t.Fatal("Incorrect path")
}
if r.Method != http.MethodPatch {
t.Fatal("Incorrect method")
}
body := r.Body
if body == nil {
t.Fatal("No body")
}
defer body.Close()
var data map[string]interface{}
err := json.NewDecoder(body).Decode(&data)
if err != nil {
t.Fatal(err)
}
if data["display_name"] != "changeTo" {
t.Fatal("Incorrect display name")
}
response := Codespace{
DisplayName: "changeTo",
}
responseData, _ := json.Marshal(response)
fmt.Fprint(w, string(responseData))
}))
}
func TestAPI_EditCodespace(t *testing.T) {
type args struct {
ctx context.Context
codespaceName string
params *EditCodespaceParams
}
tests := []struct {
name string
args args
want *Codespace
wantErr bool
}{
{
name: "success",
args: args{
ctx: context.Background(),
codespaceName: "test",
params: &EditCodespaceParams{
DisplayName: "changeTo",
},
},
want: &Codespace{
DisplayName: "changeTo",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svr := createFakeEditServer(t, tt.args.codespaceName)
defer svr.Close()
a := &API{
client: createHttpClient,
githubAPI: svr.URL,
}
got, err := a.EditCodespace(tt.args.ctx, tt.args.codespaceName, tt.args.params)
if (err != nil) != tt.wantErr {
t.Errorf("API.EditCodespace() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("API.EditCodespace() = %v, want %v", got.DisplayName, tt.want.DisplayName)
}
})
}
}
func createFakeEditPendingOpServer() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPatch {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
if r.Method == http.MethodGet {
response := Codespace{
PendingOperation: true,
PendingOperationDisabledReason: "Some pending operation",
}
responseData, _ := json.Marshal(response)
fmt.Fprint(w, string(responseData))
return
}
}))
}
func TestAPI_EditCodespacePendingOperation(t *testing.T) {
svr := createFakeEditPendingOpServer()
defer svr.Close()
a := &API{
client: createHttpClient,
githubAPI: svr.URL,
}
_, err := a.EditCodespace(context.Background(), "disabledCodespace", &EditCodespaceParams{DisplayName: "some silly name"})
if err == nil {
t.Error("Expected pending operation error, but got nothing")
}
if err.Error() != "codespace is disabled while it has a pending operation: Some pending operation" {
t.Errorf("Expected pending operation error, but got %v", err)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/run/stub.go | internal/run/stub.go | package run
import (
"fmt"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
const (
gitAuthRE = `-c credential(?:\..+)?\.helper= -c credential(?:\..+)?\.helper=!"[^"]+" auth git-credential `
)
type T interface {
Helper()
Errorf(string, ...interface{})
}
// Stub installs a catch-all for all external commands invoked from gh. It returns a restore func that, when
// invoked from tests, fails the current test if some stubs that were registered were never matched.
func Stub() (*CommandStubber, func(T)) {
cs := &CommandStubber{}
teardown := setPrepareCmd(func(cmd *exec.Cmd) Runnable {
s := cs.find(cmd.Args)
if s == nil {
panic(fmt.Sprintf("no exec stub for `%s`", strings.Join(cmd.Args, " ")))
}
for _, c := range s.callbacks {
c(cmd.Args)
}
s.matched = true
return s
})
return cs, func(t T) {
defer teardown()
var unmatched []string
for _, s := range cs.stubs {
if s.matched {
continue
}
unmatched = append(unmatched, s.pattern.String())
}
if len(unmatched) == 0 {
return
}
t.Helper()
t.Errorf("unmatched exec stubs (%d): %s", len(unmatched), strings.Join(unmatched, ", "))
}
}
func setPrepareCmd(fn func(*exec.Cmd) Runnable) func() {
origPrepare := PrepareCmd
PrepareCmd = func(cmd *exec.Cmd) Runnable {
// normalize git executable name for consistency in tests
if baseName := filepath.Base(cmd.Args[0]); baseName == "git" || baseName == "git.exe" {
cmd.Args[0] = "git"
}
return fn(cmd)
}
return func() {
PrepareCmd = origPrepare
}
}
// CommandStubber stubs out invocations to external commands.
type CommandStubber struct {
stubs []*commandStub
}
// Register a stub for an external command. Pattern is a regular expression, output is the standard output
// from a command. Pass callbacks to inspect raw arguments that the command was invoked with.
func (cs *CommandStubber) Register(pattern string, exitStatus int, output string, callbacks ...CommandCallback) {
if len(pattern) < 1 {
panic("cannot use empty regexp pattern")
}
if strings.HasPrefix(pattern, "git") {
pattern = addGitAuthentication(pattern)
}
cs.stubs = append(cs.stubs, &commandStub{
pattern: regexp.MustCompile(pattern),
exitStatus: exitStatus,
stdout: output,
callbacks: callbacks,
})
}
func (cs *CommandStubber) find(args []string) *commandStub {
line := strings.Join(args, " ")
for _, s := range cs.stubs {
if !s.matched && s.pattern.MatchString(line) {
return s
}
}
return nil
}
type CommandCallback func([]string)
type commandStub struct {
pattern *regexp.Regexp
matched bool
exitStatus int
stdout string
callbacks []CommandCallback
}
type errWithExitCode struct {
message string
exitCode int
}
func (e errWithExitCode) Error() string {
return e.message
}
func (e errWithExitCode) ExitCode() int {
return e.exitCode
}
// Run satisfies Runnable
func (s *commandStub) Run() error {
if s.exitStatus != 0 {
// It's nontrivial to construct a fake `exec.ExitError` instance, so we return an error type
// that has the `ExitCode() int` method.
return errWithExitCode{
message: fmt.Sprintf("%s exited with status %d", s.pattern, s.exitStatus),
exitCode: s.exitStatus,
}
}
return nil
}
// Output satisfies Runnable
func (s *commandStub) Output() ([]byte, error) {
if err := s.Run(); err != nil {
return []byte(nil), err
}
return []byte(s.stdout), nil
}
// Inject git authentication string for specific git commands.
func addGitAuthentication(s string) string {
pattern := regexp.MustCompile(`( fetch | pull | push | clone | remote add.+-f | submodule )`)
loc := pattern.FindStringIndex(s)
if loc == nil {
return s
}
return s[:loc[0]+1] + gitAuthRE + s[loc[0]+1:]
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/run/run.go | internal/run/run.go | package run
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/cli/cli/v2/utils"
)
// Runnable is typically an exec.Cmd or its stub in tests
type Runnable interface {
Output() ([]byte, error)
Run() error
}
// PrepareCmd extends exec.Cmd with extra error reporting features and provides a
// hook to stub command execution in tests
var PrepareCmd = func(cmd *exec.Cmd) Runnable {
return &cmdWithStderr{cmd}
}
// cmdWithStderr augments exec.Cmd by adding stderr to the error message
type cmdWithStderr struct {
*exec.Cmd
}
func (c cmdWithStderr) Output() ([]byte, error) {
if isVerbose, _ := utils.IsDebugEnabled(); isVerbose {
_ = printArgs(os.Stderr, c.Cmd.Args)
}
out, err := c.Cmd.Output()
if c.Cmd.Stderr != nil || err == nil {
return out, err
}
cmdErr := &CmdError{
Args: c.Cmd.Args,
Err: err,
}
var exitError *exec.ExitError
if errors.As(err, &exitError) {
cmdErr.Stderr = bytes.NewBuffer(exitError.Stderr)
}
return out, cmdErr
}
func (c cmdWithStderr) Run() error {
if isVerbose, _ := utils.IsDebugEnabled(); isVerbose {
_ = printArgs(os.Stderr, c.Cmd.Args)
}
if c.Cmd.Stderr != nil {
return c.Cmd.Run()
}
errStream := &bytes.Buffer{}
c.Cmd.Stderr = errStream
err := c.Cmd.Run()
if err != nil {
err = &CmdError{
Args: c.Cmd.Args,
Err: err,
Stderr: errStream,
}
}
return err
}
// CmdError provides more visibility into why an exec.Cmd had failed
type CmdError struct {
Args []string
Err error
Stderr *bytes.Buffer
}
func (e CmdError) Error() string {
msg := e.Stderr.String()
if msg != "" && !strings.HasSuffix(msg, "\n") {
msg += "\n"
}
return fmt.Sprintf("%s%s: %s", msg, e.Args[0], e.Err)
}
func (e CmdError) Unwrap() error {
return e.Err
}
func printArgs(w io.Writer, args []string) error {
if len(args) > 0 {
// print commands, but omit the full path to an executable
args = append([]string{filepath.Base(args[0])}, args[1:]...)
}
_, err := fmt.Fprintf(w, "%v\n", args)
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/config/stub.go | internal/config/stub.go | package config
import (
"io"
"os"
"path/filepath"
"testing"
"github.com/cli/cli/v2/internal/gh"
ghmock "github.com/cli/cli/v2/internal/gh/mock"
"github.com/cli/cli/v2/internal/keyring"
o "github.com/cli/cli/v2/pkg/option"
ghConfig "github.com/cli/go-gh/v2/pkg/config"
)
func NewBlankConfig() *ghmock.ConfigMock {
return NewFromString(defaultConfigStr)
}
func NewFromString(cfgStr string) *ghmock.ConfigMock {
c := ghConfig.ReadFromString(cfgStr)
cfg := cfg{c}
mock := &ghmock.ConfigMock{}
mock.GetOrDefaultFunc = func(host, key string) o.Option[gh.ConfigEntry] {
return cfg.GetOrDefault(host, key)
}
mock.SetFunc = func(host, key, value string) {
cfg.Set(host, key, value)
}
mock.WriteFunc = func() error {
return cfg.Write()
}
mock.MigrateFunc = func(m gh.Migration) error {
return cfg.Migrate(m)
}
mock.AliasesFunc = func() gh.AliasConfig {
return &AliasConfig{cfg: c}
}
mock.AuthenticationFunc = func() gh.AuthConfig {
return &AuthConfig{
cfg: c,
defaultHostOverride: func() (string, string) {
return "github.com", "default"
},
hostsOverride: func() []string {
keys, _ := c.Keys([]string{hostsKey})
return keys
},
tokenOverride: func(hostname string) (string, string) {
token, _ := c.Get([]string{hostsKey, hostname, oauthTokenKey})
return token, oauthTokenKey
},
}
}
mock.AccessibleColorsFunc = func(hostname string) gh.ConfigEntry {
return cfg.AccessibleColors(hostname)
}
mock.AccessiblePrompterFunc = func(hostname string) gh.ConfigEntry {
return cfg.AccessiblePrompter(hostname)
}
mock.BrowserFunc = func(hostname string) gh.ConfigEntry {
return cfg.Browser(hostname)
}
mock.ColorLabelsFunc = func(hostname string) gh.ConfigEntry {
return cfg.ColorLabels(hostname)
}
mock.EditorFunc = func(hostname string) gh.ConfigEntry {
return cfg.Editor(hostname)
}
mock.GitProtocolFunc = func(hostname string) gh.ConfigEntry {
return cfg.GitProtocol(hostname)
}
mock.HTTPUnixSocketFunc = func(hostname string) gh.ConfigEntry {
return cfg.HTTPUnixSocket(hostname)
}
mock.PagerFunc = func(hostname string) gh.ConfigEntry {
return cfg.Pager(hostname)
}
mock.PromptFunc = func(hostname string) gh.ConfigEntry {
return cfg.Prompt(hostname)
}
mock.PreferEditorPromptFunc = func(hostname string) gh.ConfigEntry {
return cfg.PreferEditorPrompt(hostname)
}
mock.SpinnerFunc = func(hostname string) gh.ConfigEntry {
return cfg.Spinner(hostname)
}
mock.VersionFunc = func() o.Option[string] {
return cfg.Version()
}
mock.CacheDirFunc = func() string {
return cfg.CacheDir()
}
return mock
}
// NewIsolatedTestConfig sets up a Mock keyring, creates a blank config
// overwrites the ghConfig.Read function that returns a singleton config
// in the real implementation, sets the GH_CONFIG_DIR env var so that
// any call to Write goes to a different location on disk, and then returns
// the blank config and a function that reads any data written to disk.
func NewIsolatedTestConfig(t *testing.T) (*cfg, func(io.Writer, io.Writer)) {
keyring.MockInit()
c := ghConfig.ReadFromString("")
cfg := cfg{c}
// The real implementation of config.Read uses a sync.Once
// to read config files and initialise package level variables
// that are used from then on.
//
// This means that tests can't be isolated from each other, so
// we swap out the function here to return a new config each time.
ghConfig.Read = func(_ *ghConfig.Config) (*ghConfig.Config, error) {
return c, nil
}
// The config.Write method isn't defined in the same way as Read to allow
// the function to be swapped out and it does try to write to disk.
//
// We should consider whether it makes sense to change that but in the meantime
// we can use GH_CONFIG_DIR env var to ensure the tests remain isolated.
readConfigs := StubWriteConfig(t)
return &cfg, readConfigs
}
// StubWriteConfig stubs out the filesystem where config file are written.
// It then returns a function that will read in the config files into io.Writers.
// It automatically cleans up environment variables and written files.
func StubWriteConfig(t *testing.T) func(io.Writer, io.Writer) {
t.Helper()
tempDir := t.TempDir()
t.Setenv("GH_CONFIG_DIR", tempDir)
return func(wc io.Writer, wh io.Writer) {
config, err := os.Open(filepath.Join(tempDir, "config.yml"))
if err != nil {
return
}
defer config.Close()
configData, err := io.ReadAll(config)
if err != nil {
return
}
_, err = wc.Write(configData)
if err != nil {
return
}
hosts, err := os.Open(filepath.Join(tempDir, "hosts.yml"))
if err != nil {
return
}
defer hosts.Close()
hostsData, err := io.ReadAll(hosts)
if err != nil {
return
}
_, err = wh.Write(hostsData)
if err != nil {
return
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/config/migrate_test.go | internal/config/migrate_test.go | package config
import (
"bytes"
"errors"
"io"
"os"
"path/filepath"
"testing"
ghmock "github.com/cli/cli/v2/internal/gh/mock"
ghConfig "github.com/cli/go-gh/v2/pkg/config"
"github.com/stretchr/testify/require"
)
func TestMigrationAppliedSuccessfully(t *testing.T) {
readConfig := StubWriteConfig(t)
// Given we have a migrator that writes some keys to the top level config
// and hosts key
c := ghConfig.ReadFromString(testFullConfig())
topLevelKey := []string{"toplevelkey"}
newHostKey := []string{hostsKey, "newhost"}
migration := mockMigration(func(config *ghConfig.Config) error {
config.Set(topLevelKey, "toplevelvalue")
config.Set(newHostKey, "newhostvalue")
return nil
})
// When we run the migration
conf := cfg{c}
require.NoError(t, conf.Migrate(migration))
// Then our original config is updated with the migration applied
requireKeyWithValue(t, c, topLevelKey, "toplevelvalue")
requireKeyWithValue(t, c, newHostKey, "newhostvalue")
// And our config / hosts changes are persisted to their relevant files
// Note that this is real janky. We have writers that represent the
// top level config and the hosts key but we don't merge them back together
// so when we look into the hosts data, we don't nest the key we're
// looking for under the hosts key ¯\_(ツ)_/¯
var configBuf bytes.Buffer
var hostsBuf bytes.Buffer
readConfig(&configBuf, &hostsBuf)
persistedCfg := ghConfig.ReadFromString(configBuf.String())
persistedHosts := ghConfig.ReadFromString(hostsBuf.String())
requireKeyWithValue(t, persistedCfg, topLevelKey, "toplevelvalue")
requireKeyWithValue(t, persistedHosts, []string{"newhost"}, "newhostvalue")
}
func TestMigrationAppliedBumpsVersion(t *testing.T) {
readConfig := StubWriteConfig(t)
// Given we have a migration with a pre version that matches
// the version in the config
c := ghConfig.ReadFromString(testFullConfig())
c.Set([]string{versionKey}, "expected-pre-version")
topLevelKey := []string{"toplevelkey"}
migration := &ghmock.MigrationMock{
DoFunc: func(config *ghConfig.Config) error {
config.Set(topLevelKey, "toplevelvalue")
return nil
},
PreVersionFunc: func() string {
return "expected-pre-version"
},
PostVersionFunc: func() string {
return "expected-post-version"
},
}
// When we migrate
conf := cfg{c}
require.NoError(t, conf.Migrate(migration))
// Then our original config is updated with the migration applied
requireKeyWithValue(t, c, topLevelKey, "toplevelvalue")
requireKeyWithValue(t, c, []string{versionKey}, "expected-post-version")
// And our config / hosts changes are persisted to their relevant files
var configBuf bytes.Buffer
readConfig(&configBuf, io.Discard)
persistedCfg := ghConfig.ReadFromString(configBuf.String())
requireKeyWithValue(t, persistedCfg, topLevelKey, "toplevelvalue")
requireKeyWithValue(t, persistedCfg, []string{versionKey}, "expected-post-version")
}
func TestMigrationIsNoopWhenAlreadyApplied(t *testing.T) {
// Given we have a migration with a post version that matches
// the version in the config
c := ghConfig.ReadFromString(testFullConfig())
c.Set([]string{versionKey}, "expected-post-version")
migration := &ghmock.MigrationMock{
DoFunc: func(config *ghConfig.Config) error {
return errors.New("is not called")
},
PreVersionFunc: func() string {
return "is not called"
},
PostVersionFunc: func() string {
return "expected-post-version"
},
}
// When we run Migrate
conf := cfg{c}
err := conf.Migrate(migration)
// Then there is nothing done and the config is not modified
require.NoError(t, err)
requireKeyWithValue(t, c, []string{versionKey}, "expected-post-version")
}
func TestMigrationErrorsWhenPreVersionMismatch(t *testing.T) {
StubWriteConfig(t)
// Given we have a migration with a pre version that does not match
// the version in the config
c := ghConfig.ReadFromString(testFullConfig())
c.Set([]string{versionKey}, "not-expected-pre-version")
topLevelKey := []string{"toplevelkey"}
migration := &ghmock.MigrationMock{
DoFunc: func(config *ghConfig.Config) error {
config.Set(topLevelKey, "toplevelvalue")
return nil
},
PreVersionFunc: func() string {
return "expected-pre-version"
},
PostVersionFunc: func() string {
return "not-expected"
},
}
// When we run Migrate
conf := cfg{c}
err := conf.Migrate(migration)
// Then there is an error the migration is not applied and the version is not modified
require.ErrorContains(t, err, `failed to migrate as "expected-pre-version" pre migration version did not match config version "not-expected-pre-version"`)
requireNoKey(t, c, topLevelKey)
requireKeyWithValue(t, c, []string{versionKey}, "not-expected-pre-version")
}
func TestMigrationErrorWritesNoFiles(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("GH_CONFIG_DIR", tempDir)
// Given we have a migrator that errors
c := ghConfig.ReadFromString(testFullConfig())
migration := mockMigration(func(config *ghConfig.Config) error {
return errors.New("failed to migrate in test")
})
// When we run the migration
conf := cfg{c}
err := conf.Migrate(migration)
// Then the error is wrapped and bubbled
require.EqualError(t, err, "failed to migrate config: failed to migrate in test")
// And no files are written to disk
files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 0)
}
func TestMigrationWriteErrors(t *testing.T) {
tests := []struct {
name string
unwriteableFile string
wantErrContains string
}{
{
name: "failure to write hosts",
unwriteableFile: "hosts.yml",
wantErrContains: "failed to write config after migration",
},
{
name: "failure to write config",
unwriteableFile: "config.yml",
wantErrContains: "failed to write config after migration",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("GH_CONFIG_DIR", tempDir)
// Given we error when writing the files (because we chmod the files as trickery)
makeFileUnwriteable(t, filepath.Join(tempDir, tt.unwriteableFile))
c := ghConfig.ReadFromString(testFullConfig())
topLevelKey := []string{"toplevelkey"}
hostsKey := []string{hostsKey, "newhost"}
migration := mockMigration(func(someCfg *ghConfig.Config) error {
someCfg.Set(topLevelKey, "toplevelvalue")
someCfg.Set(hostsKey, "newhostvalue")
return nil
})
// When we run the migration
conf := cfg{c}
err := conf.Migrate(migration)
// Then the error is wrapped and bubbled
require.ErrorContains(t, err, tt.wantErrContains)
})
}
}
func makeFileUnwriteable(t *testing.T, file string) {
t.Helper()
f, err := os.Create(file)
require.NoError(t, err)
f.Close()
require.NoError(t, os.Chmod(file, 0000))
}
func mockMigration(doFunc func(config *ghConfig.Config) error) *ghmock.MigrationMock {
return &ghmock.MigrationMock{
DoFunc: doFunc,
PreVersionFunc: func() string {
return ""
},
PostVersionFunc: func() string {
return "not-expected"
},
}
}
func testFullConfig() string {
var data = `
git_protocol: ssh
editor:
prompt: enabled
pager: less
hosts:
github.com:
user: user1
oauth_token: xxxxxxxxxxxxxxxxxxxx
git_protocol: ssh
enterprise.com:
user: user2
oauth_token: yyyyyyyyyyyyyyyyyyyy
git_protocol: https
`
return data
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/config/config.go | internal/config/config.go | package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/keyring"
o "github.com/cli/cli/v2/pkg/option"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
ghConfig "github.com/cli/go-gh/v2/pkg/config"
)
// Important: some of the following configuration settings are used outside of `cli/cli`,
// they are defined here to avoid `cli/cli` being changed unexpectedly.
const (
accessibleColorsKey = "accessible_colors" // used by cli/go-gh to enable the use of customizable, accessible 4-bit colors.
accessiblePrompterKey = "accessible_prompter"
aliasesKey = "aliases"
browserKey = "browser" // used by cli/go-gh to open URLs in web browsers
colorLabelsKey = "color_labels"
editorKey = "editor" // used by cli/go-gh to open interactive text editor
gitProtocolKey = "git_protocol"
hostsKey = "hosts" // used by cli/go-gh to locate authenticated host tokens
httpUnixSocketKey = "http_unix_socket"
oauthTokenKey = "oauth_token" // used by cli/go-gh to locate authenticated host tokens
pagerKey = "pager"
promptKey = "prompt"
preferEditorPromptKey = "prefer_editor_prompt"
spinnerKey = "spinner"
userKey = "user"
usersKey = "users"
versionKey = "version"
)
func NewConfig() (gh.Config, error) {
c, err := ghConfig.Read(fallbackConfig())
if err != nil {
return nil, err
}
return &cfg{c}, nil
}
// Implements Config interface
type cfg struct {
cfg *ghConfig.Config
}
func (c *cfg) get(hostname, key string) o.Option[string] {
if hostname != "" {
val, err := c.cfg.Get([]string{hostsKey, hostname, key})
if err == nil {
return o.Some(val)
}
}
val, err := c.cfg.Get([]string{key})
if err == nil {
return o.Some(val)
}
return o.None[string]()
}
func (c *cfg) GetOrDefault(hostname, key string) o.Option[gh.ConfigEntry] {
if val := c.get(hostname, key); val.IsSome() {
// Map the Option[string] to Option[gh.ConfigEntry] with a source of ConfigUserProvided
return o.Map(val, toConfigEntry(gh.ConfigUserProvided))
}
if defaultVal := defaultFor(key); defaultVal.IsSome() {
// Map the Option[string] to Option[gh.ConfigEntry] with a source of ConfigDefaultProvided
return o.Map(defaultVal, toConfigEntry(gh.ConfigDefaultProvided))
}
return o.None[gh.ConfigEntry]()
}
// toConfigEntry is a helper function to convert a string value to a ConfigEntry with a given source.
//
// It's a bit of FP style but it allows us to map an Option[string] to Option[gh.ConfigEntry] without
// unwrapping the it and rewrapping it.
func toConfigEntry(source gh.ConfigSource) func(val string) gh.ConfigEntry {
return func(val string) gh.ConfigEntry {
return gh.ConfigEntry{Value: val, Source: source}
}
}
func (c *cfg) Set(hostname, key, value string) {
if hostname == "" {
c.cfg.Set([]string{key}, value)
return
}
c.cfg.Set([]string{hostsKey, hostname, key}, value)
if user, _ := c.cfg.Get([]string{hostsKey, hostname, userKey}); user != "" {
c.cfg.Set([]string{hostsKey, hostname, usersKey, user, key}, value)
}
}
func (c *cfg) Write() error {
return ghConfig.Write(c.cfg)
}
func (c *cfg) Aliases() gh.AliasConfig {
return &AliasConfig{cfg: c.cfg}
}
func (c *cfg) Authentication() gh.AuthConfig {
return &AuthConfig{cfg: c.cfg}
}
func (c *cfg) AccessibleColors(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, accessibleColorsKey).Unwrap()
}
func (c *cfg) AccessiblePrompter(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, accessiblePrompterKey).Unwrap()
}
func (c *cfg) Browser(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, browserKey).Unwrap()
}
func (c *cfg) ColorLabels(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, colorLabelsKey).Unwrap()
}
func (c *cfg) Editor(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, editorKey).Unwrap()
}
func (c *cfg) GitProtocol(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, gitProtocolKey).Unwrap()
}
func (c *cfg) HTTPUnixSocket(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, httpUnixSocketKey).Unwrap()
}
func (c *cfg) Pager(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, pagerKey).Unwrap()
}
func (c *cfg) Prompt(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, promptKey).Unwrap()
}
func (c *cfg) PreferEditorPrompt(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, preferEditorPromptKey).Unwrap()
}
func (c *cfg) Spinner(hostname string) gh.ConfigEntry {
// Intentionally panic if there is no user provided value or default value (which would be a programmer error)
return c.GetOrDefault(hostname, spinnerKey).Unwrap()
}
func (c *cfg) Version() o.Option[string] {
return c.get("", versionKey)
}
func (c *cfg) Migrate(m gh.Migration) error {
// If there is no version entry we must never have applied a migration, and the following conditional logic
// handles the version as an empty string correctly.
version := c.Version().UnwrapOrZero()
// If migration has already occurred then do not attempt to migrate again.
if m.PostVersion() == version {
return nil
}
// If migration is incompatible with current version then return an error.
if m.PreVersion() != version {
return fmt.Errorf("failed to migrate as %q pre migration version did not match config version %q", m.PreVersion(), version)
}
if err := m.Do(c.cfg); err != nil {
return fmt.Errorf("failed to migrate config: %s", err)
}
c.Set("", versionKey, m.PostVersion())
// Then write out our migrated config.
if err := c.Write(); err != nil {
return fmt.Errorf("failed to write config after migration: %s", err)
}
return nil
}
func (c *cfg) CacheDir() string {
return ghConfig.CacheDir()
}
func defaultFor(key string) o.Option[string] {
for _, co := range Options {
if co.Key == key {
return o.Some(co.DefaultValue)
}
}
return o.None[string]()
}
// AuthConfig is used for interacting with some persistent configuration for gh,
// with knowledge on how to access encrypted storage when neccesarry.
// Behavior is scoped to authentication specific tasks.
type AuthConfig struct {
cfg *ghConfig.Config
defaultHostOverride func() (string, string)
hostsOverride func() []string
tokenOverride func(string) (string, string)
}
// ActiveToken will retrieve the active auth token for the given hostname,
// searching environment variables, plain text config, and
// lastly encrypted storage.
func (c *AuthConfig) ActiveToken(hostname string) (string, string) {
if c.tokenOverride != nil {
return c.tokenOverride(hostname)
}
token, source := ghauth.TokenFromEnvOrConfig(hostname)
if token == "" {
var user string
var err error
if user, err = c.ActiveUser(hostname); err == nil {
token, err = c.TokenFromKeyringForUser(hostname, user)
}
if err != nil {
// We should generally be able to find a token for the active user,
// but in some cases such as if the keyring was set up in a very old
// version of the CLI, it may only have a unkeyed token, so fallback
// to it.
token, err = c.TokenFromKeyring(hostname)
}
if err == nil {
source = "keyring"
}
}
return token, source
}
// HasActiveToken returns true when a token for the hostname is present.
func (c *AuthConfig) HasActiveToken(hostname string) bool {
token, _ := c.ActiveToken(hostname)
return token != ""
}
// HasEnvToken returns true when a token has been specified in an
// environment variable, else returns false.
func (c *AuthConfig) HasEnvToken() bool {
// This will check if there are any environment variable
// authentication tokens set for enterprise hosts.
// Any non-github.com hostname is fine here
hostname := "example.com"
if c.tokenOverride != nil {
token, _ := c.tokenOverride(hostname)
if token != "" {
return true
}
}
// TODO: This is _extremely_ knowledgeable about the implementation of TokenFromEnvOrConfig
// It has to use a hostname that is not going to be found in the hosts so that it
// can guarantee that tokens will only be returned from a set env var.
// Discussed here, but maybe worth revisiting: https://github.com/cli/cli/pull/7169#discussion_r1136979033
token, _ := ghauth.TokenFromEnvOrConfig(hostname)
return token != ""
}
// SetActiveToken will override any token resolution and return the given
// token and source for all calls to ActiveToken. Use for testing purposes only.
func (c *AuthConfig) SetActiveToken(token, source string) {
c.tokenOverride = func(_ string) (string, string) {
return token, source
}
}
// TokenFromKeyring will retrieve the auth token for the given hostname,
// only searching in encrypted storage.
func (c *AuthConfig) TokenFromKeyring(hostname string) (string, error) {
return keyring.Get(keyringServiceName(hostname), "")
}
// TokenFromKeyringForUser will retrieve the auth token for the given hostname
// and username, only searching in encrypted storage.
//
// An empty username will return an error because the potential to return
// the currently active token under surprising cases is just too high to risk
// compared to the utility of having the function being smart.
func (c *AuthConfig) TokenFromKeyringForUser(hostname, username string) (string, error) {
if username == "" {
return "", errors.New("username cannot be blank")
}
return keyring.Get(keyringServiceName(hostname), username)
}
// ActiveUser will retrieve the username for the active user at the given hostname.
// This will not be accurate if the oauth token is set from an environment variable.
func (c *AuthConfig) ActiveUser(hostname string) (string, error) {
return c.cfg.Get([]string{hostsKey, hostname, userKey})
}
func (c *AuthConfig) Hosts() []string {
if c.hostsOverride != nil {
return c.hostsOverride()
}
return ghauth.KnownHosts()
}
// SetHosts will override any hosts resolution and return the given
// hosts for all calls to Hosts. Use for testing purposes only.
func (c *AuthConfig) SetHosts(hosts []string) {
c.hostsOverride = func() []string {
return hosts
}
}
func (c *AuthConfig) DefaultHost() (string, string) {
if c.defaultHostOverride != nil {
return c.defaultHostOverride()
}
return ghauth.DefaultHost()
}
// SetDefaultHost will override any host resolution and return the given
// host and source for all calls to DefaultHost. Use for testing purposes only.
func (c *AuthConfig) SetDefaultHost(host, source string) {
c.defaultHostOverride = func() (string, string) {
return host, source
}
}
// Login will set user, git protocol, and auth token for the given hostname.
// If the encrypt option is specified it will first try to store the auth token
// in encrypted storage and will fall back to the plain text config file.
func (c *AuthConfig) Login(hostname, username, token, gitProtocol string, secureStorage bool) (bool, error) {
// In this section we set up the users config
var setErr error
if secureStorage {
// Try to set the token for this user in the encrypted storage for later switching
setErr = keyring.Set(keyringServiceName(hostname), username, token)
if setErr == nil {
// Clean up the previous oauth_token from the config file, if there were one
_ = c.cfg.Remove([]string{hostsKey, hostname, usersKey, username, oauthTokenKey})
}
}
insecureStorageUsed := false
if !secureStorage || setErr != nil {
// And set the oauth token under the user for later switching
c.cfg.Set([]string{hostsKey, hostname, usersKey, username, oauthTokenKey}, token)
insecureStorageUsed = true
}
if gitProtocol != "" {
// Set the host level git protocol
// Although it might be expected that this is handled by switch, git protocol
// is currently a host level config and not a user level config, so any change
// will overwrite the protocol for all users on the host.
c.cfg.Set([]string{hostsKey, hostname, gitProtocolKey}, gitProtocol)
}
// Create the username key with an empty value so it will be
// written even when there are no keys set under it.
if _, getErr := c.cfg.Get([]string{hostsKey, hostname, usersKey, username}); getErr != nil {
c.cfg.Set([]string{hostsKey, hostname, usersKey, username}, "")
}
// Then we activate the new user
return insecureStorageUsed, c.activateUser(hostname, username)
}
func (c *AuthConfig) SwitchUser(hostname, user string) error {
previouslyActiveUser, err := c.ActiveUser(hostname)
if err != nil {
return fmt.Errorf("failed to get active user: %s", err)
}
previouslyActiveToken, previousSource := c.ActiveToken(hostname)
if previousSource != "keyring" && previousSource != "oauth_token" {
return fmt.Errorf("currently active token for %s is from %s", hostname, previousSource)
}
err = c.activateUser(hostname, user)
if err != nil {
// Given that activateUser can only fail before the config is written, or when writing the config
// we know for sure that the config has not been written. However, we still should restore it back
// to its previous clean state just in case something else tries to make use of the config, or tries
// to write it again.
if previousSource == "keyring" {
if setErr := keyring.Set(keyringServiceName(hostname), "", previouslyActiveToken); setErr != nil {
err = errors.Join(err, setErr)
}
}
if previousSource == "oauth_token" {
c.cfg.Set([]string{hostsKey, hostname, oauthTokenKey}, previouslyActiveToken)
}
c.cfg.Set([]string{hostsKey, hostname, userKey}, previouslyActiveUser)
return err
}
return nil
}
// Logout will remove user, git protocol, and auth token for the given hostname.
// It will remove the auth token from the encrypted storage if it exists there.
func (c *AuthConfig) Logout(hostname, username string) error {
users := c.UsersForHost(hostname)
// If there is only one (or zero) users, then we remove the host
// and unset the keyring tokens.
if len(users) < 2 {
_ = c.cfg.Remove([]string{hostsKey, hostname})
_ = keyring.Delete(keyringServiceName(hostname), "")
_ = keyring.Delete(keyringServiceName(hostname), username)
return ghConfig.Write(c.cfg)
}
// Otherwise, we remove the user from this host
_ = c.cfg.Remove([]string{hostsKey, hostname, usersKey, username})
// This error is ignorable because we already know there is an active user for the host
activeUser, _ := c.ActiveUser(hostname)
// If the user we're removing isn't active, then we just write the config
if activeUser != username {
return ghConfig.Write(c.cfg)
}
// Otherwise we get the first user in the slice that isn't the user we're removing
switchUserIdx := slices.IndexFunc(users, func(n string) bool {
return n != username
})
// And activate them
return c.activateUser(hostname, users[switchUserIdx])
}
func (c *AuthConfig) activateUser(hostname, user string) error {
// We first need to idempotently clear out any set tokens for the host
_ = keyring.Delete(keyringServiceName(hostname), "")
_ = c.cfg.Remove([]string{hostsKey, hostname, oauthTokenKey})
// Then we'll move the keyring token or insecure token as necessary, only one of the
// following branches should be true.
// If there is a token in the secure keyring for the user, move it to the active slot
var tokenSwitched bool
if token, err := keyring.Get(keyringServiceName(hostname), user); err == nil {
if err = keyring.Set(keyringServiceName(hostname), "", token); err != nil {
return fmt.Errorf("failed to move active token in keyring: %v", err)
}
tokenSwitched = true
}
// If there is a token in the insecure config for the user, move it to the active field
if token, err := c.cfg.Get([]string{hostsKey, hostname, usersKey, user, oauthTokenKey}); err == nil {
c.cfg.Set([]string{hostsKey, hostname, oauthTokenKey}, token)
tokenSwitched = true
}
if !tokenSwitched {
return fmt.Errorf("no token found for %s", user)
}
// Then we'll update the active user for the host
c.cfg.Set([]string{hostsKey, hostname, userKey}, user)
return ghConfig.Write(c.cfg)
}
func (c *AuthConfig) UsersForHost(hostname string) []string {
users, err := c.cfg.Keys([]string{hostsKey, hostname, usersKey})
if err != nil {
return nil
}
return users
}
func (c *AuthConfig) TokenForUser(hostname, user string) (string, string, error) {
if token, err := keyring.Get(keyringServiceName(hostname), user); err == nil {
return token, "keyring", nil
}
if token, err := c.cfg.Get([]string{hostsKey, hostname, usersKey, user, oauthTokenKey}); err == nil {
return token, "oauth_token", nil
}
return "", "default", fmt.Errorf("no token found for '%s'", user)
}
func keyringServiceName(hostname string) string {
return "gh:" + hostname
}
type AliasConfig struct {
cfg *ghConfig.Config
}
func (a *AliasConfig) Get(alias string) (string, error) {
return a.cfg.Get([]string{aliasesKey, alias})
}
func (a *AliasConfig) Add(alias, expansion string) {
a.cfg.Set([]string{aliasesKey, alias}, expansion)
}
func (a *AliasConfig) Delete(alias string) error {
return a.cfg.Remove([]string{aliasesKey, alias})
}
func (a *AliasConfig) All() map[string]string {
out := map[string]string{}
keys, err := a.cfg.Keys([]string{aliasesKey})
if err != nil {
return out
}
for _, key := range keys {
val, _ := a.cfg.Get([]string{aliasesKey, key})
out[key] = val
}
return out
}
func fallbackConfig() *ghConfig.Config {
return ghConfig.ReadFromString(defaultConfigStr)
}
// The schema version in here should match the PostVersion of whatever the
// last migration we decided to run is. Therefore, if we run a new migration,
// this should be bumped.
const defaultConfigStr = `
# The default config file, auto-generated by gh. Run 'gh environment' to learn more about
# environment variables respected by gh and their precedence.
# The current version of the config schema
version: 1
# What protocol to use when performing git operations. Supported values: ssh, https
git_protocol: https
# What editor gh should run when creating issues, pull requests, etc. If blank, will refer to environment.
editor:
# When to interactively prompt. This is a global config that cannot be overridden by hostname. Supported values: enabled, disabled
prompt: enabled
# Preference for editor-based interactive prompting. This is a global config that cannot be overridden by hostname. Supported values: enabled, disabled
prefer_editor_prompt: disabled
# A pager program to send command output to, e.g. "less". If blank, will refer to environment. Set the value to "cat" to disable the pager.
pager:
# Aliases allow you to create nicknames for gh commands
aliases:
co: pr checkout
# The path to a unix socket through which to send HTTP connections. If blank, HTTP traffic will be handled by net/http.DefaultTransport.
http_unix_socket:
# What web browser gh should use when opening URLs. If blank, will refer to environment.
browser:
# Whether to display labels using their RGB hex color codes in terminals that support truecolor. Supported values: enabled, disabled
color_labels: disabled
# Whether customizable, 4-bit accessible colors should be used. Supported values: enabled, disabled
accessible_colors: disabled
# Whether an accessible prompter should be used. Supported values: enabled, disabled
accessible_prompter: disabled
# Whether to use a animated spinner as a progress indicator. If disabled, a textual progress indicator is used instead. Supported values: enabled, disabled
spinner: enabled
`
type ConfigOption struct {
Key string
Description string
DefaultValue string
AllowedValues []string
CurrentValue func(c gh.Config, hostname string) string
}
var Options = []ConfigOption{
{
Key: gitProtocolKey,
Description: "the protocol to use for git clone and push operations",
DefaultValue: "https",
AllowedValues: []string{"https", "ssh"},
CurrentValue: func(c gh.Config, hostname string) string {
return c.GitProtocol(hostname).Value
},
},
{
Key: editorKey,
Description: "the text editor program to use for authoring text",
DefaultValue: "",
CurrentValue: func(c gh.Config, hostname string) string {
return c.Editor(hostname).Value
},
},
{
Key: promptKey,
Description: "toggle interactive prompting in the terminal",
DefaultValue: "enabled",
AllowedValues: []string{"enabled", "disabled"},
CurrentValue: func(c gh.Config, hostname string) string {
return c.Prompt(hostname).Value
},
},
{
Key: preferEditorPromptKey,
Description: "toggle preference for editor-based interactive prompting in the terminal",
DefaultValue: "disabled",
AllowedValues: []string{"enabled", "disabled"},
CurrentValue: func(c gh.Config, hostname string) string {
return c.PreferEditorPrompt(hostname).Value
},
},
{
Key: pagerKey,
Description: "the terminal pager program to send standard output to",
DefaultValue: "",
CurrentValue: func(c gh.Config, hostname string) string {
return c.Pager(hostname).Value
},
},
{
Key: httpUnixSocketKey,
Description: "the path to a Unix socket through which to make an HTTP connection",
DefaultValue: "",
CurrentValue: func(c gh.Config, hostname string) string {
return c.HTTPUnixSocket(hostname).Value
},
},
{
Key: browserKey,
Description: "the web browser to use for opening URLs",
DefaultValue: "",
CurrentValue: func(c gh.Config, hostname string) string {
return c.Browser(hostname).Value
},
},
{
Key: colorLabelsKey,
Description: "whether to display labels using their RGB hex color codes in terminals that support truecolor",
DefaultValue: "disabled",
AllowedValues: []string{"enabled", "disabled"},
CurrentValue: func(c gh.Config, hostname string) string {
return c.ColorLabels(hostname).Value
},
},
{
Key: accessibleColorsKey,
Description: "whether customizable, 4-bit accessible colors should be used",
DefaultValue: "disabled",
AllowedValues: []string{"enabled", "disabled"},
CurrentValue: func(c gh.Config, hostname string) string {
return c.AccessibleColors(hostname).Value
},
},
{
Key: accessiblePrompterKey,
Description: "whether an accessible prompter should be used",
DefaultValue: "disabled",
AllowedValues: []string{"enabled", "disabled"},
CurrentValue: func(c gh.Config, hostname string) string {
return c.AccessiblePrompter(hostname).Value
},
},
{
Key: spinnerKey,
Description: "whether to use a animated spinner as a progress indicator",
DefaultValue: "enabled",
AllowedValues: []string{"enabled", "disabled"},
CurrentValue: func(c gh.Config, hostname string) string {
return c.Spinner(hostname).Value
},
},
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
newPath := filepath.Join(homeDir, subdir)
return newPath, nil
}
func StateDir() string {
return ghConfig.StateDir()
}
func DataDir() string {
return ghConfig.DataDir()
}
func ConfigDir() string {
return ghConfig.ConfigDir()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/config/config_test.go | internal/config/config_test.go | package config
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/cli/cli/v2/internal/gh"
ghConfig "github.com/cli/go-gh/v2/pkg/config"
)
func newTestConfig() *cfg {
return &cfg{
cfg: ghConfig.ReadFromString(""),
}
}
func TestNewConfigProvidesFallback(t *testing.T) {
var spiedCfg *ghConfig.Config
ghConfig.Read = func(fallback *ghConfig.Config) (*ghConfig.Config, error) {
spiedCfg = fallback
return fallback, nil
}
_, err := NewConfig()
require.NoError(t, err)
requireKeyWithValue(t, spiedCfg, []string{versionKey}, "1")
requireKeyWithValue(t, spiedCfg, []string{gitProtocolKey}, "https")
requireKeyWithValue(t, spiedCfg, []string{editorKey}, "")
requireKeyWithValue(t, spiedCfg, []string{promptKey}, "enabled")
requireKeyWithValue(t, spiedCfg, []string{pagerKey}, "")
requireKeyWithValue(t, spiedCfg, []string{aliasesKey, "co"}, "pr checkout")
requireKeyWithValue(t, spiedCfg, []string{httpUnixSocketKey}, "")
requireKeyWithValue(t, spiedCfg, []string{browserKey}, "")
requireKeyWithValue(t, spiedCfg, []string{colorLabelsKey}, "disabled")
}
func TestGetOrDefaultApplicationDefaults(t *testing.T) {
tests := []struct {
key string
expectedDefault string
}{
{gitProtocolKey, "https"},
{editorKey, ""},
{promptKey, "enabled"},
{pagerKey, ""},
{httpUnixSocketKey, ""},
{browserKey, ""},
}
for _, tt := range tests {
t.Run(tt.key, func(t *testing.T) {
// Given we have no top level configuration
cfg := newTestConfig()
// When we get a key that has no value, but has a default
optionalEntry := cfg.GetOrDefault("", tt.key)
// Then there is an entry with the default value, and source set as default
entry := optionalEntry.Expect(fmt.Sprintf("expected there to be a value for %s", tt.key))
require.Equal(t, tt.expectedDefault, entry.Value)
require.Equal(t, gh.ConfigDefaultProvided, entry.Source)
})
}
}
func TestGetOrDefaultNonExistentKey(t *testing.T) {
// Given we have no top level configuration
cfg := newTestConfig()
// When we get a key that has no value
optionalEntry := cfg.GetOrDefault("", "non-existent-key")
// Then it returns a None variant
require.True(t, optionalEntry.IsNone(), "expected there to be no value")
}
func TestGetOrDefaultNonExistentHostSpecificKey(t *testing.T) {
// Given have no top level configuration
cfg := newTestConfig()
// When we get a key for a host that has no value
optionalEntry := cfg.GetOrDefault("non-existent-host", "non-existent-key")
// Then it returns a None variant
require.True(t, optionalEntry.IsNone(), "expected there to be no value")
}
func TestGetOrDefaultExistingTopLevelKey(t *testing.T) {
// Given have a top level config entry
cfg := newTestConfig()
cfg.Set("", "top-level-key", "top-level-value")
// When we get that key
optionalEntry := cfg.GetOrDefault("non-existent-host", "top-level-key")
// Then it returns a Some variant containing the correct value and a source of user
entry := optionalEntry.Expect("expected there to be a value")
require.Equal(t, "top-level-value", entry.Value)
require.Equal(t, gh.ConfigUserProvided, entry.Source)
}
func TestGetOrDefaultExistingHostSpecificKey(t *testing.T) {
// Given have a host specific config entry
cfg := newTestConfig()
cfg.Set("github.com", "host-specific-key", "host-specific-value")
// When we get that key
optionalEntry := cfg.GetOrDefault("github.com", "host-specific-key")
// Then it returns a Some variant containing the correct value and a source of user
entry := optionalEntry.Expect("expected there to be a value")
require.Equal(t, "host-specific-value", entry.Value)
require.Equal(t, gh.ConfigUserProvided, entry.Source)
}
func TestGetOrDefaultHostnameSpecificKeyFallsBackToTopLevel(t *testing.T) {
// Given have a top level config entry
cfg := newTestConfig()
cfg.Set("", "key", "value")
// When we get that key on a specific host
optionalEntry := cfg.GetOrDefault("github.com", "key")
// Then it returns a Some variant containing the correct value by falling back
// to the top level config, with a source of user
entry := optionalEntry.Expect("expected there to be a value")
require.Equal(t, "value", entry.Value)
require.Equal(t, gh.ConfigUserProvided, entry.Source)
}
func TestFallbackConfig(t *testing.T) {
cfg := fallbackConfig()
requireKeyWithValue(t, cfg, []string{gitProtocolKey}, "https")
requireKeyWithValue(t, cfg, []string{editorKey}, "")
requireKeyWithValue(t, cfg, []string{promptKey}, "enabled")
requireKeyWithValue(t, cfg, []string{pagerKey}, "")
requireKeyWithValue(t, cfg, []string{aliasesKey, "co"}, "pr checkout")
requireKeyWithValue(t, cfg, []string{httpUnixSocketKey}, "")
requireKeyWithValue(t, cfg, []string{browserKey}, "")
requireKeyWithValue(t, cfg, []string{colorLabelsKey}, "disabled")
requireNoKey(t, cfg, []string{"unknown"})
}
func TestSetTopLevelKey(t *testing.T) {
c := newTestConfig()
host := ""
key := "top-level-key"
val := "top-level-value"
c.Set(host, key, val)
requireKeyWithValue(t, c.cfg, []string{key}, val)
}
func TestSetHostSpecificKey(t *testing.T) {
c := newTestConfig()
host := "github.com"
key := "host-level-key"
val := "host-level-value"
c.Set(host, key, val)
requireKeyWithValue(t, c.cfg, []string{hostsKey, host, key}, val)
}
func TestSetUserSpecificKey(t *testing.T) {
c := newTestConfig()
host := "github.com"
user := "test-user"
c.cfg.Set([]string{hostsKey, host, userKey}, user)
key := "host-level-key"
val := "host-level-value"
c.Set(host, key, val)
requireKeyWithValue(t, c.cfg, []string{hostsKey, host, key}, val)
requireKeyWithValue(t, c.cfg, []string{hostsKey, host, usersKey, user, key}, val)
}
func TestSetUserSpecificKeyNoUserPresent(t *testing.T) {
c := newTestConfig()
host := "github.com"
key := "host-level-key"
val := "host-level-value"
c.Set(host, key, val)
requireKeyWithValue(t, c.cfg, []string{hostsKey, host, key}, val)
requireNoKey(t, c.cfg, []string{hostsKey, host, usersKey})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/config/auth_config_test.go | internal/config/auth_config_test.go | package config
import (
"errors"
"testing"
"github.com/cli/cli/v2/internal/config/migration"
"github.com/cli/cli/v2/internal/keyring"
ghConfig "github.com/cli/go-gh/v2/pkg/config"
"github.com/stretchr/testify/require"
)
// Note that NewIsolatedTestConfig sets up a Mock keyring as well
func newTestAuthConfig(t *testing.T) *AuthConfig {
cfg, _ := NewIsolatedTestConfig(t)
return &AuthConfig{cfg: cfg.cfg}
}
func TestTokenFromKeyring(t *testing.T) {
// Given a keyring that contains a token for a host
authCfg := newTestAuthConfig(t)
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "", "test-token"))
// When we get the token from the auth config
token, err := authCfg.TokenFromKeyring("github.com")
// Then it returns successfully with the correct token
require.NoError(t, err)
require.Equal(t, "test-token", token)
}
func TestTokenFromKeyringForUser(t *testing.T) {
// Given a keyring that contains a token for a host with a specific user
authCfg := newTestAuthConfig(t)
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "test-user", "test-token"))
// When we get the token from the auth config
token, err := authCfg.TokenFromKeyringForUser("github.com", "test-user")
// Then it returns successfully with the correct token
require.NoError(t, err)
require.Equal(t, "test-token", token)
}
func TestTokenFromKeyringForUserErrorsIfUsernameIsBlank(t *testing.T) {
authCfg := newTestAuthConfig(t)
// When we get the token from the keyring for an empty username
_, err := authCfg.TokenFromKeyringForUser("github.com", "")
// Then it returns an error
require.ErrorContains(t, err, "username cannot be blank")
}
func TestHasActiveToken(t *testing.T) {
// Given the user has logged in for a host
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user", "test-token", "", false)
require.NoError(t, err)
// When we check if that host has an active token
hasActiveToken := authCfg.HasActiveToken("github.com")
// Then there is an active token
require.True(t, hasActiveToken, "expected there to be an active token")
}
func TestHasNoActiveToken(t *testing.T) {
// Given there are no users logged in for a host
authCfg := newTestAuthConfig(t)
// When we check if any host has an active token
hasActiveToken := authCfg.HasActiveToken("github.com")
// Then there is no active token
require.False(t, hasActiveToken, "expected there to be no active token")
}
func TestTokenStoredInConfig(t *testing.T) {
// Given the user has logged in insecurely
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user", "test-token", "", false)
require.NoError(t, err)
// When we get the token
token, source := authCfg.ActiveToken("github.com")
// Then the token is successfully fetched
// and the source is set to oauth_token but this isn't great:
// https://github.com/cli/go-gh/issues/94
require.Equal(t, "test-token", token)
require.Equal(t, oauthTokenKey, source)
}
func TestTokenStoredInEnv(t *testing.T) {
// When the user is authenticated via env var
authCfg := newTestAuthConfig(t)
t.Setenv("GH_TOKEN", "test-token")
// When we get the token
token, source := authCfg.ActiveToken("github.com")
// Then the token is successfully fetched
// and the source is set to the name of the env var
require.Equal(t, "test-token", token)
require.Equal(t, "GH_TOKEN", source)
}
func TestTokenStoredInKeyring(t *testing.T) {
// When the user has logged in securely
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user", "test-token", "", true)
require.NoError(t, err)
// When we get the token
token, source := authCfg.ActiveToken("github.com")
// Then the token is successfully fetched
// and the source is set to keyring
require.Equal(t, "test-token", token)
require.Equal(t, "keyring", source)
}
func TestTokenFromKeyringNonExistent(t *testing.T) {
// Given a keyring that doesn't contain any tokens
authCfg := newTestAuthConfig(t)
// When we try to get a token from the auth config
_, err := authCfg.TokenFromKeyring("github.com")
// Then it returns failure bubbling the ErrNotFound
require.ErrorContains(t, err, "secret not found in keyring")
}
func TestHasEnvTokenWithoutAnyEnvToken(t *testing.T) {
// Given we have no env set
authCfg := newTestAuthConfig(t)
// When we check if it has an env token
hasEnvToken := authCfg.HasEnvToken()
// Then it returns false
require.False(t, hasEnvToken, "expected not to have env token")
}
func TestHasEnvTokenWithEnvToken(t *testing.T) {
// Given we have an env token set
// Note that any valid env var for tokens will do, not just GH_ENTERPRISE_TOKEN
authCfg := newTestAuthConfig(t)
t.Setenv("GH_ENTERPRISE_TOKEN", "test-token")
// When we check if it has an env token
hasEnvToken := authCfg.HasEnvToken()
// Then it returns true
require.True(t, hasEnvToken, "expected to have env token")
}
func TestHasEnvTokenWithNoEnvTokenButAConfigVar(t *testing.T) {
t.Skip("this test is explicitly breaking some implementation assumptions")
// Given a token in the config
authCfg := newTestAuthConfig(t)
// Using example.com here will cause the token to be returned from the config
_, err := authCfg.Login("example.com", "test-user", "test-token", "", false)
require.NoError(t, err)
// When we check if it has an env token
hasEnvToken := authCfg.HasEnvToken()
// Then it SHOULD return false
require.False(t, hasEnvToken, "expected not to have env token")
}
func TestUserNotLoggedIn(t *testing.T) {
// Given we have not logged in
authCfg := newTestAuthConfig(t)
// When we get the user
_, err := authCfg.ActiveUser("github.com")
// Then it returns failure, bubbling the KeyNotFoundError
var keyNotFoundError *ghConfig.KeyNotFoundError
require.ErrorAs(t, err, &keyNotFoundError)
}
func TestHostsIncludesEnvVar(t *testing.T) {
// Given the GH_HOST env var is set
authCfg := newTestAuthConfig(t)
t.Setenv("GH_HOST", "ghe.io")
// When we get the hosts
hosts := authCfg.Hosts()
// Then the host in the env var is included
require.Contains(t, hosts, "ghe.io")
}
func TestDefaultHostFromEnvVar(t *testing.T) {
// Given the GH_HOST env var is set
authCfg := newTestAuthConfig(t)
t.Setenv("GH_HOST", "ghe.io")
// When we get the DefaultHost
defaultHost, source := authCfg.DefaultHost()
// Then the returned host and source are using the env var
require.Equal(t, "ghe.io", defaultHost)
require.Equal(t, "GH_HOST", source)
}
func TestDefaultHostNotLoggedIn(t *testing.T) {
// Given we are not logged in
authCfg := newTestAuthConfig(t)
// When we get the DefaultHost
defaultHost, source := authCfg.DefaultHost()
// Then the returned host is always github.com
require.Equal(t, "github.com", defaultHost)
require.Equal(t, "default", source)
}
func TestDefaultHostLoggedInToOnlyOneHost(t *testing.T) {
// Given we are logged into one host (not github.com to differentiate from the fallback)
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("ghe.io", "test-user", "test-token", "", false)
require.NoError(t, err)
// When we get the DefaultHost
defaultHost, source := authCfg.DefaultHost()
// Then the returned host is that logged in host and the source is the hosts config
require.Equal(t, "ghe.io", defaultHost)
require.Equal(t, hostsKey, source)
}
func TestLoginSecureStorageUsesKeyring(t *testing.T) {
// Given a usable keyring
authCfg := newTestAuthConfig(t)
host := "github.com"
user := "test-user"
token := "test-token"
// When we login with secure storage
insecureStorageUsed, err := authCfg.Login(host, user, token, "", true)
// Then it returns success, notes that insecure storage was not used, and stores the token in the keyring
require.NoError(t, err)
require.False(t, insecureStorageUsed, "expected to use secure storage")
gotToken, err := keyring.Get(keyringServiceName(host), "")
require.NoError(t, err)
require.Equal(t, token, gotToken)
gotToken, err = keyring.Get(keyringServiceName(host), user)
require.NoError(t, err)
require.Equal(t, token, gotToken)
}
func TestLoginSecureStorageRemovesOldInsecureConfigToken(t *testing.T) {
// Given a usable keyring and an oauth token in the config
authCfg := newTestAuthConfig(t)
authCfg.cfg.Set([]string{hostsKey, "github.com", oauthTokenKey}, "old-token")
// When we login with secure storage
_, err := authCfg.Login("github.com", "test-user", "test-token", "", true)
// Then it returns success, having also removed the old token from the config
require.NoError(t, err)
requireNoKey(t, authCfg.cfg, []string{hostsKey, "github.com", oauthTokenKey})
}
func TestLoginSecureStorageWithErrorFallsbackAndReports(t *testing.T) {
// Given a keyring that errors
authCfg := newTestAuthConfig(t)
keyring.MockInitWithError(errors.New("test-explosion"))
// When we login with secure storage
insecureStorageUsed, err := authCfg.Login("github.com", "test-user", "test-token", "", true)
// Then it returns success, reports that insecure storage was used, and stores the token in the config
require.NoError(t, err)
require.True(t, insecureStorageUsed, "expected to use insecure storage")
requireKeyWithValue(t, authCfg.cfg, []string{hostsKey, "github.com", oauthTokenKey}, "test-token")
}
func TestLoginInsecureStorage(t *testing.T) {
// Given we are not logged in
authCfg := newTestAuthConfig(t)
// When we login with insecure storage
insecureStorageUsed, err := authCfg.Login("github.com", "test-user", "test-token", "", false)
// Then it returns success, notes that insecure storage was used, and stores the token in the config
require.NoError(t, err)
require.True(t, insecureStorageUsed, "expected to use insecure storage")
requireKeyWithValue(t, authCfg.cfg, []string{hostsKey, "github.com", oauthTokenKey}, "test-token")
}
func TestLoginSetsUserForProvidedHost(t *testing.T) {
// Given we are not logged in
authCfg := newTestAuthConfig(t)
// When we login
_, err := authCfg.Login("github.com", "test-user", "test-token", "ssh", false)
// Then it returns success and the user is set
require.NoError(t, err)
user, err := authCfg.ActiveUser("github.com")
require.NoError(t, err)
require.Equal(t, "test-user", user)
}
func TestLoginSetsGitProtocolForProvidedHost(t *testing.T) {
// Given we are logged in
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we get the host git protocol
hostProtocol, err := authCfg.cfg.Get([]string{hostsKey, "github.com", gitProtocolKey})
require.NoError(t, err)
// Then it returns the git protocol we provided on login
require.Equal(t, "ssh", hostProtocol)
}
func TestLoginAddsHostIfNotAlreadyAdded(t *testing.T) {
// Given we are logged in
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we get the hosts
hosts := authCfg.Hosts()
// Then it includes our logged in host
require.Contains(t, hosts, "github.com")
}
// This test mimics the behaviour of logging in with a token, not providing
// a git protocol, and using secure storage.
func TestLoginAddsUserToConfigWithoutGitProtocolAndWithSecureStorage(t *testing.T) {
// Given we are not logged in
authCfg := newTestAuthConfig(t)
// When we log in without git protocol and with secure storage
_, err := authCfg.Login("github.com", "test-user", "test-token", "", true)
require.NoError(t, err)
// Then the username is added under the users config
users, err := authCfg.cfg.Keys([]string{hostsKey, "github.com", usersKey})
require.NoError(t, err)
require.Contains(t, users, "test-user")
}
func TestLogoutRemovesHostAndKeyringToken(t *testing.T) {
// Given we are logged into a host
authCfg := newTestAuthConfig(t)
host := "github.com"
user := "test-user"
token := "test-token"
_, err := authCfg.Login(host, user, token, "ssh", true)
require.NoError(t, err)
// When we logout
err = authCfg.Logout(host, user)
// Then we return success, and the host and token are removed from the config and keyring
require.NoError(t, err)
requireNoKey(t, authCfg.cfg, []string{hostsKey, host})
_, err = keyring.Get(keyringServiceName(host), "")
require.ErrorContains(t, err, "secret not found in keyring")
_, err = keyring.Get(keyringServiceName(host), user)
require.ErrorContains(t, err, "secret not found in keyring")
}
func TestLogoutOfActiveUserSwitchesUserIfPossible(t *testing.T) {
// Given we have two accounts logged into a host
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "inactive-user", "test-token-1", "ssh", true)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "active-user", "test-token-2", "https", true)
require.NoError(t, err)
// When we logout of the active user
err = authCfg.Logout("github.com", "active-user")
// Then we return success and the inactive user is now active
require.NoError(t, err)
activeUser, err := authCfg.ActiveUser("github.com")
require.NoError(t, err)
require.Equal(t, "inactive-user", activeUser)
token, err := authCfg.TokenFromKeyring("github.com")
require.NoError(t, err)
require.Equal(t, "test-token-1", token)
usersForHost := authCfg.UsersForHost("github.com")
require.NotContains(t, "active-user", usersForHost)
}
func TestLogoutOfInactiveUserDoesNotSwitchUser(t *testing.T) {
// Given we have two accounts logged into a host
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "inactive-user-1", "test-token-1.1", "ssh", true)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "inactive-user-2", "test-token-1.2", "ssh", true)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "active-user", "test-token-2", "https", true)
require.NoError(t, err)
// When we logout of an inactive user
err = authCfg.Logout("github.com", "inactive-user-1")
// Then we return success and the active user is still active
require.NoError(t, err)
activeUser, err := authCfg.ActiveUser("github.com")
require.NoError(t, err)
require.Equal(t, "active-user", activeUser)
}
// Note that I'm not sure this test enforces particularly desirable behaviour
// since it leads users to believe a token has been removed when really
// that might have failed for some reason.
//
// The original intention here is that if the logout fails, the user can't
// really do anything to recover. On the other hand, a user might
// want to rectify this manually, for example if there were on a shared machine.
func TestLogoutIgnoresErrorsFromConfigAndKeyring(t *testing.T) {
// Given we have keyring that errors, and a config that
// doesn't even have a hosts key (which would cause Remove to fail)
keyring.MockInitWithError(errors.New("test-explosion"))
authCfg := newTestAuthConfig(t)
// When we logout
err := authCfg.Logout("github.com", "test-user")
// Then it returns success anyway, suppressing the errors
require.NoError(t, err)
}
func TestSwitchUserMakesSecureTokenActive(t *testing.T) {
// Given we have a user with a secure token
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", true)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", true)
require.NoError(t, err)
// When we switch to that user
require.NoError(t, authCfg.SwitchUser("github.com", "test-user-1"))
// Their secure token is now active
token, err := authCfg.TokenFromKeyring("github.com")
require.NoError(t, err)
require.Equal(t, "test-token-1", token)
}
func TestSwitchUserMakesInsecureTokenActive(t *testing.T) {
// Given we have a user with an insecure token
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", false)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", false)
require.NoError(t, err)
// When we switch to that user
require.NoError(t, authCfg.SwitchUser("github.com", "test-user-1"))
// Their insecure token is now active
token, source := authCfg.ActiveToken("github.com")
require.Equal(t, "test-token-1", token)
require.Equal(t, oauthTokenKey, source)
}
func TestSwitchUserUpdatesTheActiveUser(t *testing.T) {
// Given we have two users logged into a host
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", false)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", false)
require.NoError(t, err)
// When we switch to the other user
require.NoError(t, authCfg.SwitchUser("github.com", "test-user-1"))
// Then the active user is updated
activeUser, err := authCfg.ActiveUser("github.com")
require.NoError(t, err)
require.Equal(t, "test-user-1", activeUser)
}
func TestSwitchUserErrorsImmediatelyIfTheActiveTokenComesFromEnvironment(t *testing.T) {
// Given we have a token in the env
authCfg := newTestAuthConfig(t)
t.Setenv("GH_TOKEN", "unimportant-test-value")
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", true)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", true)
require.NoError(t, err)
// When we switch to a user
err = authCfg.SwitchUser("github.com", "test-user-1")
// Then it errors immediately with an informative message
require.ErrorContains(t, err, "currently active token for github.com is from GH_TOKEN")
}
func TestSwitchUserErrorsAndRestoresUserAndInsecureConfigUnderFailure(t *testing.T) {
// Given we have a user but no token can be found (because we deleted them, simulating an error case)
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", true)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", false)
require.NoError(t, err)
require.NoError(t, keyring.Delete(keyringServiceName("github.com"), "test-user-1"))
// When we switch to the user
err = authCfg.SwitchUser("github.com", "test-user-1")
// Then it returns an error
require.EqualError(t, err, "no token found for test-user-1")
// And restores the previous state
activeUser, err := authCfg.ActiveUser("github.com")
require.NoError(t, err)
require.Equal(t, "test-user-2", activeUser)
token, source := authCfg.ActiveToken("github.com")
require.Equal(t, "test-token-2", token)
require.Equal(t, "oauth_token", source)
}
func TestSwitchUserErrorsAndRestoresUserAndKeyringUnderFailure(t *testing.T) {
// Given we have a user but no token can be found (because we deleted them, simulating an error case)
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", false)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", true)
require.NoError(t, err)
require.NoError(t, authCfg.cfg.Remove([]string{hostsKey, "github.com", usersKey, "test-user-1", oauthTokenKey}))
// When we switch to the user
err = authCfg.SwitchUser("github.com", "test-user-1")
// Then it returns an error
require.EqualError(t, err, "no token found for test-user-1")
// And restores the previous state
activeUser, err := authCfg.ActiveUser("github.com")
require.NoError(t, err)
require.Equal(t, "test-user-2", activeUser)
token, source := authCfg.ActiveToken("github.com")
require.Equal(t, "test-token-2", token)
require.Equal(t, "keyring", source)
}
func TestSwitchClearsActiveSecureTokenWhenSwitchingToInsecureUser(t *testing.T) {
// Given we have an active secure token
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", false)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", true)
require.NoError(t, err)
// When we switch to an insecure user
require.NoError(t, authCfg.SwitchUser("github.com", "test-user-1"))
// Then the active secure token is cleared
_, err = authCfg.TokenFromKeyring("github.com")
require.Error(t, err)
}
func TestSwitchClearsActiveInsecureTokenWhenSwitchingToSecureUser(t *testing.T) {
// Given we have an active insecure token
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token-1", "ssh", true)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token-2", "ssh", false)
require.NoError(t, err)
// When we switch to a secure user
require.NoError(t, authCfg.SwitchUser("github.com", "test-user-1"))
// Then the active insecure token is cleared
requireNoKey(t, authCfg.cfg, []string{hostsKey, "github.com", oauthTokenKey})
}
func TestUsersForHostNoHost(t *testing.T) {
// Given we have a config with no hosts
authCfg := newTestAuthConfig(t)
// When we get the users for a host that doesn't exist
users := authCfg.UsersForHost("github.com")
// Then it returns nil
require.Nil(t, users)
}
func TestUsersForHostWithUsers(t *testing.T) {
// Given we have a config with a host and users
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token", "ssh", false)
require.NoError(t, err)
_, err = authCfg.Login("github.com", "test-user-2", "test-token", "ssh", false)
require.NoError(t, err)
// When we get the users for that host
users := authCfg.UsersForHost("github.com")
// Then it succeeds and returns the users
require.Equal(t, []string{"test-user-1", "test-user-2"}, users)
}
func TestTokenForUserSecureLogin(t *testing.T) {
// Given a user has logged in securely
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token", "ssh", true)
require.NoError(t, err)
// When we get the token
token, source, err := authCfg.TokenForUser("github.com", "test-user-1")
// Then it returns the token and the source as keyring
require.NoError(t, err)
require.Equal(t, "test-token", token)
require.Equal(t, "keyring", source)
}
func TestTokenForUserInsecureLogin(t *testing.T) {
// Given a user has logged in insecurely
authCfg := newTestAuthConfig(t)
_, err := authCfg.Login("github.com", "test-user-1", "test-token", "ssh", false)
require.NoError(t, err)
// When we get the token
token, source, err := authCfg.TokenForUser("github.com", "test-user-1")
// Then it returns the token and the source as oauth_token
require.NoError(t, err)
require.Equal(t, "test-token", token)
require.Equal(t, "oauth_token", source)
}
func TestTokenForUserNotFoundErrors(t *testing.T) {
// Given a user has not logged in
authCfg := newTestAuthConfig(t)
// When we get the token
_, _, err := authCfg.TokenForUser("github.com", "test-user-1")
// Then it returns an error
require.EqualError(t, err, "no token found for 'test-user-1'")
}
func requireKeyWithValue(t *testing.T, cfg *ghConfig.Config, keys []string, value string) {
t.Helper()
actual, err := cfg.Get(keys)
require.NoError(t, err)
require.Equal(t, value, actual)
}
func requireNoKey(t *testing.T, cfg *ghConfig.Config, keys []string) {
t.Helper()
_, err := cfg.Get(keys)
var keyNotFoundError *ghConfig.KeyNotFoundError
require.ErrorAs(t, err, &keyNotFoundError)
}
// Post migration tests
func TestUserWorksRightAfterMigration(t *testing.T) {
// Given we have logged in before migration
authCfg := newTestAuthConfig(t)
_, err := preMigrationLogin(authCfg, "github.com", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we migrate
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
// Then we can still get the user correctly
user, err := authCfg.ActiveUser("github.com")
require.NoError(t, err)
require.Equal(t, "test-user", user)
}
func TestGitProtocolWorksRightAfterMigration(t *testing.T) {
// Given we have logged in before migration with a non-default git protocol
authCfg := newTestAuthConfig(t)
_, err := preMigrationLogin(authCfg, "github.com", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we migrate
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
// Then we can still get the git protocol correctly
gitProtocol, err := authCfg.cfg.Get([]string{hostsKey, "github.com", gitProtocolKey})
require.NoError(t, err)
require.Equal(t, "ssh", gitProtocol)
}
func TestHostsWorksRightAfterMigration(t *testing.T) {
// Given we have logged in before migration
authCfg := newTestAuthConfig(t)
_, err := preMigrationLogin(authCfg, "ghe.io", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we migrate
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
// Then we can still get the hosts correctly
hosts := authCfg.Hosts()
require.Contains(t, hosts, "ghe.io")
}
func TestDefaultHostWorksRightAfterMigration(t *testing.T) {
// Given we have logged in before migration to an enterprise host
authCfg := newTestAuthConfig(t)
_, err := preMigrationLogin(authCfg, "ghe.io", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we migrate
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
// Then the default host is still the enterprise host
defaultHost, source := authCfg.DefaultHost()
require.Equal(t, "ghe.io", defaultHost)
require.Equal(t, hostsKey, source)
}
func TestTokenWorksRightAfterMigration(t *testing.T) {
// Given we have logged in before migration
authCfg := newTestAuthConfig(t)
_, err := preMigrationLogin(authCfg, "github.com", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we migrate
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
// Then we can still get the token correctly
token, source := authCfg.ActiveToken("github.com")
require.Equal(t, "test-token", token)
require.Equal(t, oauthTokenKey, source)
}
func TestTokenPrioritizesActiveUserToken(t *testing.T) {
// Given a keyring where the active slot contains the token from a previous user
authCfg := newTestAuthConfig(t)
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "", "test-token"))
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "test-user1", "test-token"))
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "test-user2", "test-token2"))
// When no active user is set
authCfg.cfg.Remove([]string{hostsKey, "github.com", userKey})
// And get the token from the auth config
token, source := authCfg.ActiveToken("github.com")
// Then it returns the token from the keyring active slot
require.Equal(t, "keyring", source)
require.Equal(t, "test-token", token)
// When we set the active user to test-user1
authCfg.cfg.Set([]string{hostsKey, "github.com", userKey}, "test-user1")
// And get the token from the auth config
token, source = authCfg.ActiveToken("github.com")
// Then it returns the token from the active user entry in the keyring
require.Equal(t, "keyring", source)
require.Equal(t, "test-token", token)
// When we set the active user to test-user2
authCfg.cfg.Set([]string{hostsKey, "github.com", userKey}, "test-user2")
// And get the token from the auth config
token, source = authCfg.ActiveToken("github.com")
// Then it returns the token from the active user entry in the keyring
require.Equal(t, "keyring", source)
require.Equal(t, "test-token2", token)
}
func TestTokenWithActiveUserNotInKeyringFallsBackToBlank(t *testing.T) {
// Given a keyring that contains a token for a host
authCfg := newTestAuthConfig(t)
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "", "test-token"))
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "test-user1", "test-token1"))
require.NoError(t, keyring.Set(keyringServiceName("github.com"), "test-user2", "test-token2"))
// When we set the active user to test-user3
authCfg.cfg.Set([]string{hostsKey, "github.com", userKey}, "test-user3")
// And get the token from the auth config
token, source := authCfg.ActiveToken("github.com")
// Then it returns successfully with the fallback token
require.Equal(t, "keyring", source)
require.Equal(t, "test-token", token)
}
func TestLogoutRightAfterMigrationRemovesHost(t *testing.T) {
// Given we have logged in before migration
authCfg := newTestAuthConfig(t)
host := "github.com"
user := "test-user"
token := "test-token"
_, err := preMigrationLogin(authCfg, host, user, token, "ssh", false)
require.NoError(t, err)
// When we migrate and logout
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
require.NoError(t, authCfg.Logout(host, user))
// Then the host is removed from the config
requireNoKey(t, authCfg.cfg, []string{hostsKey, "github.com"})
}
func TestLoginInsecurePostMigrationUsesConfigForToken(t *testing.T) {
// Given we have not logged in
authCfg := newTestAuthConfig(t)
// When we migrate and login with insecure storage
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
insecureStorageUsed, err := authCfg.Login("github.com", "test-user", "test-token", "", false)
// Then it returns success, notes that insecure storage was used, and stores the token in the config
// both under the host and under the user
require.NoError(t, err)
require.True(t, insecureStorageUsed, "expected to use insecure storage")
requireKeyWithValue(t, authCfg.cfg, []string{hostsKey, "github.com", oauthTokenKey}, "test-token")
requireKeyWithValue(t, authCfg.cfg, []string{hostsKey, "github.com", usersKey, "test-user", oauthTokenKey}, "test-token")
}
func TestLoginPostMigrationSetsGitProtocol(t *testing.T) {
// Given we have logged in after migration
authCfg := newTestAuthConfig(t)
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
_, err := authCfg.Login("github.com", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we get the host git protocol
hostProtocol, err := authCfg.cfg.Get([]string{hostsKey, "github.com", gitProtocolKey})
require.NoError(t, err)
// Then it returns the git protocol we provided on login
require.Equal(t, "ssh", hostProtocol)
}
func TestLoginPostMigrationSetsUser(t *testing.T) {
// Given we have logged in after migration
authCfg := newTestAuthConfig(t)
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
_, err := authCfg.Login("github.com", "test-user", "test-token", "ssh", false)
require.NoError(t, err)
// When we get the user
user, err := authCfg.ActiveUser("github.com")
// Then it returns success and the user we provided on login
require.NoError(t, err)
require.Equal(t, "test-user", user)
}
func TestLoginSecurePostMigrationRemovesTokenFromConfig(t *testing.T) {
// Given we have logged in insecurely
authCfg := newTestAuthConfig(t)
_, err := preMigrationLogin(authCfg, "github.com", "test-user", "test-token", "", false)
require.NoError(t, err)
// When we migrate and login again with secure storage
var m migration.MultiAccount
c := cfg{authCfg.cfg}
require.NoError(t, c.Migrate(m))
_, err = authCfg.Login("github.com", "test-user", "test-token", "", true)
// Then it returns success, having removed the old insecure oauth token entry
require.NoError(t, err)
requireNoKey(t, authCfg.cfg, []string{hostsKey, "github.com", oauthTokenKey})
requireNoKey(t, authCfg.cfg, []string{hostsKey, "github.com", usersKey, "test-user", oauthTokenKey})
}
// Copied and pasted directly from the trunk branch before doing any work on
// login, plus the addition of AuthConfig as the first arg since it is a method
// receiver in the real implementation.
func preMigrationLogin(c *AuthConfig, hostname, username, token, gitProtocol string, secureStorage bool) (bool, error) {
var setErr error
if secureStorage {
if setErr = keyring.Set(keyringServiceName(hostname), "", token); setErr == nil {
// Clean up the previous oauth_token from the config file.
_ = c.cfg.Remove([]string{hostsKey, hostname, oauthTokenKey})
}
}
insecureStorageUsed := false
if !secureStorage || setErr != nil {
c.cfg.Set([]string{hostsKey, hostname, oauthTokenKey}, token)
insecureStorageUsed = true
}
c.cfg.Set([]string{hostsKey, hostname, userKey}, username)
if gitProtocol != "" {
c.cfg.Set([]string{hostsKey, hostname, gitProtocolKey}, gitProtocol)
}
return insecureStorageUsed, ghConfig.Write(c.cfg)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/config/migration/multi_account.go | internal/config/migration/multi_account.go | package migration
import (
"errors"
"fmt"
"net/http"
"github.com/cli/cli/v2/internal/keyring"
ghAPI "github.com/cli/go-gh/v2/pkg/api"
"github.com/cli/go-gh/v2/pkg/config"
)
var noTokenError = errors.New("no token found")
type CowardlyRefusalError struct {
err error
}
func (e CowardlyRefusalError) Error() string {
// Consider whether we should add a call to action here like "open an issue with the contents of your redacted hosts.yml"
return fmt.Sprintf("cowardly refusing to continue with multi account migration: %s", e.err.Error())
}
var hostsKey = []string{"hosts"}
type tokenSource struct {
token string
inKeyring bool
}
// This migration exists to take a hosts section of the following structure:
//
// github.com:
// user: williammartin
// git_protocol: https
// editor: vim
// github.localhost:
// user: monalisa
// git_protocol: https
// oauth_token: xyz
//
// We want this to migrate to something like:
//
// github.com:
// user: williammartin
// git_protocol: https
// editor: vim
// users:
// williammartin:
//
// github.localhost:
// user: monalisa
// git_protocol: https
// oauth_token: xyz
// users:
// monalisa:
// oauth_token: xyz
//
// For each hosts, we will create a new key `users` with the value of the host level
// `user` key as a list entry. If there is a host level `oauth_token` we will
// put that under the new user entry, otherwise there will be no value for the
// new user key. No other host level configuration will be copied to the new user.
//
// The reason for this is that we can then add new users under a host.
// Note that we are only copying the config under a new users key, and
// under a specific user. The original config is left alone. This is to
// allow forward compatibility for older versions of gh and also to avoid
// breaking existing users of go-gh which looks at a specific location
// in the config for oauth tokens that are stored insecurely.
type MultiAccount struct {
// Allow injecting a transport layer in tests.
Transport http.RoundTripper
}
func (m MultiAccount) PreVersion() string {
// It is expected that there is no version key since this migration
// introduces it.
return ""
}
func (m MultiAccount) PostVersion() string {
return "1"
}
func (m MultiAccount) Do(c *config.Config) error {
hostnames, err := c.Keys(hostsKey)
// [github.com, github.localhost]
// We wouldn't expect to have a hosts key when this is the first time anyone
// is logging in with the CLI.
var keyNotFoundError *config.KeyNotFoundError
if errors.As(err, &keyNotFoundError) {
return nil
}
if err != nil {
return CowardlyRefusalError{errors.New("couldn't get hosts configuration")}
}
// If there are no hosts then it doesn't matter whether we migrate or not,
// so lets avoid any confusion and say there's no migration required.
if len(hostnames) == 0 {
return nil
}
// Otherwise let's get to the business of migrating!
for _, hostname := range hostnames {
tokenSource, err := getToken(c, hostname)
// If no token existed for this host we'll remove the entry from the hosts file
// by deleting it and moving on to the next one.
if errors.Is(err, noTokenError) {
// The only error that can be returned here is the key not existing, which
// we know can't be true.
_ = c.Remove(append(hostsKey, hostname))
continue
}
// For any other error we'll error out
if err != nil {
return CowardlyRefusalError{fmt.Errorf("couldn't find oauth token for %q: %w", hostname, err)}
}
username, err := getUsername(c, hostname, tokenSource.token, m.Transport)
if err != nil {
issueURL := "https://github.com/cli/cli/issues/8441"
return CowardlyRefusalError{fmt.Errorf("couldn't get user name for %q please visit %s for help: %w", hostname, issueURL, err)}
}
if err := migrateConfig(c, hostname, username); err != nil {
return CowardlyRefusalError{fmt.Errorf("couldn't migrate config for %q: %w", hostname, err)}
}
if err := migrateToken(hostname, username, tokenSource); err != nil {
return CowardlyRefusalError{fmt.Errorf("couldn't migrate oauth token for %q: %w", hostname, err)}
}
}
return nil
}
func getToken(c *config.Config, hostname string) (tokenSource, error) {
if token, _ := c.Get(append(hostsKey, hostname, "oauth_token")); token != "" {
return tokenSource{token: token, inKeyring: false}, nil
}
token, err := keyring.Get(keyringServiceName(hostname), "")
// If we have an error and it's not relating to there being no token
// then we'll return the error cause that's really unexpected.
if err != nil && !errors.Is(err, keyring.ErrNotFound) {
return tokenSource{}, err
}
// Otherwise we'll return a sentinel error
if err != nil || token == "" {
return tokenSource{}, noTokenError
}
return tokenSource{
token: token,
inKeyring: true,
}, nil
}
func getUsername(c *config.Config, hostname, token string, transport http.RoundTripper) (string, error) {
username, _ := c.Get(append(hostsKey, hostname, "user"))
if username != "" && username != "x-access-token" {
return username, nil
}
opts := ghAPI.ClientOptions{
Host: hostname,
AuthToken: token,
Transport: transport,
}
client, err := ghAPI.NewGraphQLClient(opts)
if err != nil {
return "", err
}
var query struct {
Viewer struct {
Login string
}
}
err = client.Query("CurrentUser", &query, nil)
if err != nil {
return "", err
}
return query.Viewer.Login, nil
}
func migrateToken(hostname, username string, tokenSource tokenSource) error {
// If token is not currently stored in the keyring do not migrate it,
// as it is being stored in the config and is being handled when migrating the config.
if !tokenSource.inKeyring {
return nil
}
return keyring.Set(keyringServiceName(hostname), username, tokenSource.token)
}
func migrateConfig(c *config.Config, hostname, username string) error {
// Set the user key in case it was previously an anonymous user.
c.Set(append(hostsKey, hostname, "user"), username)
// Create the username key with an empty value so it will be
// written even if there are no keys set under it.
c.Set(append(hostsKey, hostname, "users", username), "")
insecureToken, err := c.Get(append(hostsKey, hostname, "oauth_token"))
var keyNotFoundError *config.KeyNotFoundError
// If there is no token then we're done here
if errors.As(err, &keyNotFoundError) {
return nil
}
// If there's another error (current implementation doesn't have any other error but we'll be defensive)
// then bubble something up.
if err != nil {
return fmt.Errorf("couldn't get oauth token for %s: %s", hostname, err)
}
// Otherwise we'll set the token under the new key
c.Set(append(hostsKey, hostname, "users", username, "oauth_token"), insecureToken)
return nil
}
func keyringServiceName(hostname string) string {
return "gh:" + hostname
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/config/migration/multi_account_test.go | internal/config/migration/multi_account_test.go | package migration_test
import (
"errors"
"fmt"
"testing"
"github.com/cli/cli/v2/internal/config/migration"
"github.com/cli/cli/v2/internal/keyring"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/go-gh/v2/pkg/config"
"github.com/stretchr/testify/require"
)
func TestMigration(t *testing.T) {
cfg := config.ReadFromString(`
hosts:
github.com:
user: user1
oauth_token: xxxxxxxxxxxxxxxxxxxx
git_protocol: ssh
enterprise.com:
user: user2
oauth_token: yyyyyyyyyyyyyyyyyyyy
git_protocol: https
`)
var m migration.MultiAccount
require.NoError(t, m.Do(cfg))
// First we'll check that the oauth tokens have been moved to their new locations
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "users", "user1", "oauth_token"}, "xxxxxxxxxxxxxxxxxxxx")
requireKeyWithValue(t, cfg, []string{"hosts", "enterprise.com", "users", "user2", "oauth_token"}, "yyyyyyyyyyyyyyyyyyyy")
// Then we'll check that the old data has been left alone
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "user"}, "user1")
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "oauth_token"}, "xxxxxxxxxxxxxxxxxxxx")
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "git_protocol"}, "ssh")
requireKeyWithValue(t, cfg, []string{"hosts", "enterprise.com", "user"}, "user2")
requireKeyWithValue(t, cfg, []string{"hosts", "enterprise.com", "oauth_token"}, "yyyyyyyyyyyyyyyyyyyy")
requireKeyWithValue(t, cfg, []string{"hosts", "enterprise.com", "git_protocol"}, "https")
}
func TestMigrationSecureStorage(t *testing.T) {
cfg := config.ReadFromString(`
hosts:
github.com:
user: userOne
git_protocol: ssh
enterprise.com:
user: userTwo
git_protocol: https
`)
userOneToken := "userOne-token"
userTwoToken := "userTwo-token"
keyring.MockInit()
require.NoError(t, keyring.Set("gh:github.com", "", userOneToken))
require.NoError(t, keyring.Set("gh:enterprise.com", "", userTwoToken))
var m migration.MultiAccount
require.NoError(t, m.Do(cfg))
// Verify token gets stored with host and username
gotUserOneToken, err := keyring.Get("gh:github.com", "userOne")
require.NoError(t, err)
require.Equal(t, userOneToken, gotUserOneToken)
// Verify token still exists with only host
gotUserOneToken, err = keyring.Get("gh:github.com", "")
require.NoError(t, err)
require.Equal(t, userOneToken, gotUserOneToken)
// Verify token gets stored with host and username
gotUserTwoToken, err := keyring.Get("gh:enterprise.com", "userTwo")
require.NoError(t, err)
require.Equal(t, userTwoToken, gotUserTwoToken)
// Verify token still exists with only host
gotUserTwoToken, err = keyring.Get("gh:enterprise.com", "")
require.NoError(t, err)
require.Equal(t, userTwoToken, gotUserTwoToken)
// First we'll check that the users have been created with no config underneath them
requireKeyExists(t, cfg, []string{"hosts", "github.com", "users", "userOne"})
requireKeyExists(t, cfg, []string{"hosts", "enterprise.com", "users", "userTwo"})
// Then we'll check that the old data has been left alone
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "user"}, "userOne")
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "git_protocol"}, "ssh")
requireKeyWithValue(t, cfg, []string{"hosts", "enterprise.com", "user"}, "userTwo")
requireKeyWithValue(t, cfg, []string{"hosts", "enterprise.com", "git_protocol"}, "https")
}
func TestPreVersionIsEmptyString(t *testing.T) {
var m migration.MultiAccount
require.Equal(t, "", m.PreVersion())
}
func TestPostVersion(t *testing.T) {
var m migration.MultiAccount
require.Equal(t, "1", m.PostVersion())
}
func TestMigrationReturnsSuccessfullyWhenNoHostsEntry(t *testing.T) {
cfg := config.ReadFromString(``)
var m migration.MultiAccount
require.NoError(t, m.Do(cfg))
}
func TestMigrationReturnsSuccessfullyWhenEmptyHosts(t *testing.T) {
cfg := config.ReadFromString(`
hosts:
`)
var m migration.MultiAccount
require.NoError(t, m.Do(cfg))
}
func TestMigrationReturnsSuccessfullyWhenAnonymousUserExists(t *testing.T) {
// Simulates config that gets generated when a user logs
// in with a token and git protocol is not specified and
// secure storage is used.
token := "test-token"
keyring.MockInit()
require.NoError(t, keyring.Set("gh:github.com", "", token))
cfg := config.ReadFromString(`
hosts:
github.com:
user: x-access-token
`)
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.GraphQL(`query CurrentUser\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`),
)
m := migration.MultiAccount{Transport: reg}
require.NoError(t, m.Do(cfg))
require.Equal(t, fmt.Sprintf("token %s", token), reg.Requests[0].Header.Get("Authorization"))
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "user"}, "monalisa")
// monalisa key gets created with no value
users, err := cfg.Keys([]string{"hosts", "github.com", "users"})
require.NoError(t, err)
require.Equal(t, []string{"monalisa"}, users)
// Verify token gets stored with host and username
gotToken, err := keyring.Get("gh:github.com", "monalisa")
require.NoError(t, err)
require.Equal(t, token, gotToken)
// Verify token still exists with only host
gotToken, err = keyring.Get("gh:github.com", "")
require.NoError(t, err)
require.Equal(t, token, gotToken)
}
func TestMigrationReturnsSuccessfullyWhenAnonymousUserExistsAndInsecureStorage(t *testing.T) {
// Simulates config that gets generated when a user logs
// in with a token and git protocol is specified and
// secure storage is not used.
cfg := config.ReadFromString(`
hosts:
github.com:
user: x-access-token
oauth_token: test-token
git_protocol: ssh
`)
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.GraphQL(`query CurrentUser\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`),
)
m := migration.MultiAccount{Transport: reg}
require.NoError(t, m.Do(cfg))
require.Equal(t, "token test-token", reg.Requests[0].Header.Get("Authorization"))
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "user"}, "monalisa")
requireKeyWithValue(t, cfg, []string{"hosts", "github.com", "users", "monalisa", "oauth_token"}, "test-token")
}
func TestMigrationRemovesHostsWithInvalidTokens(t *testing.T) {
// Simulates config when user is logged in securely
// but no token entry is in the keyring.
keyring.MockInit()
cfg := config.ReadFromString(`
hosts:
github.com:
user: user1
git_protocol: ssh
`)
m := migration.MultiAccount{}
require.NoError(t, m.Do(cfg))
requireNoKey(t, cfg, []string{"hosts", "github.com"})
}
func TestMigrationErrorsWhenUnableToGetExpectedSecureToken(t *testing.T) {
// Simulates config when user is logged in securely
// but no token entry is in the keyring.
keyring.MockInitWithError(errors.New("keyring test error"))
cfg := config.ReadFromString(`
hosts:
github.com:
user: user1
git_protocol: ssh
`)
m := migration.MultiAccount{}
err := m.Do(cfg)
require.ErrorContains(t, err, `couldn't find oauth token for "github.com": keyring test error`)
}
func requireKeyExists(t *testing.T, cfg *config.Config, keys []string) {
t.Helper()
_, err := cfg.Get(keys)
require.NoError(t, err)
}
func requireKeyWithValue(t *testing.T, cfg *config.Config, keys []string, value string) {
t.Helper()
actual, err := cfg.Get(keys)
require.NoError(t, err)
require.Equal(t, value, actual)
}
func requireNoKey(t *testing.T, cfg *config.Config, keys []string) {
t.Helper()
_, err := cfg.Get(keys)
var keyNotFoundError *config.KeyNotFoundError
require.ErrorAs(t, err, &keyNotFoundError)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/authflow/flow.go | internal/authflow/flow.go | package authflow
import (
"bufio"
"fmt"
"io"
"net/http"
"net/url"
"github.com/atotto/clipboard"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/oauth"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
)
var (
// The "GitHub CLI" OAuth app
oauthClientID = "178c6fc778ccc68e1d6a"
// This value is safe to be embedded in version control
oauthClientSecret = "34ddeff2b558a23d38fba8a6de74f086ede1cc0b"
)
// AuthFlow initiates an OAuth device or web application flow to acquire a
// token. The provided HTTP client should be a plain client that does not set
// auth or other headers.
func AuthFlow(httpClient *http.Client, oauthHost string, IO *iostreams.IOStreams, notice string, additionalScopes []string, isInteractive bool, b browser.Browser, isCopyToClipboard bool) (string, string, error) {
w := IO.ErrOut
cs := IO.ColorScheme()
minimumScopes := []string{"repo", "read:org", "gist"}
scopes := append(minimumScopes, additionalScopes...)
host, err := oauth.NewGitHubHost(ghinstance.HostPrefix(oauthHost))
if err != nil {
return "", "", err
}
flow := &oauth.Flow{
Host: host,
ClientID: oauthClientID,
ClientSecret: oauthClientSecret,
CallbackURI: getCallbackURI(oauthHost),
Scopes: scopes,
DisplayCode: func(code, verificationURL string) error {
if isCopyToClipboard {
err := clipboard.WriteAll(code)
if err == nil {
fmt.Fprintf(w, "%s One-time code (%s) copied to clipboard\n", cs.Yellow("!"), cs.Bold(code))
return nil
}
fmt.Fprintf(w, "%s Failed to copy one-time code to clipboard\n", cs.Red("!"))
fmt.Fprintf(w, " %s\n", err)
}
fmt.Fprintf(w, "%s First copy your one-time code: %s\n", cs.Yellow("!"), cs.Bold(code))
return nil
},
BrowseURL: func(authURL string) error {
if u, err := url.Parse(authURL); err == nil {
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("invalid URL: %s", authURL)
}
} else {
return err
}
if !isInteractive {
fmt.Fprintf(w, "%s to continue in your web browser: %s\n", cs.Bold("Open this URL"), authURL)
return nil
}
fmt.Fprintf(w, "%s to open %s in your browser... ", cs.Bold("Press Enter"), authURL)
_ = waitForEnter(IO.In)
if err := b.Browse(authURL); err != nil {
fmt.Fprintf(w, "%s Failed opening a web browser at %s\n", cs.Red("!"), authURL)
fmt.Fprintf(w, " %s\n", err)
fmt.Fprint(w, " Please try entering the URL in your browser manually\n")
}
return nil
},
WriteSuccessHTML: func(w io.Writer) {
fmt.Fprint(w, oauthSuccessPage)
},
HTTPClient: httpClient,
Stdin: IO.In,
Stdout: w,
}
fmt.Fprintln(w, notice)
token, err := flow.DetectFlow()
if err != nil {
return "", "", err
}
userLogin, err := getViewer(oauthHost, token.Token, IO.ErrOut)
if err != nil {
return "", "", err
}
return token.Token, userLogin, nil
}
func getCallbackURI(oauthHost string) string {
callbackURI := "http://127.0.0.1/callback"
if ghauth.IsEnterprise(oauthHost) {
// the OAuth app on Enterprise hosts is still registered with a legacy callback URL
// see https://github.com/cli/cli/pull/222, https://github.com/cli/cli/pull/650
callbackURI = "http://localhost/"
}
return callbackURI
}
type cfg struct {
token string
}
func (c cfg) ActiveToken(hostname string) (string, string) {
return c.token, "oauth_token"
}
func getViewer(hostname, token string, logWriter io.Writer) (string, error) {
opts := api.HTTPClientOptions{
Config: cfg{token: token},
Log: logWriter,
}
client, err := api.NewHTTPClient(opts)
if err != nil {
return "", err
}
return api.CurrentLoginName(api.NewClientFromHTTP(client), hostname)
}
func waitForEnter(r io.Reader) error {
scanner := bufio.NewScanner(r)
scanner.Scan()
return scanner.Err()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/authflow/flow_test.go | internal/authflow/flow_test.go | package authflow
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_getCallbackURI(t *testing.T) {
tests := []struct {
name string
oauthHost string
want string
}{
{
name: "dotcom",
oauthHost: "github.com",
want: "http://127.0.0.1/callback",
},
{
name: "ghes",
oauthHost: "my.server.com",
want: "http://localhost/",
},
{
name: "ghec data residency (ghe.com)",
oauthHost: "stampname.ghe.com",
want: "http://127.0.0.1/callback",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, getCallbackURI(tt.oauthHost))
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/authflow/success.go | internal/authflow/success.go | package authflow
const oauthSuccessPage = `
<!doctype html>
<meta charset="utf-8">
<title>Success: GitHub CLI</title>
<style type="text/css">
body {
color: #1B1F23;
background: #F6F8FA;
font-size: 14px;
font-family: -apple-system, "Segoe UI", Helvetica, Arial, sans-serif;
line-height: 1.5;
max-width: 620px;
margin: 28px auto;
text-align: center;
}
h1 {
font-size: 24px;
margin-bottom: 0;
}
p {
margin-top: 0;
}
.box {
border: 1px solid #E1E4E8;
background: white;
padding: 24px;
margin: 28px;
}
</style>
<body>
<svg height="52" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="52" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
<div class="box">
<h1>Successfully authenticated GitHub CLI</h1>
<p>You may now close this tab and return to the terminal.</p>
</div>
</body>
`
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghinstance/host.go | internal/ghinstance/host.go | package ghinstance
import (
"errors"
"fmt"
"strings"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
)
// DefaultHostname is the domain name of the default GitHub instance.
const defaultHostname = "github.com"
// Localhost is the domain name of a local GitHub instance.
const localhost = "github.localhost"
// TenancyHost is the domain name of a tenancy GitHub instance.
const tenancyHost = "ghe.com"
// Default returns the host name of the default GitHub instance.
func Default() string {
return defaultHostname
}
// TenantName extracts the tenant name from tenancy host name and
// reports whether it found the tenant name.
func TenantName(h string) (string, bool) {
normalizedHostName := ghauth.NormalizeHostname(h)
return strings.CutSuffix(normalizedHostName, "."+tenancyHost)
}
func isGarage(h string) bool {
return strings.EqualFold(h, "garage.github.com")
}
func HostnameValidator(hostname string) error {
if len(strings.TrimSpace(hostname)) < 1 {
return errors.New("a value is required")
}
if strings.ContainsRune(hostname, '/') || strings.ContainsRune(hostname, ':') {
return errors.New("invalid hostname")
}
return nil
}
func GraphQLEndpoint(hostname string) string {
if isGarage(hostname) {
return fmt.Sprintf("https://%s/api/graphql", hostname)
}
if ghauth.IsEnterprise(hostname) {
return fmt.Sprintf("https://%s/api/graphql", hostname)
}
if strings.EqualFold(hostname, localhost) {
return fmt.Sprintf("http://api.%s/graphql", hostname)
}
return fmt.Sprintf("https://api.%s/graphql", hostname)
}
func RESTPrefix(hostname string) string {
if isGarage(hostname) {
return fmt.Sprintf("https://%s/api/v3/", hostname)
}
if ghauth.IsEnterprise(hostname) {
return fmt.Sprintf("https://%s/api/v3/", hostname)
}
if strings.EqualFold(hostname, localhost) {
return fmt.Sprintf("http://api.%s/", hostname)
}
return fmt.Sprintf("https://api.%s/", hostname)
}
func GistPrefix(hostname string) string {
prefix := "https://"
if strings.EqualFold(hostname, localhost) {
prefix = "http://"
}
return prefix + GistHost(hostname)
}
func GistHost(hostname string) string {
if isGarage(hostname) {
return fmt.Sprintf("%s/gist/", hostname)
}
if ghauth.IsEnterprise(hostname) {
return fmt.Sprintf("%s/gist/", hostname)
}
if strings.EqualFold(hostname, localhost) {
return fmt.Sprintf("%s/gist/", hostname)
}
return fmt.Sprintf("gist.%s/", hostname)
}
func HostPrefix(hostname string) string {
if strings.EqualFold(hostname, localhost) {
return fmt.Sprintf("http://%s/", hostname)
}
return fmt.Sprintf("https://%s/", hostname)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghinstance/host_test.go | internal/ghinstance/host_test.go | package ghinstance
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTenantName(t *testing.T) {
tests := []struct {
host string
wantTenant string
wantFound bool
}{
{
host: "github.com",
wantTenant: "github.com",
},
{
host: "github.localhost",
wantTenant: "github.localhost",
},
{
host: "garage.github.com",
wantTenant: "github.com",
},
{
host: "ghe.com",
wantTenant: "ghe.com",
},
{
host: "tenant.ghe.com",
wantTenant: "tenant",
wantFound: true,
},
{
host: "api.tenant.ghe.com",
wantTenant: "tenant",
wantFound: true,
},
}
for _, tt := range tests {
t.Run(tt.host, func(t *testing.T) {
if tenant, found := TenantName(tt.host); tenant != tt.wantTenant || found != tt.wantFound {
t.Errorf("TenantName(%v) = %v %v, want %v %v", tt.host, tenant, found, tt.wantTenant, tt.wantFound)
}
})
}
}
func TestHostnameValidator(t *testing.T) {
tests := []struct {
name string
input string
wantsErr bool
}{
{
name: "valid hostname",
input: "internal.instance",
wantsErr: false,
},
{
name: "hostname with slashes",
input: "//internal.instance",
wantsErr: true,
},
{
name: "empty hostname",
input: " ",
wantsErr: true,
},
{
name: "hostname with colon",
input: "internal.instance:2205",
wantsErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := HostnameValidator(tt.input)
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
})
}
}
func TestGraphQLEndpoint(t *testing.T) {
tests := []struct {
host string
want string
}{
{
host: "github.com",
want: "https://api.github.com/graphql",
},
{
host: "github.localhost",
want: "http://api.github.localhost/graphql",
},
{
host: "garage.github.com",
want: "https://garage.github.com/api/graphql",
},
{
host: "ghe.io",
want: "https://ghe.io/api/graphql",
},
{
host: "tenant.ghe.com",
want: "https://api.tenant.ghe.com/graphql",
},
}
for _, tt := range tests {
t.Run(tt.host, func(t *testing.T) {
if got := GraphQLEndpoint(tt.host); got != tt.want {
t.Errorf("GraphQLEndpoint() = %v, want %v", got, tt.want)
}
})
}
}
func TestRESTPrefix(t *testing.T) {
tests := []struct {
host string
want string
}{
{
host: "github.com",
want: "https://api.github.com/",
},
{
host: "github.localhost",
want: "http://api.github.localhost/",
},
{
host: "garage.github.com",
want: "https://garage.github.com/api/v3/",
},
{
host: "ghe.io",
want: "https://ghe.io/api/v3/",
},
{
host: "tenant.ghe.com",
want: "https://api.tenant.ghe.com/",
},
}
for _, tt := range tests {
t.Run(tt.host, func(t *testing.T) {
if got := RESTPrefix(tt.host); got != tt.want {
t.Errorf("RESTPrefix() = %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/internal/text/text.go | internal/text/text.go | package text
import (
"fmt"
"math"
"net/url"
"regexp"
"slices"
"strings"
"time"
"github.com/cli/go-gh/v2/pkg/text"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var whitespaceRE = regexp.MustCompile(`\s+`)
func Indent(s, indent string) string {
return text.Indent(s, indent)
}
// Title returns a copy of the string s with all Unicode letters that begin words mapped to their Unicode title case.
func Title(s string) string {
c := cases.Title(language.English)
return c.String(s)
}
// RemoveExcessiveWhitespace returns a copy of the string s with excessive whitespace removed.
func RemoveExcessiveWhitespace(s string) string {
return whitespaceRE.ReplaceAllString(strings.TrimSpace(s), " ")
}
func DisplayWidth(s string) int {
return text.DisplayWidth(s)
}
func Truncate(maxWidth int, s string) string {
return text.Truncate(maxWidth, s)
}
func Pluralize(num int, thing string) string {
return text.Pluralize(num, thing)
}
func FuzzyAgo(a, b time.Time) string {
return text.RelativeTimeAgo(a, b)
}
// FuzzyAgoAbbr is an abbreviated version of FuzzyAgo. It returns a human readable string of the
// time duration between a and b that is estimated to the nearest unit of time.
func FuzzyAgoAbbr(a, b time.Time) string {
ago := a.Sub(b)
if ago < time.Hour {
return fmt.Sprintf("%d%s", int(ago.Minutes()), "m")
}
if ago < 24*time.Hour {
return fmt.Sprintf("%d%s", int(ago.Hours()), "h")
}
if ago < 30*24*time.Hour {
return fmt.Sprintf("%d%s", int(ago.Hours())/24, "d")
}
return b.Format("Jan _2, 2006")
}
// DisplayURL returns a copy of the string urlStr removing everything except the scheme, hostname, and path.
// If the scheme is not specified, "https" is assumed.
// If there is an error parsing urlStr then urlStr is returned without modification.
func DisplayURL(urlStr string) string {
u, err := url.Parse(urlStr)
if err != nil {
return urlStr
}
scheme := u.Scheme
if scheme == "" {
scheme = "https"
}
return scheme + "://" + u.Hostname() + u.Path
}
// RemoveDiacritics returns the input value without "diacritics", or accent marks
func RemoveDiacritics(value string) string {
return text.RemoveDiacritics(value)
}
func PadRight(maxWidth int, s string) string {
return text.PadRight(maxWidth, s)
}
// FormatSlice concatenates elements of the given string slice into a
// well-formatted, possibly multiline, string with specific line length limit.
// Elements can be optionally surrounded by custom strings (e.g., quotes or
// brackets). If the lineLength argument is non-positive, no line length limit
// will be applied.
func FormatSlice(values []string, lineLength uint, indent uint, prependWith string, appendWith string, sort bool) string {
if lineLength <= 0 {
lineLength = math.MaxInt
}
sortedValues := values
if sort {
sortedValues = slices.Clone(values)
slices.Sort(sortedValues)
}
pre := strings.Repeat(" ", int(indent))
if len(sortedValues) == 0 {
return pre
} else if len(sortedValues) == 1 {
return pre + sortedValues[0]
}
builder := strings.Builder{}
currentLineLength := 0
sep := ","
ws := " "
for i := 0; i < len(sortedValues); i++ {
v := prependWith + sortedValues[i] + appendWith
isLast := i == -1+len(sortedValues)
if currentLineLength == 0 {
builder.WriteString(pre)
builder.WriteString(v)
currentLineLength += len(v)
if !isLast {
builder.WriteString(sep)
currentLineLength += len(sep)
}
} else {
if !isLast && currentLineLength+len(ws)+len(v)+len(sep) > int(lineLength) ||
isLast && currentLineLength+len(ws)+len(v) > int(lineLength) {
currentLineLength = 0
builder.WriteString("\n")
i--
continue
}
builder.WriteString(ws)
builder.WriteString(v)
currentLineLength += len(ws) + len(v)
if !isLast {
builder.WriteString(sep)
currentLineLength += len(sep)
}
}
}
return builder.String()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/text/text_test.go | internal/text/text_test.go | package text
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRemoveExcessiveWhitespace(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{
name: "nothing to remove",
input: "one two three",
want: "one two three",
},
{
name: "whitespace b-gone",
input: "\n one\n\t two three\r\n ",
want: "one two three",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := RemoveExcessiveWhitespace(tt.input)
assert.Equal(t, tt.want, got)
})
}
}
func TestFuzzyAgoAbbr(t *testing.T) {
const form = "2006-Jan-02 15:04:05"
now, _ := time.Parse(form, "2020-Nov-22 14:00:00")
cases := map[string]string{
"2020-Nov-22 14:00:00": "0m",
"2020-Nov-22 13:59:00": "1m",
"2020-Nov-22 13:30:00": "30m",
"2020-Nov-22 13:00:00": "1h",
"2020-Nov-22 02:00:00": "12h",
"2020-Nov-21 14:00:00": "1d",
"2020-Nov-07 14:00:00": "15d",
"2020-Oct-24 14:00:00": "29d",
"2020-Oct-23 14:00:00": "Oct 23, 2020",
"2019-Nov-22 14:00:00": "Nov 22, 2019",
}
for createdAt, expected := range cases {
d, err := time.Parse(form, createdAt)
assert.NoError(t, err)
fuzzy := FuzzyAgoAbbr(now, d)
assert.Equal(t, expected, fuzzy)
}
}
func TestFormatSlice(t *testing.T) {
tests := []struct {
name string
values []string
indent uint
lineLength uint
prependWith string
appendWith string
sort bool
wants string
}{
{
name: "empty",
lineLength: 10,
values: []string{},
wants: "",
},
{
name: "empty with indent",
lineLength: 10,
indent: 2,
values: []string{},
wants: " ",
},
{
name: "single",
lineLength: 10,
values: []string{"foo"},
wants: "foo",
},
{
name: "single with indent",
lineLength: 10,
indent: 2,
values: []string{"foo"},
wants: " foo",
},
{
name: "long single with indent",
lineLength: 10,
indent: 2,
values: []string{"some-long-value"},
wants: " some-long-value",
},
{
name: "exact line length",
lineLength: 4,
values: []string{"a", "b"},
wants: "a, b",
},
{
name: "values longer than line length",
lineLength: 4,
values: []string{"long-value", "long-value"},
wants: "long-value,\nlong-value",
},
{
name: "zero line length (no wrapping expected)",
lineLength: 0,
values: []string{"foo", "bar"},
wants: "foo, bar",
},
{
name: "simple",
lineLength: 10,
values: []string{"foo", "bar", "baz", "foo", "bar", "baz"},
wants: "foo, bar,\nbaz, foo,\nbar, baz",
},
{
name: "simple, surrounded",
lineLength: 13,
prependWith: "<",
appendWith: ">",
values: []string{"foo", "bar", "baz", "foo", "bar", "baz"},
wants: "<foo>, <bar>,\n<baz>, <foo>,\n<bar>, <baz>",
},
{
name: "sort",
lineLength: 99,
sort: true,
values: []string{"c", "b", "a"},
wants: "a, b, c",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.wants, FormatSlice(tt.values, tt.lineLength, tt.indent, tt.prependWith, tt.appendWith, tt.sort))
})
}
}
func TestDisplayURL(t *testing.T) {
tests := []struct {
name string
url string
want string
}{
{
name: "simple",
url: "https://github.com/cli/cli/issues/9470",
want: "https://github.com/cli/cli/issues/9470",
},
{
name: "without scheme",
url: "github.com/cli/cli/issues/9470",
want: "https://github.com/cli/cli/issues/9470",
},
{
name: "with query param and anchor",
url: "https://github.com/cli/cli/issues/9470?q=is:issue#issue-command",
want: "https://github.com/cli/cli/issues/9470",
},
{
name: "preserve http protocol use despite insecure",
url: "http://github.com/cli/cli/issues/9470",
want: "http://github.com/cli/cli/issues/9470",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, DisplayURL(tt.url))
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghrepo/repo.go | internal/ghrepo/repo.go | package ghrepo
import (
"fmt"
"net/url"
"strings"
"github.com/cli/cli/v2/internal/ghinstance"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
"github.com/cli/go-gh/v2/pkg/repository"
)
// Interface describes an object that represents a GitHub repository
type Interface interface {
RepoName() string
RepoOwner() string
RepoHost() string
}
// New instantiates a GitHub repository from owner and name arguments
func New(owner, repo string) Interface {
return NewWithHost(owner, repo, ghinstance.Default())
}
// NewWithHost is like New with an explicit host name
func NewWithHost(owner, repo, hostname string) Interface {
return &ghRepo{
owner: owner,
name: repo,
hostname: normalizeHostname(hostname),
}
}
// FullName serializes a GitHub repository into an "OWNER/REPO" string
func FullName(r Interface) string {
return fmt.Sprintf("%s/%s", r.RepoOwner(), r.RepoName())
}
func defaultHost() string {
host, _ := ghauth.DefaultHost()
return host
}
// FromFullName extracts the GitHub repository information from the following
// formats: "OWNER/REPO", "HOST/OWNER/REPO", and a full URL.
func FromFullName(nwo string) (Interface, error) {
return FromFullNameWithHost(nwo, defaultHost())
}
// FromFullNameWithHost is like FromFullName that defaults to a specific host for values that don't
// explicitly include a hostname.
func FromFullNameWithHost(nwo, fallbackHost string) (Interface, error) {
repo, err := repository.ParseWithHost(nwo, fallbackHost)
if err != nil {
return nil, err
}
return NewWithHost(repo.Owner, repo.Name, repo.Host), nil
}
// FromURL extracts the GitHub repository information from a git remote URL
func FromURL(u *url.URL) (Interface, error) {
if u.Hostname() == "" {
return nil, fmt.Errorf("no hostname detected")
}
parts := strings.SplitN(strings.Trim(u.Path, "/"), "/", 3)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid path: %s", u.Path)
}
return NewWithHost(parts[0], strings.TrimSuffix(parts[1], ".git"), u.Hostname()), nil
}
func normalizeHostname(h string) string {
return strings.ToLower(strings.TrimPrefix(h, "www."))
}
// IsSame compares two GitHub repositories
func IsSame(a, b Interface) bool {
return strings.EqualFold(a.RepoOwner(), b.RepoOwner()) &&
strings.EqualFold(a.RepoName(), b.RepoName()) &&
normalizeHostname(a.RepoHost()) == normalizeHostname(b.RepoHost())
}
func GenerateRepoURL(repo Interface, p string, args ...interface{}) string {
baseURL := fmt.Sprintf("%s%s/%s", ghinstance.HostPrefix(repo.RepoHost()), repo.RepoOwner(), repo.RepoName())
if p != "" {
if path := fmt.Sprintf(p, args...); path != "" {
return baseURL + "/" + path
}
}
return baseURL
}
func FormatRemoteURL(repo Interface, protocol string) string {
if protocol == "ssh" {
if tenant, found := ghinstance.TenantName(repo.RepoHost()); found {
return fmt.Sprintf("%s@%s:%s/%s.git", tenant, repo.RepoHost(), repo.RepoOwner(), repo.RepoName())
}
return fmt.Sprintf("git@%s:%s/%s.git", repo.RepoHost(), repo.RepoOwner(), repo.RepoName())
}
return fmt.Sprintf("%s%s/%s.git", ghinstance.HostPrefix(repo.RepoHost()), repo.RepoOwner(), repo.RepoName())
}
type ghRepo struct {
owner string
name string
hostname string
}
func (r ghRepo) RepoOwner() string {
return r.owner
}
func (r ghRepo) RepoName() string {
return r.name
}
func (r ghRepo) RepoHost() string {
return r.hostname
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/ghrepo/repo_test.go | internal/ghrepo/repo_test.go | package ghrepo
import (
"errors"
"fmt"
"net/url"
"testing"
)
func Test_repoFromURL(t *testing.T) {
tests := []struct {
name string
input string
result string
host string
err error
}{
{
name: "github.com URL",
input: "https://github.com/monalisa/octo-cat.git",
result: "monalisa/octo-cat",
host: "github.com",
err: nil,
},
{
name: "github.com URL with trailing slash",
input: "https://github.com/monalisa/octo-cat/",
result: "monalisa/octo-cat",
host: "github.com",
err: nil,
},
{
name: "www.github.com URL",
input: "http://www.GITHUB.com/monalisa/octo-cat.git",
result: "monalisa/octo-cat",
host: "github.com",
err: nil,
},
{
name: "too many path components",
input: "https://github.com/monalisa/octo-cat/pulls",
result: "",
host: "",
err: errors.New("invalid path: /monalisa/octo-cat/pulls"),
},
{
name: "non-GitHub hostname",
input: "https://example.com/one/two",
result: "one/two",
host: "example.com",
err: nil,
},
{
name: "filesystem path",
input: "/path/to/file",
result: "",
host: "",
err: errors.New("no hostname detected"),
},
{
name: "filesystem path with scheme",
input: "file:///path/to/file",
result: "",
host: "",
err: errors.New("no hostname detected"),
},
{
name: "github.com SSH URL",
input: "ssh://github.com/monalisa/octo-cat.git",
result: "monalisa/octo-cat",
host: "github.com",
err: nil,
},
{
name: "github.com HTTPS+SSH URL",
input: "https+ssh://github.com/monalisa/octo-cat.git",
result: "monalisa/octo-cat",
host: "github.com",
err: nil,
},
{
name: "github.com git URL",
input: "git://github.com/monalisa/octo-cat.git",
result: "monalisa/octo-cat",
host: "github.com",
err: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
u, err := url.Parse(tt.input)
if err != nil {
t.Fatalf("got error %q", err)
}
repo, err := FromURL(u)
if err != nil {
if tt.err == nil {
t.Fatalf("got error %q", err)
} else if tt.err.Error() == err.Error() {
return
}
t.Fatalf("got error %q", err)
}
got := fmt.Sprintf("%s/%s", repo.RepoOwner(), repo.RepoName())
if tt.result != got {
t.Errorf("expected %q, got %q", tt.result, got)
}
if tt.host != repo.RepoHost() {
t.Errorf("expected %q, got %q", tt.host, repo.RepoHost())
}
})
}
}
func TestFromFullName(t *testing.T) {
tests := []struct {
name string
input string
hostOverride string
wantOwner string
wantName string
wantHost string
wantErr error
}{
{
name: "OWNER/REPO combo",
input: "OWNER/REPO",
wantHost: "github.com",
wantOwner: "OWNER",
wantName: "REPO",
wantErr: nil,
},
{
name: "too few elements",
input: "OWNER",
wantErr: errors.New(`expected the "[HOST/]OWNER/REPO" format, got "OWNER"`),
},
{
name: "too many elements",
input: "a/b/c/d",
wantErr: errors.New(`expected the "[HOST/]OWNER/REPO" format, got "a/b/c/d"`),
},
{
name: "blank value",
input: "a/",
wantErr: errors.New(`expected the "[HOST/]OWNER/REPO" format, got "a/"`),
},
{
name: "with hostname",
input: "example.org/OWNER/REPO",
wantHost: "example.org",
wantOwner: "OWNER",
wantName: "REPO",
wantErr: nil,
},
{
name: "full URL",
input: "https://example.org/OWNER/REPO.git",
wantHost: "example.org",
wantOwner: "OWNER",
wantName: "REPO",
wantErr: nil,
},
{
name: "SSH URL",
input: "git@example.org:OWNER/REPO.git",
wantHost: "example.org",
wantOwner: "OWNER",
wantName: "REPO",
wantErr: nil,
},
{
name: "OWNER/REPO with default host override",
input: "OWNER/REPO",
hostOverride: "override.com",
wantHost: "override.com",
wantOwner: "OWNER",
wantName: "REPO",
wantErr: nil,
},
{
name: "HOST/OWNER/REPO with default host override",
input: "example.com/OWNER/REPO",
hostOverride: "override.com",
wantHost: "example.com",
wantOwner: "OWNER",
wantName: "REPO",
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.hostOverride != "" {
t.Setenv("GH_HOST", tt.hostOverride)
}
r, err := FromFullName(tt.input)
if tt.wantErr != nil {
if err == nil {
t.Fatalf("no error in result, expected %v", tt.wantErr)
} else if err.Error() != tt.wantErr.Error() {
t.Fatalf("expected error %q, got %q", tt.wantErr.Error(), err.Error())
}
return
}
if err != nil {
t.Fatalf("got error %v", err)
}
if r.RepoHost() != tt.wantHost {
t.Errorf("expected host %q, got %q", tt.wantHost, r.RepoHost())
}
if r.RepoOwner() != tt.wantOwner {
t.Errorf("expected owner %q, got %q", tt.wantOwner, r.RepoOwner())
}
if r.RepoName() != tt.wantName {
t.Errorf("expected name %q, got %q", tt.wantName, r.RepoName())
}
})
}
}
func TestFormatRemoteURL(t *testing.T) {
tests := []struct {
name string
repoHost string
repoOwner string
repoName string
protocol string
want string
}{
{
name: "https protocol",
repoHost: "github.com",
repoOwner: "owner",
repoName: "name",
protocol: "https",
want: "https://github.com/owner/name.git",
},
{
name: "https protocol local host",
repoHost: "github.localhost",
repoOwner: "owner",
repoName: "name",
protocol: "https",
want: "http://github.localhost/owner/name.git",
},
{
name: "ssh protocol",
repoHost: "github.com",
repoOwner: "owner",
repoName: "name",
protocol: "ssh",
want: "git@github.com:owner/name.git",
},
{
name: "ssh protocol tenancy host",
repoHost: "tenant.ghe.com",
repoOwner: "owner",
repoName: "name",
protocol: "ssh",
want: "tenant@tenant.ghe.com:owner/name.git",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := ghRepo{
hostname: tt.repoHost,
owner: tt.repoOwner,
name: tt.repoName,
}
if url := FormatRemoteURL(r, tt.protocol); url != tt.want {
t.Errorf("expected url %q, got %q", tt.want, url)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/browser/stub.go | internal/browser/stub.go | package browser
type Stub struct {
urls []string
}
func (b *Stub) Browse(url string) error {
b.urls = append(b.urls, url)
return nil
}
func (b *Stub) BrowsedURL() string {
if len(b.urls) > 0 {
return b.urls[0]
}
return ""
}
type _testing interface {
Errorf(string, ...interface{})
Helper()
}
func (b *Stub) Verify(t _testing, url string) {
t.Helper()
if url != "" {
switch len(b.urls) {
case 0:
t.Errorf("expected browser to open URL %q, but it was never invoked", url)
case 1:
if url != b.urls[0] {
t.Errorf("expected browser to open URL %q, got %q", url, b.urls[0])
}
default:
t.Errorf("expected browser to open one URL, but was invoked %d times", len(b.urls))
}
} else if len(b.urls) > 0 {
t.Errorf("expected no browser to open, but was invoked %d times: %v", len(b.urls), b.urls)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/internal/browser/browser.go | internal/browser/browser.go | package browser
import (
"io"
ghBrowser "github.com/cli/go-gh/v2/pkg/browser"
)
type Browser interface {
Browse(string) error
}
func New(launcher string, stdout, stderr io.Writer) Browser {
b := ghBrowser.New(launcher, stdout, stderr)
return b
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/script/build.go | script/build.go | // Build tasks for the GitHub CLI project.
//
// Usage: go run script/build.go [<tasks>...] [<env>...]
//
// Known tasks are:
//
// bin/gh:
// Builds the main executable.
// Supported environment variables:
// - GH_VERSION: determined from source by default
// - GH_OAUTH_CLIENT_ID
// - GH_OAUTH_CLIENT_SECRET
// - SOURCE_DATE_EPOCH: enables reproducible builds
// - GO_LDFLAGS
//
// manpages:
// Builds the man pages under `share/man/man1/`.
//
// clean:
// Deletes all built files.
//
package main
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/cli/safeexec"
)
var tasks = map[string]func(string) error{
"bin/gh": func(exe string) error {
info, err := os.Stat(exe)
if err == nil && !sourceFilesLaterThan(info.ModTime()) {
fmt.Printf("%s: `%s` is up to date.\n", self, exe)
return nil
}
ldflags := os.Getenv("GO_LDFLAGS")
ldflags = fmt.Sprintf("-X github.com/cli/cli/v2/internal/build.Version=%s %s", version(), ldflags)
ldflags = fmt.Sprintf("-X github.com/cli/cli/v2/internal/build.Date=%s %s", date(), ldflags)
if oauthSecret := os.Getenv("GH_OAUTH_CLIENT_SECRET"); oauthSecret != "" {
ldflags = fmt.Sprintf("-X github.com/cli/cli/v2/internal/authflow.oauthClientSecret=%s %s", oauthSecret, ldflags)
ldflags = fmt.Sprintf("-X github.com/cli/cli/v2/internal/authflow.oauthClientID=%s %s", os.Getenv("GH_OAUTH_CLIENT_ID"), ldflags)
}
buildTags, _ := os.LookupEnv("GO_BUILDTAGS")
args := []string{"go", "build", "-trimpath"}
if buildTags != "" {
args = append(args, "-tags", buildTags)
}
args = append(args, "-ldflags", ldflags, "-o", exe, "./cmd/gh")
return run(args...)
},
"manpages": func(_ string) error {
return run("go", "run", "./cmd/gen-docs", "--man-page", "--doc-path", "./share/man/man1/")
},
"clean": func(_ string) error {
return rmrf("bin", "share")
},
}
var self string
func main() {
args := os.Args[:1]
for _, arg := range os.Args[1:] {
if idx := strings.IndexRune(arg, '='); idx >= 0 {
os.Setenv(arg[:idx], arg[idx+1:])
} else {
args = append(args, arg)
}
}
if len(args) < 2 {
if isWindowsTarget() {
args = append(args, filepath.Join("bin", "gh.exe"))
} else {
args = append(args, "bin/gh")
}
}
self = filepath.Base(args[0])
if self == "build" {
self = "build.go"
}
for _, task := range args[1:] {
t := tasks[normalizeTask(task)]
if t == nil {
fmt.Fprintf(os.Stderr, "Don't know how to build task `%s`.\n", task)
os.Exit(1)
}
err := t(task)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintf(os.Stderr, "%s: building task `%s` failed.\n", self, task)
os.Exit(1)
}
}
}
func isWindowsTarget() bool {
if os.Getenv("GOOS") == "windows" {
return true
}
if runtime.GOOS == "windows" {
return true
}
return false
}
func version() string {
if versionEnv := os.Getenv("GH_VERSION"); versionEnv != "" {
return versionEnv
}
if desc, err := cmdOutput("git", "describe", "--tags"); err == nil {
return desc
}
rev, _ := cmdOutput("git", "rev-parse", "--short", "HEAD")
return rev
}
func date() string {
t := time.Now()
if sourceDate := os.Getenv("SOURCE_DATE_EPOCH"); sourceDate != "" {
if sec, err := strconv.ParseInt(sourceDate, 10, 64); err == nil {
t = time.Unix(sec, 0)
}
}
return t.Format("2006-01-02")
}
func sourceFilesLaterThan(t time.Time) bool {
foundLater := false
err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
// Ignore errors that occur when the project contains a symlink to a filesystem or volume that
// Windows doesn't have access to.
if path != "." && isAccessDenied(err) {
fmt.Fprintf(os.Stderr, "%s: %v\n", path, err)
return nil
}
return err
}
if foundLater {
return filepath.SkipDir
}
if len(path) > 1 && (path[0] == '.' || path[0] == '_') {
if info.IsDir() {
return filepath.SkipDir
} else {
return nil
}
}
if info.IsDir() {
if name := filepath.Base(path); name == "vendor" || name == "node_modules" {
return filepath.SkipDir
}
return nil
}
if path == "go.mod" || path == "go.sum" || (strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go")) {
if info.ModTime().After(t) {
foundLater = true
}
}
return nil
})
if err != nil {
panic(err)
}
return foundLater
}
func isAccessDenied(err error) bool {
var pe *os.PathError
// we would use `syscall.ERROR_ACCESS_DENIED` if this script supported build tags
return errors.As(err, &pe) && strings.Contains(pe.Err.Error(), "Access is denied")
}
func rmrf(targets ...string) error {
args := append([]string{"rm", "-rf"}, targets...)
announce(args...)
for _, target := range targets {
if err := os.RemoveAll(target); err != nil {
return err
}
}
return nil
}
func announce(args ...string) {
fmt.Println(shellInspect(args))
}
func run(args ...string) error {
exe, err := safeexec.LookPath(args[0])
if err != nil {
return err
}
announce(args...)
cmd := exec.Command(exe, args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func cmdOutput(args ...string) (string, error) {
exe, err := safeexec.LookPath(args[0])
if err != nil {
return "", err
}
cmd := exec.Command(exe, args[1:]...)
cmd.Stderr = io.Discard
out, err := cmd.Output()
return strings.TrimSuffix(string(out), "\n"), err
}
func shellInspect(args []string) string {
fmtArgs := make([]string, len(args))
for i, arg := range args {
if strings.ContainsAny(arg, " \t'\"") {
fmtArgs[i] = fmt.Sprintf("%q", arg)
} else {
fmtArgs[i] = arg
}
}
return strings.Join(fmtArgs, " ")
}
func normalizeTask(t string) string {
return filepath.ToSlash(strings.TrimSuffix(t, ".exe"))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/context/remote.go | context/remote.go | package context
import (
"fmt"
"net/url"
"strings"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
)
// Remotes represents a set of git remotes
type Remotes []*Remote
// FindByName returns the first Remote whose name matches the list
func (r Remotes) FindByName(names ...string) (*Remote, error) {
for _, name := range names {
for _, rem := range r {
if rem.Name == name || name == "*" {
return rem, nil
}
}
}
return nil, fmt.Errorf("no matching remote found")
}
// FindByRepo returns the first Remote that points to a specific GitHub repository
func (r Remotes) FindByRepo(owner, name string) (*Remote, error) {
for _, rem := range r {
if strings.EqualFold(rem.RepoOwner(), owner) && strings.EqualFold(rem.RepoName(), name) {
return rem, nil
}
}
return nil, fmt.Errorf("no matching remote found; looking for %s/%s", owner, name)
}
// Filter remotes by given hostnames, maintains original order
func (r Remotes) FilterByHosts(hosts []string) Remotes {
filtered := make(Remotes, 0)
for _, rr := range r {
for _, host := range hosts {
if strings.EqualFold(rr.RepoHost(), host) {
filtered = append(filtered, rr)
break
}
}
}
return filtered
}
func (r Remotes) ResolvedRemote() (*Remote, error) {
for _, rr := range r {
if rr.Resolved != "" {
return rr, nil
}
}
return nil, fmt.Errorf("no resolved remote found")
}
func remoteNameSortScore(name string) int {
switch strings.ToLower(name) {
case "upstream":
return 3
case "github":
return 2
case "origin":
return 1
default:
return 0
}
}
// https://golang.org/pkg/sort/#Interface
func (r Remotes) Len() int { return len(r) }
func (r Remotes) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r Remotes) Less(i, j int) bool {
return remoteNameSortScore(r[i].Name) > remoteNameSortScore(r[j].Name)
}
// Remote represents a git remote mapped to a GitHub repository
type Remote struct {
*git.Remote
Repo ghrepo.Interface
}
// RepoName is the name of the GitHub repository
func (r Remote) RepoName() string {
return r.Repo.RepoName()
}
// RepoOwner is the name of the GitHub account that owns the repo
func (r Remote) RepoOwner() string {
return r.Repo.RepoOwner()
}
// RepoHost is the GitHub hostname that the remote points to
func (r Remote) RepoHost() string {
return r.Repo.RepoHost()
}
type Translator interface {
Translate(*url.URL) *url.URL
}
func TranslateRemotes(gitRemotes git.RemoteSet, translator Translator) (remotes Remotes) {
for _, r := range gitRemotes {
var repo ghrepo.Interface
if r.FetchURL != nil {
repo, _ = ghrepo.FromURL(translator.Translate(r.FetchURL))
}
if r.PushURL != nil && repo == nil {
repo, _ = ghrepo.FromURL(translator.Translate(r.PushURL))
}
if repo == nil {
continue
}
remotes = append(remotes, &Remote{
Remote: r,
Repo: repo,
})
}
return
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/context/context.go | context/context.go | // TODO: rename this package to avoid clash with stdlib
package context
import (
"errors"
"fmt"
"slices"
"sort"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/iostreams"
)
// Cap the number of git remotes to look up, since the user might have an
// unusually large number of git remotes.
const defaultRemotesForLookup = 5
func ResolveRemotesToRepos(remotes Remotes, client *api.Client, base string) (*ResolvedRemotes, error) {
sort.Stable(remotes)
result := &ResolvedRemotes{
remotes: remotes,
apiClient: client,
}
var baseOverride ghrepo.Interface
if base != "" {
var err error
baseOverride, err = ghrepo.FromFullName(base)
if err != nil {
return result, err
}
result.baseOverride = baseOverride
}
return result, nil
}
func resolveNetwork(result *ResolvedRemotes, remotesForLookup int) error {
var repos []ghrepo.Interface
for _, r := range result.remotes {
repos = append(repos, r)
if len(repos) == remotesForLookup {
break
}
}
networkResult, err := api.RepoNetwork(result.apiClient, repos)
result.network = &networkResult
return err
}
type ResolvedRemotes struct {
baseOverride ghrepo.Interface
remotes Remotes
network *api.RepoNetworkResult
apiClient *api.Client
}
func (r *ResolvedRemotes) BaseRepo(io *iostreams.IOStreams) (ghrepo.Interface, error) {
if r.baseOverride != nil {
return r.baseOverride, nil
}
if len(r.remotes) == 0 {
return nil, errors.New("no git remotes")
}
// if any of the remotes already has a resolution, respect that
for _, r := range r.remotes {
if r.Resolved == "base" {
return r, nil
} else if r.Resolved != "" {
repo, err := ghrepo.FromFullName(r.Resolved)
if err != nil {
return nil, err
}
return ghrepo.NewWithHost(repo.RepoOwner(), repo.RepoName(), r.RepoHost()), nil
}
}
if !io.CanPrompt() {
// we cannot prompt, so just resort to the 1st remote
return r.remotes[0], nil
}
repos, err := r.NetworkRepos(defaultRemotesForLookup)
if err != nil {
return nil, err
}
if len(repos) == 0 {
return r.remotes[0], nil
} else if len(repos) == 1 {
return repos[0], nil
}
cs := io.ColorScheme()
fmt.Fprintf(io.ErrOut,
"%s No default remote repository has been set. To learn more about the default repository, run: gh repo set-default --help\n",
cs.FailureIcon())
fmt.Fprintln(io.Out)
return nil, errors.New(
"please run `gh repo set-default` to select a default remote repository.")
}
func (r *ResolvedRemotes) HeadRepos() ([]*api.Repository, error) {
if r.network == nil {
err := resolveNetwork(r, defaultRemotesForLookup)
if err != nil {
return nil, err
}
}
var results []*api.Repository
var ids []string // Check if repo duplicates
for _, repo := range r.network.Repositories {
if repo != nil && repo.ViewerCanPush() && !slices.Contains(ids, repo.ID) {
results = append(results, repo)
ids = append(ids, repo.ID)
}
}
return results, nil
}
// NetworkRepos fetches info about remotes for the network of repos.
// Pass a value of 0 to fetch info on all remotes.
func (r *ResolvedRemotes) NetworkRepos(remotesForLookup int) ([]*api.Repository, error) {
if r.network == nil {
err := resolveNetwork(r, remotesForLookup)
if err != nil {
return nil, err
}
}
var repos []*api.Repository
repoMap := map[string]bool{}
add := func(r *api.Repository) {
fn := ghrepo.FullName(r)
if _, ok := repoMap[fn]; !ok {
repoMap[fn] = true
repos = append(repos, r)
}
}
for _, repo := range r.network.Repositories {
if repo == nil {
continue
}
if repo.Parent != nil {
add(repo.Parent)
}
add(repo)
}
return repos, nil
}
// RemoteForRepo finds the git remote that points to a repository
func (r *ResolvedRemotes) RemoteForRepo(repo ghrepo.Interface) (*Remote, error) {
for _, remote := range r.remotes {
if ghrepo.IsSame(remote, repo) {
return remote, nil
}
}
return nil, errors.New("not found")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/context/remote_test.go | context/remote_test.go | package context
import (
"net/url"
"testing"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/stretchr/testify/assert"
)
func Test_Remotes_FindByName(t *testing.T) {
list := Remotes{
&Remote{Remote: &git.Remote{Name: "mona"}, Repo: ghrepo.New("monalisa", "myfork")},
&Remote{Remote: &git.Remote{Name: "origin"}, Repo: ghrepo.New("monalisa", "octo-cat")},
&Remote{Remote: &git.Remote{Name: "upstream"}, Repo: ghrepo.New("hubot", "tools")},
}
r, err := list.FindByName("upstream", "origin")
assert.NoError(t, err)
assert.Equal(t, "upstream", r.Name)
r, err = list.FindByName("nonexistent", "*")
assert.NoError(t, err)
assert.Equal(t, "mona", r.Name)
_, err = list.FindByName("nonexistent")
assert.Error(t, err, "no GitHub remotes found")
}
func Test_Remotes_FindByRepo(t *testing.T) {
list := Remotes{
&Remote{Remote: &git.Remote{Name: "remote-0"}, Repo: ghrepo.New("owner", "repo")},
&Remote{Remote: &git.Remote{Name: "remote-1"}, Repo: ghrepo.New("another-owner", "another-repo")},
}
tests := []struct {
name string
owner string
repo string
wantsRemote *Remote
wantsError string
}{
{
name: "exact match (owner/repo)",
owner: "owner",
repo: "repo",
wantsRemote: list[0],
},
{
name: "exact match (another-owner/another-repo)",
owner: "another-owner",
repo: "another-repo",
wantsRemote: list[1],
},
{
name: "case-insensitive match",
owner: "OWNER",
repo: "REPO",
wantsRemote: list[0],
},
{
name: "non-match (owner)",
owner: "unknown-owner",
repo: "repo",
wantsError: "no matching remote found; looking for unknown-owner/repo",
},
{
name: "non-match (repo)",
owner: "owner",
repo: "unknown-repo",
wantsError: "no matching remote found; looking for owner/unknown-repo",
},
{
name: "non-match (owner, repo)",
owner: "unknown-owner",
repo: "unknown-repo",
wantsError: "no matching remote found; looking for unknown-owner/unknown-repo",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r, err := list.FindByRepo(tt.owner, tt.repo)
if tt.wantsError != "" {
assert.Error(t, err, tt.wantsError)
assert.Nil(t, r)
} else {
assert.NoError(t, err)
assert.Equal(t, r, tt.wantsRemote)
}
})
}
}
type identityTranslator struct{}
func (it identityTranslator) Translate(u *url.URL) *url.URL {
return u
}
func Test_translateRemotes(t *testing.T) {
publicURL, _ := url.Parse("https://github.com/monalisa/hello")
originURL, _ := url.Parse("http://example.com/repo")
gitRemotes := git.RemoteSet{
&git.Remote{
Name: "origin",
FetchURL: originURL,
},
&git.Remote{
Name: "public",
FetchURL: publicURL,
},
}
result := TranslateRemotes(gitRemotes, identityTranslator{})
if len(result) != 1 {
t.Errorf("got %d results", len(result))
}
if result[0].Name != "public" {
t.Errorf("got %q", result[0].Name)
}
if result[0].RepoName() != "hello" {
t.Errorf("got %q", result[0].RepoName())
}
}
func Test_FilterByHosts(t *testing.T) {
r1 := &Remote{Remote: &git.Remote{Name: "mona"}, Repo: ghrepo.NewWithHost("monalisa", "myfork", "test.com")}
r2 := &Remote{Remote: &git.Remote{Name: "origin"}, Repo: ghrepo.NewWithHost("monalisa", "octo-cat", "example.com")}
r3 := &Remote{Remote: &git.Remote{Name: "upstream"}, Repo: ghrepo.New("hubot", "tools")}
list := Remotes{r1, r2, r3}
f := list.FilterByHosts([]string{"example.com", "test.com"})
assert.Equal(t, 2, len(f))
assert.Equal(t, r1, f[0])
assert.Equal(t, r2, f[1])
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/main.go | main.go | package main
import (
"context"
"github.com/spf13/cobra"
"github.com/ollama/ollama/cmd"
)
func main() {
cobra.CheckErr(cmd.NewCLI().ExecuteContext(context.Background()))
}
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/path.go | ml/path.go | package ml
import (
"os"
"path/filepath"
"runtime"
)
// LibPath is a path to lookup dynamic libraries
// in development it's usually 'build/lib/ollama'
// in distribution builds it's 'lib/ollama' on Windows
// '../lib/ollama' on Linux and the executable's directory on macOS
// note: distribution builds, additional GPU-specific libraries are
// found in subdirectories of the returned path, such as
// 'cuda_v12', 'rocm', etc.
var LibOllamaPath string = func() string {
exe, err := os.Executable()
if err != nil {
return ""
}
if eval, err := filepath.EvalSymlinks(exe); err == nil {
exe = eval
}
var libPath string
switch runtime.GOOS {
case "windows":
libPath = filepath.Join(filepath.Dir(exe), "lib", "ollama")
case "linux":
libPath = filepath.Join(filepath.Dir(exe), "..", "lib", "ollama")
case "darwin":
libPath = filepath.Dir(exe)
}
cwd, err := os.Getwd()
if err != nil {
return ""
}
paths := []string{
libPath,
// build paths for development
filepath.Join(filepath.Dir(exe), "build", "lib", "ollama"),
filepath.Join(cwd, "build", "lib", "ollama"),
}
for _, p := range paths {
if _, err := os.Stat(p); err == nil {
return p
}
}
return filepath.Dir(exe)
}()
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/device.go | ml/device.go | package ml
import (
"context"
"encoding/binary"
"encoding/json"
"fmt"
"hash/maphash"
"io"
"log/slog"
"math"
"net/http"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/ollama/ollama/format"
"github.com/ollama/ollama/logutil"
)
// GPULayers is a set of layers to be allocated on a single GPU
type GPULayers struct {
DeviceID
// Layers is a set of layer indicies to load
Layers []int
}
// FirstLayer returns the smallest layer index scheduled on this GPU, or MaxInt when empty.
func (g GPULayers) FirstLayer() int {
if len(g.Layers) == 0 {
return math.MaxInt
}
first := g.Layers[0]
for i := 1; i < len(g.Layers); i++ {
if g.Layers[i] < first {
first = g.Layers[i]
}
}
return first
}
func (g GPULayers) String() string {
if len(g.Layers) == 0 {
return ""
}
slices.Sort(g.Layers)
contiguous := true
base := g.Layers[0]
for i := range g.Layers {
if g.Layers[i] != base+i {
contiguous = false
break
}
}
if contiguous {
return fmt.Sprintf("ID:%v Layers:%v(%v..%v)", g.ID, len(g.Layers), g.Layers[0], g.Layers[len(g.Layers)-1])
} else {
return fmt.Sprintf("ID:%v Layers:%v%v", g.ID, len(g.Layers), g.Layers)
}
}
// GPULayersList is a set of layer allocations across multiple GPUs
type GPULayersList []GPULayers
func (l GPULayersList) Len() int { return len(l) }
func (l GPULayersList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
// Sort by the ordering of the layers offloaded
func (l GPULayersList) Less(i, j int) bool {
li := l[i].FirstLayer()
lj := l[j].FirstLayer()
return li < lj
}
func (l GPULayersList) String() string {
if l.Sum() > 0 {
return fmt.Sprintf("%v%v", l.Sum(), []GPULayers(l))
} else {
return fmt.Sprintf("%v", []GPULayers(l))
}
}
// Sum is the total number of layers assigned across all GPUs
func (l GPULayersList) Sum() int {
var sum int
for _, g := range l {
sum += len(g.Layers)
}
return sum
}
var h maphash.Hash
// Hash is an identifier of this layer assignment
func (l GPULayersList) Hash() uint64 {
h.Reset()
for _, g := range l {
if len(g.Layers) > 0 {
h.WriteString(g.ID + g.Library)
for _, l := range g.Layers {
binary.Write(&h, binary.NativeEndian, int64(l))
}
}
}
return h.Sum64()
}
// ErrNoMem is returned when panicing due to insufficient memory. It includes
// the attempted memory allocation.
type ErrNoMem struct {
BackendMemory
}
func (e ErrNoMem) Error() string {
return fmt.Sprintf("insufficient memory - required allocations: %+v", e.BackendMemory)
}
// Minimal unique device identification
type DeviceID struct {
// ID is an identifier for the device for matching with system
// management libraries. The ID is only unique for other devices
// using the same Library.
// This ID represents a "post filtered" view of the enumerated devices
// if the ID is numeric
ID string `json:"id"`
// Library identifies which library is used for the device (e.g. CUDA, ROCm, etc.)
Library string `json:"backend,omitempty"`
}
// DeviceMemory provides a breakdown of the memory needed
// per device, such as a CPU or GPU.
type DeviceMemory struct {
DeviceID
// Name is the name of the device as labeled by the backend. It
// may not be persistent across instances of the runner.
Name string
// Weights is the per-layer memory needed for the model weights.
Weights []uint64
// Cache is the per-layer memory needed for the KV cache.
Cache []uint64
// Graph is the size of the compute graph. It is not per-layer.
Graph uint64
}
func sumMemory(mem []uint64) uint64 {
var sum uint64
for _, m := range mem {
sum += m
}
return sum
}
// Size returns the total size of the memory required by this device
func (m DeviceMemory) Size() uint64 {
return sumMemory(m.Weights) + sumMemory(m.Cache) + m.Graph
}
func memoryPresent(mem []uint64) bool {
return slices.ContainsFunc(mem, func(m uint64) bool { return m != 0 })
}
func (m DeviceMemory) LogValue() slog.Value {
var attrs []slog.Attr
if memoryPresent(m.Weights) {
attrs = append(attrs, slog.Any("Weights", m.Weights))
}
if memoryPresent(m.Cache) {
attrs = append(attrs, slog.Any("Cache", m.Cache))
}
if m.Graph != 0 {
attrs = append(attrs, slog.Any("Graph", m.Graph))
}
if len(attrs) > 0 && m.ID != "" {
attrs = append([]slog.Attr{slog.String("ID", m.ID)}, attrs...)
}
return slog.GroupValue(attrs...)
}
// BackendMemory provides the amount of memory required to load the model
// per device based on the BackendParams. In some cases, not all required
// allocations will be known at this point. However, the size of the most recent
// allocation is guaranteed to be provided so that if it failed, the caller can
// accommodate that to make forward progress.
type BackendMemory struct {
// InputWeights are always located on the CPU and cannot be moved
InputWeights uint64
// CPU model components are located in system memory. This does not
// include unified memory allocated through the GPU.
CPU DeviceMemory
// GPU model components are located on one or more GPUs.
GPUs []DeviceMemory
}
func (m BackendMemory) LogValue() slog.Value {
var attrs []slog.Attr
if m.InputWeights != 0 {
attrs = append(attrs, slog.Any("InputWeights", m.InputWeights))
}
attrs = append(attrs, slog.Any(m.CPU.Name, m.CPU))
for _, g := range m.GPUs {
attrs = append(attrs, slog.Any(g.Name, g))
}
return slog.GroupValue(attrs...)
}
// Log prints a high level summary of the memory
func (m BackendMemory) Log(level slog.Level) {
var total uint64
for _, gpu := range m.GPUs {
if sum := sumMemory(gpu.Weights); sum > 0 {
slog.Log(context.TODO(), level, "model weights", "device", gpu.Name, "size", format.HumanBytes2(sum))
total += sum
}
}
if sum := m.InputWeights + sumMemory(m.CPU.Weights); sum > 0 {
slog.Log(context.TODO(), level, "model weights", "device", m.CPU.Name, "size", format.HumanBytes2(sum))
total += sum
}
for _, gpu := range m.GPUs {
if sum := sumMemory(gpu.Cache); sum > 0 {
slog.Log(context.TODO(), level, "kv cache", "device", gpu.Name, "size", format.HumanBytes2(sum))
total += sum
}
}
if sum := sumMemory(m.CPU.Cache); sum > 0 {
slog.Log(context.TODO(), level, "kv cache", "device", m.CPU.Name, "size", format.HumanBytes2(sum))
total += sum
}
for _, gpu := range m.GPUs {
if sum := gpu.Graph; sum > 0 {
slog.Log(context.TODO(), level, "compute graph", "device", gpu.Name, "size", format.HumanBytes2(sum))
total += sum
}
}
if sum := m.CPU.Graph; sum > 0 {
slog.Log(context.TODO(), level, "compute graph", "device", m.CPU.Name, "size", format.HumanBytes2(sum))
total += sum
}
if total > 0 {
slog.Log(context.TODO(), level, "total memory", "size", format.HumanBytes2(total))
}
}
type DeviceInfo struct {
DeviceID
// Name is the name of the device as labeled by the backend. It
// may not be persistent across instances of the runner.
Name string `json:"name"`
// Description is the longer user-friendly identification of the device
Description string `json:"description"`
// FilterID is populated with the unfiltered device ID if a numeric ID is used
// so the device can be included.
FilterID string `json:"filter_id,omitempty"`
// Integrated is set true for integrated GPUs, false for Discrete GPUs
Integrated bool `json:"integration,omitempty"`
// PCIID is the bus, device and domain ID of the device for deduplication
// when discovered by multiple backends
PCIID string `json:"pci_id,omitempty"`
// TotalMemory is the total amount of memory the device can use for loading models
TotalMemory uint64 `json:"total_memory"`
// FreeMemory is the amount of memory currently available on the device for loading models
FreeMemory uint64 `json:"free_memory,omitempty"`
// ComputeMajor is the major version of capabilities of the device
// if unsupported by the backend, -1 will be returned
ComputeMajor int
// ComputeMinor is the minor version of capabilities of the device
// if unsupported by the backend, -1 will be returned
ComputeMinor int
// Driver Information
DriverMajor int `json:"driver_major,omitempty"`
DriverMinor int `json:"driver_minor,omitempty"`
// Where backends were loaded from
LibraryPath []string
}
type SystemInfo struct {
// ThreadCount is the optimal number of threads to use for inference
ThreadCount int `json:"threads,omitempty"`
// TotalMemory is the total amount of system memory
TotalMemory uint64 `json:"total_memory,omitempty"`
// FreeMemory is the amount of memory currently available on the system for loading models
FreeMemory uint64 `json:"free_memory,omitempty"`
// FreeSwap is the amount of system swap space reported as available
FreeSwap uint64 `json:"free_swap,omitempty"`
}
func (d DeviceInfo) Compute() string {
// AMD gfx is encoded into the major minor in hex form
if strings.EqualFold(d.Library, "ROCm") {
return fmt.Sprintf("gfx%x%02x", d.ComputeMajor, d.ComputeMinor)
}
return strconv.Itoa(d.ComputeMajor) + "." + strconv.Itoa(d.ComputeMinor)
}
func (d DeviceInfo) Driver() string {
return strconv.Itoa(d.DriverMajor) + "." + strconv.Itoa(d.DriverMinor)
}
// MinimumMemory reports the amount of memory that should be set aside
// on the device for overhead (e.g. VRAM consumed by context structures independent
// of model allocations)
func (d DeviceInfo) MinimumMemory() uint64 {
if d.Library == "Metal" {
return 512 * format.MebiByte
}
return 457 * format.MebiByte
}
// Sort by Free Space.
// iGPUs are reported first, thus Reverse() yields the largest discrete GPU first
type ByFreeMemory []DeviceInfo
func (a ByFreeMemory) Len() int { return len(a) }
func (a ByFreeMemory) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByFreeMemory) Less(i, j int) bool {
if a[i].Integrated && !a[j].Integrated {
return true
} else if !a[i].Integrated && a[j].Integrated {
return false
}
return a[i].FreeMemory < a[j].FreeMemory
}
// ByPerformance groups devices by similar speed
func ByPerformance(l []DeviceInfo) [][]DeviceInfo {
resp := [][]DeviceInfo{}
scores := []bool{}
for _, info := range l {
found := false
requested := info.Integrated
for i, score := range scores {
if score == requested {
resp[i] = append(resp[i], info)
found = true
break
}
}
if !found {
scores = append(scores, requested)
resp = append(resp, []DeviceInfo{info})
}
}
return resp
}
func ByLibrary(l []DeviceInfo) [][]DeviceInfo {
resp := [][]DeviceInfo{}
libs := []string{}
for _, info := range l {
found := false
requested := info.Library
for i, lib := range libs {
if lib == requested {
resp[i] = append(resp[i], info)
found = true
break
}
}
if !found {
libs = append(libs, requested)
resp = append(resp, []DeviceInfo{info})
}
}
return resp
}
func LibraryPaths(l []DeviceInfo) []string {
gpuLibs := []string{LibOllamaPath}
for _, gpu := range l {
for _, dir := range gpu.LibraryPath {
needed := true
for _, existing := range gpuLibs {
if dir == existing {
needed = false
break
}
}
if needed {
gpuLibs = append(gpuLibs, dir)
}
}
}
return gpuLibs
}
type DeviceComparison int
const (
UniqueDevice DeviceComparison = iota
SameBackendDevice // The device is the same, and the library/backend is the same
DuplicateDevice // The same physical device but different library/backend (overlapping device)
)
func (a DeviceInfo) Compare(b DeviceInfo) DeviceComparison {
if a.PCIID != b.PCIID {
return UniqueDevice
}
// If PCIID is empty, we have to use ID + library for uniqueness
if a.PCIID == "" && a.DeviceID != b.DeviceID {
return UniqueDevice
}
if a.Library == b.Library {
return SameBackendDevice
}
return DuplicateDevice
}
// For a SameBackendDevice, return true if b is better than a
// e.g. newer GPU library version
func (a DeviceInfo) IsBetter(b DeviceInfo) bool {
aLib := a.LibraryPath[len(a.LibraryPath)-1]
bLib := b.LibraryPath[len(b.LibraryPath)-1]
if aLib == bLib {
return false
}
aLibSplit := strings.SplitN(aLib, "_", 2)
bLibSplit := strings.SplitN(bLib, "_", 2)
if len(aLibSplit) < 2 || len(bLibSplit) < 2 {
return false
}
if aLibSplit[0] != bLibSplit[0] {
slog.Debug("unexpected libraries", "a", aLib, "b", bLib)
return false
}
if aLibSplit[1] == bLibSplit[1] {
return false
}
cmp := []string{aLibSplit[1], bLibSplit[1]}
sort.Sort(sort.Reverse(sort.StringSlice(cmp)))
return cmp[0] == bLibSplit[1]
}
// For each GPU, check if it does NOT support flash attention
func FlashAttentionSupported(l []DeviceInfo) bool {
for _, gpu := range l {
supportsFA := gpu.Library == "cpu" ||
gpu.Name == "Metal" || gpu.Library == "Metal" ||
(gpu.Library == "CUDA" && gpu.DriverMajor >= 7 && !(gpu.ComputeMajor == 7 && gpu.ComputeMinor == 2)) ||
gpu.Library == "ROCm" ||
gpu.Library == "Vulkan"
if !supportsFA {
return false
}
}
return true
}
type FlashAttentionType int32
const (
// Aligned with llama_flash_attn_type
FlashAttentionAuto FlashAttentionType = -1
FlashAttentionDisabled FlashAttentionType = 0
FlashAttentionEnabled FlashAttentionType = 1
)
func (f FlashAttentionType) LogValue() slog.Value {
return slog.AnyValue(f.String())
}
func (f FlashAttentionType) String() string {
switch f {
case FlashAttentionAuto:
return "Auto"
case FlashAttentionDisabled:
return "Disabled"
case FlashAttentionEnabled:
return "Enabled"
default:
return "unknown"
}
}
// Given the list of GPUs this instantiation is targeted for,
// figure out the visible devices environment variables
// Set mustFilter true to enable filtering of CUDA devices
func GetVisibleDevicesEnv(l []DeviceInfo, mustFilter bool) map[string]string {
if len(l) == 0 {
return nil
}
env := map[string]string{}
for _, d := range l {
d.updateVisibleDevicesEnv(env, mustFilter)
}
return env
}
// NeedsInitValidation returns true if the device in question has the potential
// to crash at inference time and requires deeper validation before we include
// it in the supported devices list.
func (d DeviceInfo) NeedsInitValidation() bool {
// ROCm: rocblas will crash on unsupported devices.
// CUDA: verify CC is supported by the version of the library
return d.Library == "ROCm" || d.Library == "CUDA"
}
// Set the init validation environment variable
func (d DeviceInfo) AddInitValidation(env map[string]string) {
env["GGML_CUDA_INIT"] = "1" // force deep initialization to trigger crash on unsupported GPUs
}
// PreferredLibrary returns true if this library is preferred over the other input
// library
// Used to filter out Vulkan in favor of CUDA or ROCm
func (d DeviceInfo) PreferredLibrary(other DeviceInfo) bool {
// TODO in the future if we find Vulkan is better than ROCm on some devices
// that implementation can live here.
if d.Library == "CUDA" || d.Library == "ROCm" {
return true
}
return false
}
func (d DeviceInfo) updateVisibleDevicesEnv(env map[string]string, mustFilter bool) {
var envVar string
switch d.Library {
case "ROCm":
// ROCm must be filtered as it can crash the runner on unsupported devices
envVar = "ROCR_VISIBLE_DEVICES"
if runtime.GOOS != "linux" {
envVar = "HIP_VISIBLE_DEVICES"
}
case "CUDA":
if !mustFilter {
// By default we try to avoid filtering CUDA devices because ROCm also
// looks at the CUDA env var, and gets confused in mixed vendor environments.
return
}
envVar = "CUDA_VISIBLE_DEVICES"
default:
// Vulkan is not filtered via env var, but via scheduling decisions
return
}
v, existing := env[envVar]
if existing {
v = v + ","
}
if d.FilterID != "" {
v = v + d.FilterID
} else {
v = v + d.ID
}
env[envVar] = v
}
type BaseRunner interface {
// GetPort returns the localhost port number the runner is running on
GetPort() int
// HasExited indicates if the runner is no longer running. This can be used during
// bootstrap to detect if a given filtered device is incompatible and triggered an assert
HasExited() bool
}
type RunnerDiscovery interface {
BaseRunner
// GetDeviceInfos will perform a query of the underlying device libraries
// for device identification and free VRAM information
// During bootstrap scenarios, this routine may take seconds to complete
GetDeviceInfos(ctx context.Context) []DeviceInfo
}
type FilteredRunnerDiscovery interface {
RunnerDiscovery
// GetActiveDeviceIDs returns the filtered set of devices actively in
// use by this runner for running models. If the runner is a bootstrap runner, no devices
// will be active yet so no device IDs are returned.
// This routine will not query the underlying device and will return immediately
GetActiveDeviceIDs() []DeviceID
}
func GetDevicesFromRunner(ctx context.Context, runner BaseRunner) ([]DeviceInfo, error) {
var moreDevices []DeviceInfo
port := runner.GetPort()
tick := time.Tick(10 * time.Millisecond)
for {
select {
case <-ctx.Done():
return nil, fmt.Errorf("failed to finish discovery before timeout")
case <-tick:
r, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/info", port), nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
r.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(r)
if err != nil {
// slog.Warn("failed to send request", "error", err)
if runner.HasExited() {
return nil, fmt.Errorf("runner crashed")
}
continue
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
// old runner, fall back to bootstrapping model
return nil, fmt.Errorf("llamarunner free vram reporting not supported")
}
body, err := io.ReadAll(resp.Body)
if err != nil {
slog.Warn("failed to read response", "error", err)
continue
}
if resp.StatusCode != 200 {
logutil.Trace("runner failed to discover free VRAM", "status", resp.StatusCode, "response", body)
return nil, fmt.Errorf("runner error: %s", string(body))
}
if err := json.Unmarshal(body, &moreDevices); err != nil {
slog.Warn("unmarshal encode response", "error", err)
continue
}
return moreDevices, nil
}
}
}
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend.go | ml/backend.go | package ml
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"math"
"slices"
"strconv"
"strings"
"github.com/ollama/ollama/fs"
)
type Backend interface {
// Close frees all memory associated with this backend
Close()
Load(ctx context.Context, progress func(float32)) error
// BackendMemory returns the memory allocations that were made for this model
BackendMemory() BackendMemory
Config() fs.Config
Get(name string) Tensor
NewContext() Context
NewContextSize(size int) Context
// Enumerate the devices available for inference via this backend
BackendDevices() []DeviceInfo
}
// BackendCacheConfig should be implemented by backends that need special output
// from the cache to meet specific requirements. It is frequently implemented in
// conjunction with ScaledDotProductAttention.
type BackendCacheConfig interface {
CacheConfig() CacheConfig
}
// CacheConfig controls optimizations (mostly backend-specific) that may transform
// the output the cache to work better with specific kernels.
type CacheConfig struct {
// CachePadding specifies the multiple for the number of tokens of cache history
// that will be returned from cache Get for k, v and mask. The capacity of the
// cache itself will also be increased to a multiple of this size if needed.
CachePadding int
// PermutedV performs Permute(ctx, 1, 2, 0, 3) on v tensors stored via Put
// and return the permuted version via Get. This uses the cache copy operation
// to avoid a Contiguous call on the permuted tensor.
PermutedV bool
// MaskDType specifies the data type for generating the mask. If unset it will
// default to DTypeF32.
MaskDType DType
}
// BackendParams controls how the backend loads and executes models
type BackendParams struct {
// AllocMemory causes the backend to allocate memory for the model. If
// false, this is only being used for discovering the required amount of
// memory and cannot load the model for running.
AllocMemory bool
// NumThreads sets the number of threads to use if running on the CPU
NumThreads int
// GPULayers is the set of layers to offload to GPUs
GPULayers GPULayersList
// FlashAttention indicates that we should use a fused flash attention kernel
FlashAttention FlashAttentionType
}
var backends = make(map[string]func(string, BackendParams) (Backend, error))
func RegisterBackend(name string, f func(string, BackendParams) (Backend, error)) {
if _, ok := backends[name]; ok {
panic("backend: backend already registered")
}
backends[name] = f
}
func NewBackend(modelPath string, params BackendParams) (Backend, error) {
if backend, ok := backends["ggml"]; ok {
return backend(modelPath, params)
}
return nil, fmt.Errorf("unsupported backend")
}
type Context interface {
Empty(dtype DType, shape ...int) Tensor
Zeros(dtype DType, shape ...int) Tensor
FromBytes(dtype DType, s []byte, shape ...int) Tensor
FromFloats(s []float32, shape ...int) Tensor
FromInts(s []int32, shape ...int) Tensor
// Arange creates a 1D tensor with values within an interval (start, stop] increased by step.
Arange(start, stop, step float32, dtype DType) Tensor
Forward(...Tensor) Context
// SetBatchSize provides a hint on the batch size to optimize processing
// Uses heuristics if not set
SetBatchSize(int)
Compute(...Tensor)
ComputeWithNotify(func(), ...Tensor) // notify callback once compute has begun
// Reserve is analogous to Compute but rather than executing a
// graph, simply preallocates memory. Typically called with a
// worst case graph to ensure all resources are available for
// for future inference.
Reserve()
MaxGraphNodes() int
Close()
// Input returns a context appropriate for creating tensors that are
// inputs to the model (which includes things like output locations)
Input() Context
// Layer returns a context appropriate for creating intermediate tensors
Layer(int) Context
}
type Tensor interface {
Dim(n int) int
Stride(n int) int
Shape() []int
DType() DType
Cast(ctx Context, dtype DType) Tensor
Bytes() []byte
Floats() []float32
FromBytes([]byte)
FromFloats([]float32)
FromInts([]int32)
Add(ctx Context, t2 Tensor) Tensor
Sub(ctx Context, t2 Tensor) Tensor
Mul(ctx Context, t2 Tensor) Tensor
Div(ctx Context, t2 Tensor) Tensor
Mulmat(ctx Context, t2 Tensor) Tensor
MulmatFullPrec(ctx Context, t2 Tensor) Tensor
MulmatID(ctx Context, t2, ids Tensor) Tensor
AddID(ctx Context, t2, ids Tensor) Tensor
Softmax(ctx Context) Tensor
L2Norm(ctx Context, eps float32) Tensor
LayerNorm(ctx Context, weight, bias Tensor, eps float32) Tensor
RMSNorm(ctx Context, weight Tensor, eps float32) Tensor
Scale(ctx Context, s float64) Tensor
SumRows(ctx Context) Tensor
AvgPool2D(ctx Context, k, s int, p float32) Tensor
Conv2D(ctx Context, weight Tensor, s0, s1, p0, p1, d0, d1 int) Tensor
Conv3D(ctx Context, weight Tensor, c, s0, s1, s2, p0, p1, p2, d0, d1, d2 int) Tensor
IM2Col(ctx Context, weight Tensor, s0, s1, p0, p1, d0, d1 int) Tensor
Sin(ctx Context) Tensor
Cos(ctx Context) Tensor
Tanh(ctx Context) Tensor
GELU(ctx Context, up ...Tensor) Tensor
QuickGELU(ctx Context, up ...Tensor) Tensor
SILU(ctx Context, up ...Tensor) Tensor
RELU(ctx Context, up ...Tensor) Tensor
Sigmoid(ctx Context) Tensor
// AlphaLimitSILU is a variant of SILU that clamps the input to the range [-limit, limit]
SILUAlphaLimit(ctx Context, up Tensor, alpha, limit float32) Tensor
Reshape(ctx Context, shape ...int) Tensor
View(ctx Context, offset int, shape ...int) Tensor
Permute(ctx Context, shape ...int) Tensor
Contiguous(ctx Context, shape ...int) Tensor
Pad(ctx Context, shape ...int) Tensor
Stack(ctx Context, dim int, s ...Tensor) Tensor
// Repeat repeats the tensor n times along dimension dim
Repeat(ctx Context, dim, n int) Tensor
Concat(ctx Context, t2 Tensor, dim int) Tensor
Rows(ctx Context, t2 Tensor) Tensor
SetRows(ctx Context, src Tensor, idxs Tensor) Tensor
Copy(ctx Context, t2 Tensor) Tensor
Duplicate(ctx Context) Tensor
Slice(ctx Context, dim, low, high, step int) Tensor
Chunk(ctx Context, dim int, size int) []Tensor
ChunkSections(ctx Context, dim int, sections ...int) []Tensor
TopK(ctx Context, k int) Tensor
Argsort(ctx Context) Tensor
Mean(ctx Context) Tensor
Variance(ctx Context) Tensor
Stddev(ctx Context) Tensor
Sqr(ctx Context) Tensor
Sqrt(ctx Context) Tensor
Interpolate(ctx Context, dims [4]int, samplingMode SamplingMode) Tensor
}
// ScaledDotProductAttention implements a fused attention
// operation equivalent to following code on a tensor named
// query:
//
// query = query.Permute(ctx, 0, 2, 1, 3)
// key = key.Permute(ctx, 0, 2, 1, 3)
// value = value.Permute(ctx, 1, 2, 0, 3).Contiguous(ctx)
//
// kq := key.MulmatFullPrec(ctx, query)
//
// kq = kq.Scale(ctx, scale)
//
// if mask != nil {
// kq = kq.Add(ctx, mask)
// }
//
// kq = kq.Softmax(ctx)
//
// kqv := value.Mulmat(ctx, kq)
// return kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
//
// cacheConfigApplied indicates whether the optimizations requested through CacheConfig have been performed
type ScaledDotProductAttention interface {
ScaledDotProductAttention(ctx Context, key, value, mask, sinks Tensor, vmla Tensor, scale float64, cacheConfigApplied bool) Tensor
}
type number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64 |
~complex64 | ~complex128
}
func mul[T number](s ...T) T {
p := T(1)
for _, v := range s {
p *= v
}
return p
}
type DumpOptions func(*dumpOptions)
// DumpWithPrecision sets the number of decimal places to print. Applies to float32 and float64.
func DumpWithPrecision(n int) DumpOptions {
return func(opts *dumpOptions) {
opts.Precision = n
}
}
// DumpWithThreshold sets the threshold for printing the entire tensor. If the number of elements
// is less than or equal to this value, the entire tensor will be printed. Otherwise, only the
// beginning and end of each dimension will be printed.
func DumpWithThreshold(n int) DumpOptions {
return func(opts *dumpOptions) {
opts.Threshold = n
}
}
// DumpWithEdgeItems sets the number of elements to print at the beginning and end of each dimension.
func DumpWithEdgeItems(n int) DumpOptions {
return func(opts *dumpOptions) {
opts.EdgeItems = n
}
}
type dumpOptions struct {
Precision, Threshold, EdgeItems int
}
func Dump(ctx Context, t Tensor, optsFuncs ...DumpOptions) string {
opts := dumpOptions{Precision: 4, Threshold: 1000, EdgeItems: 3}
for _, optsFunc := range optsFuncs {
optsFunc(&opts)
}
if mul(t.Shape()...) <= opts.Threshold {
opts.EdgeItems = math.MaxInt
}
switch t.DType() {
case DTypeF32:
return dump[[]float32](ctx, t, opts.EdgeItems, func(f float32) string {
return strconv.FormatFloat(float64(f), 'f', opts.Precision, 32)
})
case DTypeF16, DTypeQ80, DTypeQ40:
f32 := ctx.Input().Empty(DTypeF32, t.Shape()...)
f32 = t.Copy(ctx, f32)
return dump[[]float32](ctx, f32, opts.EdgeItems, func(f float32) string {
return strconv.FormatFloat(float64(f), 'f', opts.Precision, 32)
})
case DTypeI32:
return dump[[]int32](ctx, t, opts.EdgeItems, func(i int32) string {
return strconv.FormatInt(int64(i), 10)
})
default:
return "<unsupported>"
}
}
func dump[S ~[]E, E number](ctx Context, t Tensor, items int, fn func(E) string) string {
if t.Bytes() == nil {
ctx.Forward(t).Compute(t)
}
s := make(S, mul(t.Shape()...))
if err := binary.Read(bytes.NewBuffer(t.Bytes()), binary.LittleEndian, &s); err != nil {
panic(err)
}
shape := t.Shape()
slices.Reverse(shape)
var sb strings.Builder
var f func([]int, int)
f = func(dims []int, stride int) {
prefix := strings.Repeat(" ", len(shape)-len(dims)+1)
sb.WriteString("[")
defer func() { sb.WriteString("]") }()
for i := 0; i < dims[0]; i++ {
if i >= items && i < dims[0]-items {
sb.WriteString("..., ")
// skip to next printable element
skip := dims[0] - 2*items
if len(dims) > 1 {
stride += mul(append(dims[1:], skip)...)
fmt.Fprint(&sb, strings.Repeat("\n", len(dims)-1), prefix)
}
i += skip - 1
} else if len(dims) > 1 {
f(dims[1:], stride)
stride += mul(dims[1:]...)
if i < dims[0]-1 {
fmt.Fprint(&sb, ",", strings.Repeat("\n", len(dims)-1), prefix)
}
} else {
text := fn(s[stride+i])
if len(text) > 0 && text[0] != '-' {
sb.WriteString(" ")
}
sb.WriteString(text)
if i < dims[0]-1 {
sb.WriteString(", ")
}
}
}
}
f(shape, 0)
return sb.String()
}
type DType int
const (
DTypeOther DType = iota
DTypeF32
DTypeF16
DTypeQ80
DTypeQ40
DTypeI32
DTypeMXFP4
)
type SamplingMode int
const (
SamplingModeNearest SamplingMode = iota
SamplingModeBilinear
)
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/backend.go | ml/backend/backend.go | package backend
import (
_ "github.com/ollama/ollama/ml/backend/ggml"
)
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/quantization.go | ml/backend/ggml/quantization.go | package ggml
// #cgo CPPFLAGS: -I${SRCDIR}/ggml/src
// #include <stdlib.h>
// #include <stdint.h>
// #include "ggml.h"
// #include "ggml-cpu.h"
// #include "ggml-backend.h"
// #include "ggml-quants.h"
import "C"
import (
"unsafe"
fsggml "github.com/ollama/ollama/fs/ggml"
)
// ConvertToF32 converts (dequantizes) the raw data to F32 so we can then quantize it
func ConvertToF32(data []byte, dtype uint32, nelements uint64) []float32 {
f32s := make([]float32, nelements)
elems := C.int64_t(nelements)
switch dtype {
case C.GGML_TYPE_F16:
C.ggml_fp16_to_fp32_row((*C.uint16_t)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q4_0:
C.dequantize_row_q4_0((*C.block_q4_0)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q4_1:
C.dequantize_row_q4_1((*C.block_q4_1)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q5_0:
C.dequantize_row_q5_0((*C.block_q5_0)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q5_1:
C.dequantize_row_q5_1((*C.block_q5_1)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q8_0:
C.dequantize_row_q8_0((*C.block_q8_0)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q2_K:
C.dequantize_row_q2_K((*C.block_q2_K)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q3_K:
C.dequantize_row_q3_K((*C.block_q3_K)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q4_K:
C.dequantize_row_q4_K((*C.block_q4_K)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q5_K:
C.dequantize_row_q5_K((*C.block_q5_K)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_Q6_K:
C.dequantize_row_q6_K((*C.block_q6_K)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_BF16:
C.ggml_bf16_to_fp32_row((*C.ggml_bf16_t)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
case C.GGML_TYPE_MXFP4:
C.dequantize_row_mxfp4((*C.block_mxfp4)(unsafe.Pointer(&data[0])), (*C.float)(&f32s[0]), elems)
default:
panic("unsupported quantization format")
}
return f32s
}
func Quantize(newType fsggml.TensorType, f32s []float32, shape []uint64) []byte {
buf := make([]byte, len(f32s)*4) // upper bound on size
nPerRow := C.int64_t(shape[0])
nrows := C.int64_t(1)
if len(shape) > 1 {
nrows = C.int64_t(shape[1])
}
shape2 := C.int64_t(1)
if len(shape) > 2 {
shape2 = C.int64_t(shape[2])
}
nelements_matrix := nPerRow * nrows
newSize := C.size_t(0)
for i03 := C.int64_t(0); i03 < shape2; i03++ {
f32s_03 := i03 * nelements_matrix
buf_03 := C.int64_t(C.ggml_row_size(uint32(newType), nPerRow)) * i03 * nrows
newSize += C.ggml_quantize_chunk(
uint32(newType),
(*C.float)(&f32s[f32s_03]),
unsafe.Pointer((uintptr)(unsafe.Pointer(&buf[0]))+uintptr(buf_03)),
0,
nrows,
nPerRow,
nil)
}
return buf[:newSize]
}
func QuantizationVersion() uint32 {
return uint32(C.GGML_QNT_VERSION)
}
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/threads_debug.go | ml/backend/ggml/threads_debug.go | //go:build debug
package ggml
func Threads(_ int) int {
return 1
}
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/threads.go | ml/backend/ggml/threads.go | //go:build !debug
package ggml
func Threads(n int) int {
return n
}
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml_test.go | ml/backend/ggml/ggml_test.go | package ggml
import (
"errors"
"fmt"
"os"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/ollama/ollama/fs/ggml"
"github.com/ollama/ollama/ml"
)
func setup(tb testing.TB) ml.Context {
tb.Helper()
f, err := os.CreateTemp(tb.TempDir(), "*.bin")
if err != nil {
tb.Fatal(err)
}
defer f.Close()
if err := ggml.WriteGGUF(f, ggml.KV{"general.architecture": "test"}, nil); err != nil {
tb.Fatal(err)
}
b, err := ml.NewBackend(f.Name(), ml.BackendParams{AllocMemory: true})
if err != nil {
tb.Fatal(err)
}
ctx := b.NewContext().Input()
tb.Cleanup(func() {
ctx.Close()
b.Close()
})
return ctx
}
func TestInferShape(t *testing.T) {
cases := []struct {
name string
input []int
want []int
err error
}{
{
name: "no inferred shape",
input: []int{2, 3, 4},
want: []int{2, 3, 4},
},
{
name: "infer begin",
input: []int{-1, 3, 4},
want: []int{2, 3, 4},
},
{
name: "infer mid",
input: []int{2, -1, 4},
want: []int{2, 3, 4},
},
{
name: "infer end",
input: []int{2, 3, -1},
want: []int{2, 3, 4},
},
{
name: "too many inferred dims",
input: []int{-1, 3, -1},
err: errors.New("only one dimension can be inferred"),
},
{
name: "infer gather",
input: []int{2, -1},
want: []int{2, 12},
},
{
name: "infer gather all",
input: []int{-1},
want: []int{24},
},
{
name: "infer split",
input: []int{2, -1, 3, 2},
want: []int{2, 2, 3, 2},
},
{
name: "indivisible infer",
input: []int{2, -1, 2, 4},
err: errors.New("cannot infer dimension"),
},
{
name: "infer zero dim",
input: []int{2, 0, 4},
err: errors.New("dimension cannot be zero"),
},
}
ctx := setup(t)
tensor, ok := ctx.Empty(ml.DTypeF32, 2, 3, 4).(*Tensor)
if !ok {
t.Fatal("expected *Tensor")
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
defer func() {
if r := recover(); r == nil && tt.err == nil {
// all good
} else if r != nil && tt.err == nil {
t.Errorf("unexpected panic: %v", r)
} else if r == nil && tt.err != nil {
t.Errorf("expected panic but did not get one: %v", tt.err)
} else if errStr, ok := r.(string); ok && errStr != tt.err.Error() {
t.Errorf("expected panic %q but got %q", tt.err.Error(), errStr)
}
}()
inferShape(tensor, tt.input)
if diff := cmp.Diff(tt.want, tt.input); diff != "" {
t.Errorf("%s: shape mismatch (-want +got):\n%s", tt.name, diff)
}
})
}
}
func EquateTensors(ctx ml.Context) cmp.Option {
return cmp.Comparer(func(x, y ml.Tensor) bool {
ctx.Forward(x, y).Compute(x, y)
return cmp.Equal(x.Shape(), y.Shape()) &&
cmp.Equal(x.DType(), y.DType()) &&
cmp.Equal(x.Bytes(), y.Bytes())
})
}
func TestMulmat(t *testing.T) {
cases := []struct {
name string
a, b, c func(ml.Context) ml.Tensor
}{
{
name: "vector x vector",
a: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 3, 1, ml.DTypeF32)
},
b: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 3, 1, ml.DTypeF32)
},
c: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{5}, 1)
},
},
{
name: "vector x matrix",
a: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4, 1, ml.DTypeF32)
},
b: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 4, 3)
},
c: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
14, 38, 62,
}, 1, 3)
},
},
{
name: "broadcast vector x batched matrix",
a: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4, 1, ml.DTypeF32)
},
b: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 10*3*4, 1, ml.DTypeF32).Reshape(ctx, 4, 3, 10)
},
c: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
14, 38, 62,
86, 110, 134,
158, 182, 206,
230, 254, 278,
302, 326, 350,
374, 398, 422,
446, 470, 494,
518, 542, 566,
590, 614, 638,
662, 686, 710,
}, 1, 3, 10)
},
},
{
name: "batched matrix x batched matrix",
a: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*5*10, 1, ml.DTypeF32).Reshape(ctx, 4, 5, 10)
},
b: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*3*10, 1, ml.DTypeF32).Reshape(ctx, 4, 3, 10)
},
c: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
14, 38, 62, 86, 110,
38, 126, 214, 302, 390,
62, 214, 366, 518, 670,
1166, 1382, 1598, 1814, 2030,
1510, 1790, 2070, 2350, 2630,
1854, 2198, 2542, 2886, 3230,
4238, 4646, 5054, 5462, 5870,
4902, 5374, 5846, 6318, 6790,
5566, 6102, 6638, 7174, 7710,
9230, 9830, 10430, 11030, 11630,
10214, 10878, 11542, 12206, 12870,
11198, 11926, 12654, 13382, 14110,
16142, 16934, 17726, 18518, 19310,
17446, 18302, 19158, 20014, 20870,
18750, 19670, 20590, 21510, 22430,
24974, 25958, 26942, 27926, 28910,
26598, 27646, 28694, 29742, 30790,
28222, 29334, 30446, 31558, 32670,
35726, 36902, 38078, 39254, 40430,
37670, 38910, 40150, 41390, 42630,
39614, 40918, 42222, 43526, 44830,
48398, 49766, 51134, 52502, 53870,
50662, 52094, 53526, 54958, 56390,
52926, 54422, 55918, 57414, 58910,
62990, 64550, 66110, 67670, 69230,
65574, 67198, 68822, 70446, 72070,
68158, 69846, 71534, 73222, 74910,
79502, 81254, 83006, 84758, 86510,
82406, 84222, 86038, 87854, 89670,
85310, 87190, 89070, 90950, 92830,
}, 5, 3, 10)
},
},
{
name: "broadcast matrix x batched matrix",
a: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*5, 1, ml.DTypeF32).Reshape(ctx, 4, 5)
},
b: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*3*10, 1, ml.DTypeF32).Reshape(ctx, 4, 3, 10)
},
c: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
14, 38, 62, 86, 110,
38, 126, 214, 302, 390,
62, 214, 366, 518, 670,
86, 302, 518, 734, 950,
110, 390, 670, 950, 1230,
134, 478, 822, 1166, 1510,
158, 566, 974, 1382, 1790,
182, 654, 1126, 1598, 2070,
206, 742, 1278, 1814, 2350,
230, 830, 1430, 2030, 2630,
254, 918, 1582, 2246, 2910,
278, 1006, 1734, 2462, 3190,
302, 1094, 1886, 2678, 3470,
326, 1182, 2038, 2894, 3750,
350, 1270, 2190, 3110, 4030,
374, 1358, 2342, 3326, 4310,
398, 1446, 2494, 3542, 4590,
422, 1534, 2646, 3758, 4870,
446, 1622, 2798, 3974, 5150,
470, 1710, 2950, 4190, 5430,
494, 1798, 3102, 4406, 5710,
518, 1886, 3254, 4622, 5990,
542, 1974, 3406, 4838, 6270,
566, 2062, 3558, 5054, 6550,
590, 2150, 3710, 5270, 6830,
614, 2238, 3862, 5486, 7110,
638, 2326, 4014, 5702, 7390,
662, 2414, 4166, 5918, 7670,
686, 2502, 4318, 6134, 7950,
710, 2590, 4470, 6350, 8230,
}, 5, 3, 10)
},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
ctx := setup(t)
a, b := tt.a(ctx), tt.b(ctx)
c := a.Mulmat(ctx, b)
if diff := cmp.Diff(tt.c(ctx), c, EquateTensors(ctx)); diff != "" {
t.Errorf("MulMat() result mismatch (-want +got):\n%s", diff)
}
})
}
}
func TestPermute(t *testing.T) {
cases := []struct {
name string
input func(ml.Context) ml.Tensor
shape []int
want func(ml.Context) ml.Tensor
}{
{
name: "transpose",
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 3*2, 1, ml.DTypeF32).Reshape(ctx, 3, 2)
},
shape: []int{1, 0, 2, 3},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 3,
1, 4,
2, 5,
}, 2, 3)
},
},
{
name: "transpose fill dims",
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 3*2, 1, ml.DTypeF32).Reshape(ctx, 3, 2)
},
shape: []int{1, 0},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 3,
1, 4,
2, 5,
}, 2, 3)
},
},
{
name: "permute 3d",
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 5*3*2, 1, ml.DTypeF32).Reshape(ctx, 2, 3, 5)
},
shape: []int{2, 0, 1, 3},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 2, 4,
6, 8, 10,
12, 14, 16,
18, 20, 22,
24, 26, 28,
1, 3, 5,
7, 9, 11,
13, 15, 17,
19, 21, 23,
25, 27, 29,
}, 3, 5, 2)
},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
ctx := setup(t)
got := tt.input(ctx).Permute(ctx, tt.shape...)
got = got.Contiguous(ctx)
if diff := cmp.Diff(tt.want(ctx), got, EquateTensors(ctx)); diff != "" {
t.Errorf("Permute() result mismatch (-want +got):\n%s", diff)
}
})
}
}
func TestSlice(t *testing.T) {
cases := []struct {
dim int
low int
high int
step int
input func(ml.Context) ml.Tensor
want func(ml.Context) ml.Tensor
}{
{
dim: 0, low: 1, high: 3, step: 1,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
1, 2,
5, 6,
9, 10,
13, 14,
17, 18,
21, 22,
25, 26,
29, 30,
33, 34,
37, 38,
41, 42,
45, 46,
49, 50,
53, 54,
57, 58,
61, 62,
65, 66,
69, 70,
73, 74,
77, 78,
81, 82,
85, 86,
89, 90,
93, 94,
97, 98,
101, 102,
105, 106,
109, 110,
113, 114,
117, 118,
121, 122,
125, 126,
129, 130,
133, 134,
137, 138,
141, 142,
145, 146,
149, 150,
153, 154,
157, 158,
161, 162,
165, 166,
169, 170,
173, 174,
177, 178,
181, 182,
185, 186,
189, 190,
193, 194,
197, 198,
201, 202,
205, 206,
209, 210,
213, 214,
217, 218,
221, 222,
225, 226,
229, 230,
233, 234,
237, 238,
241, 242,
245, 246,
249, 250,
253, 254,
}, 2, 4, 4, 4)
},
},
{
dim: 1, low: 1, high: 3, step: 1,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
4, 5, 6, 7,
8, 9, 10, 11,
20, 21, 22, 23,
24, 25, 26, 27,
36, 37, 38, 39,
40, 41, 42, 43,
52, 53, 54, 55,
56, 57, 58, 59,
68, 69, 70, 71,
72, 73, 74, 75,
84, 85, 86, 87,
88, 89, 90, 91,
100, 101, 102, 103,
104, 105, 106, 107,
116, 117, 118, 119,
120, 121, 122, 123,
132, 133, 134, 135,
136, 137, 138, 139,
148, 149, 150, 151,
152, 153, 154, 155,
164, 165, 166, 167,
168, 169, 170, 171,
180, 181, 182, 183,
184, 185, 186, 187,
196, 197, 198, 199,
200, 201, 202, 203,
212, 213, 214, 215,
216, 217, 218, 219,
228, 229, 230, 231,
232, 233, 234, 235,
244, 245, 246, 247,
248, 249, 250, 251,
}, 4, 2, 4, 4)
},
},
{
dim: 2, low: 1, high: 3, step: 1,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
16, 17, 18, 19,
20, 21, 22, 23,
24, 25, 26, 27,
28, 29, 30, 31,
32, 33, 34, 35,
36, 37, 38, 39,
40, 41, 42, 43,
44, 45, 46, 47,
80, 81, 82, 83,
84, 85, 86, 87,
88, 89, 90, 91,
92, 93, 94, 95,
96, 97, 98, 99,
100, 101, 102, 103,
104, 105, 106, 107,
108, 109, 110, 111,
144, 145, 146, 147,
148, 149, 150, 151,
152, 153, 154, 155,
156, 157, 158, 159,
160, 161, 162, 163,
164, 165, 166, 167,
168, 169, 170, 171,
172, 173, 174, 175,
208, 209, 210, 211,
212, 213, 214, 215,
216, 217, 218, 219,
220, 221, 222, 223,
224, 225, 226, 227,
228, 229, 230, 231,
232, 233, 234, 235,
236, 237, 238, 239,
}, 4, 4, 2, 4)
},
},
{
dim: 3, low: 1, high: 3, step: 1,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
64, 65, 66, 67,
68, 69, 70, 71,
72, 73, 74, 75,
76, 77, 78, 79,
80, 81, 82, 83,
84, 85, 86, 87,
88, 89, 90, 91,
92, 93, 94, 95,
96, 97, 98, 99,
100, 101, 102, 103,
104, 105, 106, 107,
108, 109, 110, 111,
112, 113, 114, 115,
116, 117, 118, 119,
120, 121, 122, 123,
124, 125, 126, 127,
128, 129, 130, 131,
132, 133, 134, 135,
136, 137, 138, 139,
140, 141, 142, 143,
144, 145, 146, 147,
148, 149, 150, 151,
152, 153, 154, 155,
156, 157, 158, 159,
160, 161, 162, 163,
164, 165, 166, 167,
168, 169, 170, 171,
172, 173, 174, 175,
176, 177, 178, 179,
180, 181, 182, 183,
184, 185, 186, 187,
188, 189, 190, 191,
}, 4, 4, 4, 2)
},
},
{
dim: 0, low: 0, high: 4, step: 2,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 2,
4, 6,
8, 10,
12, 14,
16, 18,
20, 22,
24, 26,
28, 30,
32, 34,
36, 38,
40, 42,
44, 46,
48, 50,
52, 54,
56, 58,
60, 62,
64, 66,
68, 70,
72, 74,
76, 78,
80, 82,
84, 86,
88, 90,
92, 94,
96, 98,
100, 102,
104, 106,
108, 110,
112, 114,
116, 118,
120, 122,
124, 126,
128, 130,
132, 134,
136, 138,
140, 142,
144, 146,
148, 150,
152, 154,
156, 158,
160, 162,
164, 166,
168, 170,
172, 174,
176, 178,
180, 182,
184, 186,
188, 190,
192, 194,
196, 198,
200, 202,
204, 206,
208, 210,
212, 214,
216, 218,
220, 222,
224, 226,
228, 230,
232, 234,
236, 238,
240, 242,
244, 246,
248, 250,
252, 254,
}, 2, 4, 4, 4)
},
},
{
dim: 1, low: 0, high: 4, step: 2,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 1, 2, 3,
8, 9, 10, 11,
16, 17, 18, 19,
24, 25, 26, 27,
32, 33, 34, 35,
40, 41, 42, 43,
48, 49, 50, 51,
56, 57, 58, 59,
64, 65, 66, 67,
72, 73, 74, 75,
80, 81, 82, 83,
88, 89, 90, 91,
96, 97, 98, 99,
104, 105, 106, 107,
112, 113, 114, 115,
120, 121, 122, 123,
128, 129, 130, 131,
136, 137, 138, 139,
144, 145, 146, 147,
152, 153, 154, 155,
160, 161, 162, 163,
168, 169, 170, 171,
176, 177, 178, 179,
184, 185, 186, 187,
192, 193, 194, 195,
200, 201, 202, 203,
208, 209, 210, 211,
216, 217, 218, 219,
224, 225, 226, 227,
232, 233, 234, 235,
240, 241, 242, 243,
248, 249, 250, 251,
}, 4, 2, 4, 4)
},
},
{
dim: 2, low: 0, high: 4, step: 2,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15,
32, 33, 34, 35,
36, 37, 38, 39,
40, 41, 42, 43,
44, 45, 46, 47,
64, 65, 66, 67,
68, 69, 70, 71,
72, 73, 74, 75,
76, 77, 78, 79,
96, 97, 98, 99,
100, 101, 102, 103,
104, 105, 106, 107,
108, 109, 110, 111,
128, 129, 130, 131,
132, 133, 134, 135,
136, 137, 138, 139,
140, 141, 142, 143,
160, 161, 162, 163,
164, 165, 166, 167,
168, 169, 170, 171,
172, 173, 174, 175,
192, 193, 194, 195,
196, 197, 198, 199,
200, 201, 202, 203,
204, 205, 206, 207,
224, 225, 226, 227,
228, 229, 230, 231,
232, 233, 234, 235,
236, 237, 238, 239,
}, 4, 4, 2, 4)
},
},
{
dim: 3, low: 0, high: 4, step: 2,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 4*4*4*4, 1, ml.DTypeF32).Reshape(ctx, 4, 4, 4, 4)
},
want: func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15,
16, 17, 18, 19,
20, 21, 22, 23,
24, 25, 26, 27,
28, 29, 30, 31,
32, 33, 34, 35,
36, 37, 38, 39,
40, 41, 42, 43,
44, 45, 46, 47,
48, 49, 50, 51,
52, 53, 54, 55,
56, 57, 58, 59,
60, 61, 62, 63,
128, 129, 130, 131,
132, 133, 134, 135,
136, 137, 138, 139,
140, 141, 142, 143,
144, 145, 146, 147,
148, 149, 150, 151,
152, 153, 154, 155,
156, 157, 158, 159,
160, 161, 162, 163,
164, 165, 166, 167,
168, 169, 170, 171,
172, 173, 174, 175,
176, 177, 178, 179,
180, 181, 182, 183,
184, 185, 186, 187,
188, 189, 190, 191,
}, 4, 4, 4, 2)
},
},
}
for _, tt := range cases {
name := fmt.Sprintf("dim=%d,low=%d,high=%d,step=%d", tt.dim, tt.low, tt.high, tt.step)
t.Run(name, func(t *testing.T) {
ctx := setup(t)
got := tt.input(ctx).Slice(ctx, tt.dim, tt.low, tt.high, tt.step)
got = got.Contiguous(ctx)
if diff := cmp.Diff(tt.want(ctx), got, EquateTensors(ctx)); diff != "" {
t.Errorf("Slice() result mismatch (-want +got):\n%s", diff)
}
})
}
}
func TestSplitSections(t *testing.T) {
cases := []struct {
dim int
sections []int
input func(ml.Context) ml.Tensor
want []func(ml.Context) ml.Tensor
}{
{
dim: 0, sections: []int{1, 1, 1},
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 3, 4)
},
want: []func(ml.Context) ml.Tensor{
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{0, 3, 6, 9}, 1, 4)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{1, 4, 7, 10}, 1, 4)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{2, 5, 8, 11}, 1, 4)
},
},
},
{
dim: 1, sections: []int{1, 3},
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 3, 4)
},
want: []func(ml.Context) ml.Tensor{
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{0, 1, 2}, 3, 1)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
3, 4, 5,
6, 7, 8,
9, 10, 11,
}, 3, 3)
},
},
},
{
dim: 0, sections: []int{2, 2},
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 4, 3)
},
want: []func(ml.Context) ml.Tensor{
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 1,
4, 5,
8, 9,
}, 2, 3)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
2, 3,
6, 7,
10, 11,
}, 2, 3)
},
},
},
{
dim: 1, sections: []int{1, 2},
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 4, 3)
},
want: []func(ml.Context) ml.Tensor{
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{0, 1, 2, 3}, 4, 1)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
4, 5, 6, 7,
8, 9, 10, 11,
}, 4, 2)
},
},
},
}
for _, tt := range cases {
t.Run(fmt.Sprintf("sections=%v", tt.sections), func(t *testing.T) {
ctx := setup(t)
got := tt.input(ctx).ChunkSections(ctx, tt.dim, tt.sections...)
for i := range got {
got[i] = got[i].Contiguous(ctx)
}
ctx.Forward(got...).Compute(got...)
for i, want := range tt.want {
if diff := cmp.Diff(want(ctx), got[i], EquateTensors(ctx)); diff != "" {
t.Errorf("SplitSections() section %d mismatch (-want +got):\n%s", i, diff)
}
}
})
}
}
func TestChunk(t *testing.T) {
cases := []struct {
dim int
chunk int
input func(ml.Context) ml.Tensor
want []func(ml.Context) ml.Tensor
}{
{
dim: 0, chunk: 1,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 3, 4)
},
want: []func(ml.Context) ml.Tensor{
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{0, 3, 6, 9}, 1, 4)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{1, 4, 7, 10}, 1, 4)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{2, 5, 8, 11}, 1, 4)
},
},
},
{
dim: 1, chunk: 2,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 3, 4)
},
want: []func(ml.Context) ml.Tensor{
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 1, 2,
3, 4, 5,
}, 3, 2)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
6, 7, 8,
9, 10, 11,
}, 3, 2)
},
},
},
{
dim: 0, chunk: 2,
input: func(ctx ml.Context) ml.Tensor {
return ctx.Arange(0, 12, 1, ml.DTypeF32).Reshape(ctx, 3, 4)
},
want: []func(ml.Context) ml.Tensor{
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
0, 1,
3, 4,
6, 7,
9, 10,
}, 2, 4)
},
func(ctx ml.Context) ml.Tensor {
return ctx.FromFloats([]float32{
2,
5,
8,
11,
}, 1, 4)
},
},
},
}
for _, tt := range cases {
t.Run(fmt.Sprintf("dim=%d,chunk=%d", tt.dim, tt.chunk), func(t *testing.T) {
ctx := setup(t)
got := tt.input(ctx).Chunk(ctx, tt.dim, tt.chunk)
for i := range got {
got[i] = got[i].Contiguous(ctx)
}
ctx.Forward(got...).Compute(got...)
for i, want := range tt.want {
if diff := cmp.Diff(want(ctx), got[i], EquateTensors(ctx)); diff != "" {
t.Errorf("Split() section %d mismatch (-want +got):\n%s", i, diff)
}
}
})
}
}
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml.go | ml/backend/ggml/ggml.go | package ggml
// #cgo linux LDFLAGS: -lrt -lpthread -ldl -lstdc++ -lm
// #cgo windows LDFLAGS: -lpthread
// #cgo CPPFLAGS: -I${SRCDIR}/ggml/include
// #include <stdlib.h>
// #include <stdint.h>
// #include "ggml.h"
// #include "ggml-cpu.h"
// #include "ggml-backend.h"
import "C"
import (
"cmp"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"os"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"unicode"
"unsafe"
"github.com/ollama/ollama/format"
"github.com/ollama/ollama/fs"
fsggml "github.com/ollama/ollama/fs/ggml"
"github.com/ollama/ollama/logutil"
"github.com/ollama/ollama/ml"
ggml "github.com/ollama/ollama/ml/backend/ggml/ggml/src"
"github.com/ollama/ollama/ml/nn/rope"
"golang.org/x/sync/errgroup"
)
var (
cpus, accels, gpus []C.ggml_backend_dev_t
backends map[C.ggml_backend_dev_t]C.ggml_backend_t
)
var initDevices = sync.OnceFunc(func() {
ggml.OnceLoad()
backends = make(map[C.ggml_backend_dev_t]C.ggml_backend_t)
for i := range C.ggml_backend_dev_count() {
d := C.ggml_backend_dev_get(i)
switch C.ggml_backend_dev_type(d) {
case C.GGML_BACKEND_DEVICE_TYPE_CPU:
if len(cpus) == 0 {
// only the first cpu device should be used
cpus = append(cpus, d)
}
case C.GGML_BACKEND_DEVICE_TYPE_ACCEL:
accels = append(accels, d)
case C.GGML_BACKEND_DEVICE_TYPE_GPU,
C.GGML_BACKEND_DEVICE_TYPE_IGPU:
gpus = append(gpus, d)
}
backends[d] = C.ggml_backend_dev_init(d, nil)
}
})
type layerDevice struct {
d C.ggml_backend_dev_t
bt C.ggml_backend_buffer_type_t
}
type Backend struct {
// modelPath is the location of the model data
modelPath string
meta *fsggml.GGML
// allocMemory means that memory should be allocated for tensors and not
// just a dry run
allocMemory bool
// tensorLoadTargets maps from the name of the tensor in the file
// to the name that is used by the model definition
tensorLoadTargets map[string][]string
schedMu sync.Mutex // Only one Compute can run at a time
sched C.ggml_backend_sched_t
schedBackends []C.ggml_backend_t
schedBufts []C.ggml_backend_buffer_type_t
tensors map[string]*C.struct_ggml_tensor
// input is the backend buffer type used for inputs
input C.ggml_backend_buffer_type_t
// output is the backend device used for outputs
output C.ggml_backend_dev_t
// layers is the backend used for repeating layers
layers map[int]layerDevice
// requiredMemory is the cumulative memory allocations needed by the backend
requiredMemory *ml.BackendMemory
// btDeviceMemory maps from a buffer type to the memory allocations associated with that device
btDeviceMemory map[C.ggml_backend_buffer_type_t]*ml.DeviceMemory
flashAttention ml.FlashAttentionType
// maxGraphNodes is the maximum allowed number of graph nodes in this scheduler
maxGraphNodes int
// weightBuffers are the GGML contexts and buffers for allocating weights
weightBuffers map[*C.struct_ggml_context]C.ggml_backend_buffer_t
}
var once sync.Once
func New(modelPath string, params ml.BackendParams) (ml.Backend, error) {
r, err := os.Open(modelPath)
if err != nil {
return nil, err
}
defer r.Close()
meta, err := fsggml.Decode(r, -1)
if err != nil {
return nil, err
}
once.Do(func() {
slog.Info(
"",
"architecture", meta.KV().Architecture(),
"file_type", meta.KV().FileType(),
"name", meta.KV().String("general.name"),
"description", meta.KV().String("general.description"),
"num_tensors", len(meta.Tensors().Items()),
"num_key_values", len(meta.KV()),
)
})
initDevices()
var requiredMemory ml.BackendMemory
btDeviceMemory := make(map[C.ggml_backend_buffer_type_t]*ml.DeviceMemory)
type deviceBufferType struct {
d C.ggml_backend_dev_t
bts []C.ggml_backend_buffer_type_t
}
blocks := int(meta.KV().BlockCount())
// create list of buffer types for the cpu
cpuDeviceBufferType := deviceBufferType{d: C.ggml_backend_dev_by_type(C.GGML_BACKEND_DEVICE_TYPE_CPU)}
for _, d := range append(accels, append(gpus, cpus...)...) {
switch C.ggml_backend_dev_type(d) {
case C.GGML_BACKEND_DEVICE_TYPE_CPU,
C.GGML_BACKEND_DEVICE_TYPE_ACCEL:
bt := C.ggml_backend_dev_buffer_type(d)
cpuDeviceBufferType.bts = append(cpuDeviceBufferType.bts, bt)
btDeviceMemory[C.ggml_backend_dev_buffer_type(d)] = &requiredMemory.CPU
}
}
requiredMemory.CPU.Name = C.GoString(C.ggml_backend_dev_name(cpuDeviceBufferType.d))
var props C.struct_ggml_backend_dev_props
C.ggml_backend_dev_get_props(cpuDeviceBufferType.d, &props)
requiredMemory.CPU.ID = C.GoString(props.id)
requiredMemory.CPU.Library = C.GoString(props.library)
requiredMemory.CPU.Weights = make([]uint64, blocks+1)
requiredMemory.CPU.Cache = make([]uint64, blocks+1)
// create list of buffer types for each gpu
var gpuDeviceBufferTypes []deviceBufferType
requiredMemory.GPUs = make([]ml.DeviceMemory, len(gpus))
for i, d := range gpus {
bt := C.ggml_backend_dev_buffer_type(d)
gpuDeviceBufferTypes = append(gpuDeviceBufferTypes, deviceBufferType{
d: d,
bts: append([]C.ggml_backend_buffer_type_t{bt}, cpuDeviceBufferType.bts...),
})
btDeviceMemory[bt] = &requiredMemory.GPUs[i]
requiredMemory.GPUs[i].Name = C.GoString(C.ggml_backend_dev_name(d))
var props C.struct_ggml_backend_dev_props
C.ggml_backend_dev_get_props(d, &props)
requiredMemory.GPUs[i].ID = C.GoString(props.id)
requiredMemory.GPUs[i].Library = C.GoString(props.library)
requiredMemory.GPUs[i].Weights = make([]uint64, blocks+1)
requiredMemory.GPUs[i].Cache = make([]uint64, blocks+1)
}
// inputs always use cpu
input := cpuDeviceBufferType
assignLayer := func(layer int) deviceBufferType {
for _, p := range params.GPULayers {
for _, l := range p.Layers {
if l == layer {
for i := range requiredMemory.GPUs {
if requiredMemory.GPUs[i].DeviceID == p.DeviceID {
return gpuDeviceBufferTypes[i]
}
}
return cpuDeviceBufferType
}
}
}
return cpuDeviceBufferType
}
// repeating layers are assigned based on their index in reverse order, e.g. i / (block_count + 1)
layers := make([]deviceBufferType, blocks)
for i := range layers {
layers[i] = assignLayer(i)
}
// outputs are assigned iff allowed by splits and configured number of gpu layers
output := assignLayer(blocks)
maxTensors := len(meta.Tensors().Items())
maxTensors += 1
// each layer has at most 2 extra tensors for rope operations
maxTensors += blocks * 2
type tensor struct {
source *fsggml.Tensor
target string
}
// some tensors are mapped to different names so keep a list
targets := make(map[string][]string)
// contexts are shared by tensors of the same buffer type
ctxs := make(map[C.ggml_backend_buffer_type_t]*C.struct_ggml_context)
createTensor := func(t tensor, bts []C.ggml_backend_buffer_type_t, layer int) *C.struct_ggml_tensor {
for _, bt := range bts {
if _, ok := ctxs[bt]; !ok {
ctxs[bt] = C.ggml_init(C.struct_ggml_init_params{
mem_size: C.ggml_tensor_overhead() * C.size_t(maxTensors),
no_alloc: true,
})
}
targets[t.source.Name] = append(targets[t.source.Name], t.target)
name := t.source.Name
if t.target != "" {
name = t.target
}
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
if tt := C.ggml_get_tensor(ctxs[bt], cname); tt != nil {
return tt
}
kind := t.source.Kind
if t.source.Kind == 4 {
// transform raw mxfp4 stream to ggml mxfp4 format
kind = 39
} else if t.source.Kind == uint32(fsggml.TensorTypeBF16) && strings.HasSuffix(t.source.Name, "_exps.bias") {
// transform "_exps.bias" from bf16 to fp32; add_ids only supports fp32 tensors
kind = uint32(fsggml.TensorTypeF32)
}
tt := C.ggml_new_tensor(ctxs[bt], kind, C.int(len(t.source.Shape)), (*C.int64_t)(unsafe.Pointer(&t.source.Shape[0])))
C.ggml_set_name(tt, cname)
logutil.Trace("created tensor", "name", name, "shape", t.source.Shape, "dtype", t.source.Kind, "buffer_type", C.GoString(C.ggml_backend_buft_name(bt)))
size := pad(C.ggml_backend_buft_get_alloc_size(bt, tt), C.ggml_backend_buft_get_alignment(bt))
if layer == -1 {
requiredMemory.InputWeights += uint64(size)
} else {
btDeviceMemory[bt].Weights[layer] += uint64(size)
}
//nolint:staticcheck // TODO: check if buffer type supports this tensor
return tt
}
return nil
}
contains := func(s string, parts ...string) bool {
split := strings.Split(s, ".")
for _, part := range parts {
if slices.Contains(split, part) {
return true
}
}
return false
}
for _, t := range meta.Tensors().Items() {
switch {
case contains(t.Name, "position_embd", "token_embd", "token_norm_embd", "token_types"):
createTensor(tensor{source: t}, input.bts, -1)
if _, ok := meta.Tensors().GroupLayers()["output"]; !ok && t.Name == "token_embd.weight" {
createTensor(tensor{source: t, target: "output.weight"}, output.bts, blocks)
}
case contains(t.Name, "cls", "output", "output_norm",
"altup_proj", "altup_unembd_proj",
"per_layer_token_embd", "per_layer_model_proj", "per_layer_proj_norm"):
createTensor(tensor{source: t}, output.bts, blocks)
case strings.HasPrefix(t.Name, "v.") || strings.HasPrefix(t.Name, "mm.") || strings.HasPrefix(t.Name, "s."):
// TODO: assign vision tensors to the gpu if possible
createTensor(tensor{source: t}, output.bts, blocks)
case contains(t.Name, "rope_freqs", "rope_factors_long", "rope_factors_short"):
// these tensors should be repeated per layer
for i, layer := range layers {
createTensor(tensor{
source: t,
target: "blk." + strconv.Itoa(i) + "." + t.Name,
}, layer.bts, i)
}
default:
layerIndex := -1
if fields := strings.FieldsFunc(t.Name, func(r rune) bool { return !unicode.IsNumber(r) }); len(fields) > 0 {
if i, err := strconv.Atoi(fields[0]); err == nil {
layerIndex = i
}
}
if layerIndex >= 0 {
createTensor(tensor{source: t}, layers[layerIndex].bts, layerIndex)
} else {
// load all other tensors on the cpu
createTensor(tensor{source: t}, input.bts, -1)
}
}
}
// map tensor names to tensors for easy lookup later
tensors := make(map[string]*C.struct_ggml_tensor)
for _, c := range ctxs {
for t := C.ggml_get_first_tensor(c); t != nil; t = C.ggml_get_next_tensor(c, t) {
tensors[C.GoString(C.ggml_get_name(t))] = t
}
}
// map devices to backend buffer types so new tensors can be assigned to the correct device
deviceBufferTypes := make(map[C.ggml_backend_dev_t]C.ggml_backend_buffer_type_t)
// create backends and buffer types used for the compute graph scheduler
var schedBackends []C.ggml_backend_t
var schedBufts []C.ggml_backend_buffer_type_t
for _, d := range append(gpus, append(accels, cpus...)...) {
b := backends[d]
bt := C.ggml_backend_get_default_buffer_type(b)
// Always include CPU as a fallback but otherwise, just use the devices where we assigned layers
if !slices.Contains(cpuDeviceBufferType.bts, bt) {
if c, ok := ctxs[bt]; !ok || C.ggml_get_first_tensor(c) == nil {
continue
}
}
deviceBufferTypes[d] = bt
schedBackends = append(schedBackends, b)
schedBufts = append(schedBufts, bt)
if C.ggml_backend_is_cpu(b) {
// set number of threads for cpu backend
C.ggml_backend_cpu_set_n_threads(b, C.int(Threads(params.NumThreads)))
}
}
maxGraphNodes := max(1024, len(meta.Tensors().Items())*8)
sched := C.ggml_backend_sched_new_ext(
(*C.ggml_backend_t)(unsafe.Pointer(&schedBackends[0])),
(*C.ggml_backend_buffer_type_t)(unsafe.Pointer(&schedBufts[0])),
C.int(len(schedBackends)),
C.size_t(maxGraphNodes),
C._Bool(false),
C._Bool(true),
C._Bool(params.AllocMemory),
)
// allocate buffers for each context
bbs := make(map[*C.struct_ggml_context]C.ggml_backend_buffer_t, len(ctxs))
for bt, c := range ctxs {
if C.ggml_get_first_tensor(c) == nil {
continue
}
b := C.ggml_backend_alloc_ctx_tensors_from_buft(c, bt)
if b == nil {
for _, b := range bbs {
C.ggml_backend_buffer_free(b)
}
for _, ctx := range ctxs {
C.ggml_free(ctx)
}
panic(ml.ErrNoMem{BackendMemory: requiredMemory})
}
C.ggml_backend_buffer_set_usage(b, C.GGML_BACKEND_BUFFER_USAGE_WEIGHTS)
bbs[c] = b
}
for bs := range maps.Values(bbs) {
logutil.Trace("model weights", "buffer", C.GoString(C.ggml_backend_buffer_name(bs)),
"size", format.HumanBytes2(uint64(C.ggml_backend_buffer_get_size(bs))))
}
return &Backend{
modelPath: modelPath,
allocMemory: params.AllocMemory,
flashAttention: params.FlashAttention,
meta: meta,
tensorLoadTargets: targets,
tensors: tensors,
sched: sched,
schedBackends: schedBackends,
schedBufts: schedBufts,
input: deviceBufferTypes[input.d],
output: output.d,
layers: func() map[int]layerDevice {
m := make(map[int]layerDevice)
for i, layer := range layers {
m[i] = layerDevice{
d: layer.d,
bt: deviceBufferTypes[layer.d],
}
}
return m
}(),
requiredMemory: &requiredMemory,
btDeviceMemory: btDeviceMemory,
maxGraphNodes: maxGraphNodes,
weightBuffers: bbs,
}, nil
}
func init() {
ml.RegisterBackend("ggml", New)
}
func (b *Backend) Close() {
if b == nil {
return
}
for ctx, b := range b.weightBuffers {
C.ggml_backend_buffer_free(b)
C.ggml_free(ctx)
}
C.ggml_backend_sched_free(b.sched)
}
func (b *Backend) Load(ctx context.Context, progress func(float32)) error {
if !b.allocMemory {
return errors.New("cannot load model without memory allocation")
}
// Mimic llama runner logs summarizing layers and memory
gpuLayers := 0
for layer := range maps.Values(b.layers) {
switch C.ggml_backend_dev_type(layer.d) {
case C.GGML_BACKEND_DEVICE_TYPE_GPU,
C.GGML_BACKEND_DEVICE_TYPE_IGPU:
gpuLayers++
}
}
slog.Info(fmt.Sprintf("offloading %d repeating layers to GPU", gpuLayers))
switch C.ggml_backend_dev_type(b.output) {
case C.GGML_BACKEND_DEVICE_TYPE_CPU:
slog.Info("offloading output layer to CPU")
case C.GGML_BACKEND_DEVICE_TYPE_GPU,
C.GGML_BACKEND_DEVICE_TYPE_IGPU:
slog.Info("offloading output layer to GPU")
gpuLayers++
case C.GGML_BACKEND_DEVICE_TYPE_ACCEL:
slog.Info("offloading output layer to ACCEL")
}
slog.Info(fmt.Sprintf("offloaded %d/%d layers to GPU", gpuLayers, len(b.layers)+1))
var doneBytes atomic.Uint64
totalBytes := uint64(b.meta.Length) - b.meta.Tensors().Offset
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(runtime.GOMAXPROCS(0))
for _, t := range b.meta.Tensors().Items() {
g.Go(func() error {
tts := make([]*C.struct_ggml_tensor, max(1, len(b.tensorLoadTargets[t.Name])))
for i := range tts {
target := b.tensorLoadTargets[t.Name][i]
if target == "" {
target = t.Name
}
tt, ok := b.tensors[target]
if !ok {
return fmt.Errorf("unassigned tensor: %s", t.Name)
}
tts[i] = tt
}
// Create a new FD for each goroutine so that each FD is read sequentially, rather than
// seeking around within an FD shared between all goroutines.
file, err := os.Open(b.modelPath)
if err != nil {
slog.Warn("file open error", "file", b.modelPath, "error", err)
return err
}
defer file.Close()
sr := io.NewSectionReader(file, int64(b.meta.Tensors().Offset+t.Offset), int64(t.Size()))
if t.Kind == 4 && tts[0]._type == 39 {
// source is mxfp4, target is ggml mxfp4
const BS = 17 // MXFP4 block size
bts := make([]byte, 8*BS*format.KibiByte) // ~128k block aligned
var s uint64
var tmp [16]byte
for s < t.Size() {
// Stop if either the parent context has been canceled or if any of the other tensors returned an error
if err := ctx.Err(); err != nil {
return err
}
n, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])
if err != nil {
slog.Warn("file read error", "file", b.modelPath, "error", err)
return err
}
for j := range n / BS {
for i := 1; i < 9; i++ {
// transform a1b2c3 ... x7y8z9 -> 71xa82yb93zc
a, b := bts[j*BS+i], bts[j*BS+i+8]
tmp[2*(i-1)] = (a & 0x0F) | (b << 4)
tmp[2*(i-1)+1] = (a >> 4) | (b & 0xF0)
}
copy(bts[j*BS+1:j*BS+17], tmp[:])
}
for _, tt := range tts {
C.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))
}
s += uint64(n)
if progress != nil {
done := doneBytes.Add(uint64(n))
progress(float32(done) / float32(totalBytes))
}
}
return nil
} else if strings.HasSuffix(t.Name, "_exps.bias") && t.Kind == 30 && tts[0]._type == 0 {
// source is bf16, target is ggml fp32
// data is bf16 but we need to convert to fp32
bts := make([]byte, 128*format.KibiByte)
var e uint64
for e < t.Elements() {
// Stop if either the parent context has been canceled or if any of the other tensors returned an error
if err := ctx.Err(); err != nil {
return err
}
n, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Elements()-e)*2)])
if err != nil {
slog.Warn("file read error", "file", b.modelPath, "error", err)
return err
}
fp32 := ConvertToF32(bts, uint32(fsggml.TensorTypeBF16), uint64(n/2))
for _, tt := range tts {
C.ggml_backend_tensor_set(tt, unsafe.Pointer(&fp32[0]), C.size_t(e*4), C.size_t(n*2))
}
e += uint64(n / 2)
if progress != nil {
done := doneBytes.Add(uint64(n))
progress(float32(done) / float32(totalBytes))
}
}
return nil
}
bts := make([]byte, 128*format.KibiByte)
var s uint64
for s < t.Size() {
// Stop if either the parent context has been canceled or if any of the other tensors returned an error
if err := ctx.Err(); err != nil {
return err
}
n, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])
if err != nil {
slog.Warn("file read error", "file", b.modelPath, "error", err)
return err
}
for _, tt := range tts {
C.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))
}
s += uint64(n)
if progress != nil {
done := doneBytes.Add(uint64(n))
progress(float32(done) / float32(totalBytes))
}
}
return nil
})
}
// Cleanup any backend state from devices that we didn't end up using
nextDevice:
for _, d := range append(gpus, append(accels, cpus...)...) {
for _, backend := range b.schedBackends {
if d == C.ggml_backend_get_device(backend) {
continue nextDevice
}
}
C.ggml_backend_dev_reset(d)
}
if err := g.Wait(); err != nil {
return err
}
return nil
}
func (b *Backend) BackendMemory() ml.BackendMemory {
return *b.requiredMemory
}
func (b *Backend) Config() fs.Config {
return b.meta.KV()
}
func (b *Backend) Get(name string) ml.Tensor {
if t, ok := b.tensors[name]; ok {
return &Tensor{b: b, t: t}
}
return nil
}
func (b *Backend) NewContext() ml.Context {
return b.NewContextSize(b.maxGraphNodes)
}
func (b *Backend) NewContextSize(n int) ml.Context {
if n > b.maxGraphNodes {
panic(fmt.Errorf("requested number of graph nodes (%v) for new context exceeds maximum (%v)", n, b.maxGraphNodes))
}
var allocatedBuffers []C.ggml_backend_buffer_t
return &Context{
b: b,
maxGraphNodes: n,
ctx: C.ggml_init(C.struct_ggml_init_params{
mem_size: C.size_t(n)*C.ggml_tensor_overhead() + C.ggml_graph_overhead_custom(C.size_t(n), false),
no_alloc: true,
}),
allocatedBuffers: &allocatedBuffers,
layer: -1,
}
}
func (b *Backend) CacheConfig() ml.CacheConfig {
if b.flashAttention == ml.FlashAttentionEnabled {
return ml.CacheConfig{CachePadding: 256, MaskDType: ml.DTypeF16}
} else {
return ml.CacheConfig{CachePadding: 256, PermutedV: true}
}
}
func (b *Backend) BackendDevices() []ml.DeviceInfo {
deviceInfos := []ml.DeviceInfo{}
for _, dev := range gpus {
// If we have a model loaded, and it's only loaded on a subset of the devices
// skip idle/unused devices to avoid initializing them and causing VRAM allocations
if b.allocMemory {
idleDev := true
for _, backend := range b.schedBackends {
if dev == C.ggml_backend_get_device(backend) {
idleDev = false
break
}
}
if idleDev {
slog.Debug("skipping unused backend device", "description", C.GoString(C.ggml_backend_dev_description(dev)))
continue
}
}
info := ml.DeviceInfo{}
props := C.struct_ggml_backend_dev_props{}
C.ggml_backend_dev_get_props(dev, &props)
info.Name = C.GoString(props.name)
info.Description = C.GoString(props.description)
info.ID = C.GoString(props.id)
info.Library = C.GoString(props.library)
info.ComputeMajor = (int)(props.compute_major)
info.ComputeMinor = (int)(props.compute_minor)
info.DriverMajor = (int)(props.driver_major)
info.DriverMinor = (int)(props.driver_minor)
info.Integrated = props.integrated != 0
if props.library != nil {
info.Library = C.GoString(props.library)
}
if props.device_id != nil {
info.PCIID = C.GoString(props.device_id)
}
info.LibraryPath = ggml.LibPaths()
C.ggml_backend_dev_memory(dev, &props.memory_free, &props.memory_total)
info.TotalMemory = (uint64)(props.memory_total)
info.FreeMemory = (uint64)(props.memory_free)
deviceInfos = append(deviceInfos, info)
}
return deviceInfos
}
type Context struct {
b *Backend
ctx *C.struct_ggml_context
graph *C.struct_ggml_cgraph
// batchSize is a hint to optimize processing
batchSize int
// buft is the buffer type used for new tensors
buft C.ggml_backend_buffer_type_t
// allocatedBuffers are buffers for tensors that we have allocated in this context
// so that we can free them when we close the context
allocatedBuffers *[]C.ggml_backend_buffer_t
// maxGraphNodes is the maximum allowed number of graph nodes in this context
maxGraphNodes int
// layer is the graph layer that this context is allocating for - assumed to be cache
layer int
}
func (c *Context) Input() ml.Context {
if c.b.input != nil {
return &Context{
b: c.b,
ctx: c.ctx,
buft: c.b.input,
allocatedBuffers: c.allocatedBuffers,
maxGraphNodes: c.maxGraphNodes,
layer: -1,
}
}
return c
}
func (c *Context) Layer(i int) ml.Context {
if layer, ok := c.b.layers[i]; ok {
return &Context{
b: c.b,
ctx: c.ctx,
buft: layer.bt,
allocatedBuffers: c.allocatedBuffers,
maxGraphNodes: c.maxGraphNodes,
layer: i,
}
}
return c
}
func (c *Context) Forward(tensors ...ml.Tensor) ml.Context {
if c.graph == nil {
c.graph = C.ggml_new_graph_custom(c.ctx, C.size_t(c.maxGraphNodes), false)
}
for _, tensor := range tensors {
C.ggml_build_forward_expand(c.graph, tensor.(*Tensor).t)
}
return c
}
func (c *Context) SetBatchSize(batchSize int) {
c.batchSize = batchSize
}
func (c *Context) Compute(tensors ...ml.Tensor) {
c.ComputeWithNotify(nil, tensors...)
}
func (c *Context) ComputeWithNotify(cb func(), tensors ...ml.Tensor) {
c.b.schedMu.Lock()
defer c.b.schedMu.Unlock()
if cb != nil {
go cb()
}
if c.batchSize > 0 {
C.ggml_backend_sched_set_batch_size(c.b.sched, C.int(c.batchSize))
}
if status := C.ggml_backend_sched_graph_compute_async(c.b.sched, c.graph); status != C.GGML_STATUS_SUCCESS {
panic(fmt.Errorf("error computing ggml graph: %v", status))
}
C.ggml_backend_sched_reset(c.b.sched)
needSync := true
sync := func() {
if needSync {
C.ggml_backend_sched_synchronize(c.b.sched)
needSync = false
}
}
for _, t := range tensors {
if C.ggml_nbytes(t.(*Tensor).t) > 0 {
t.(*Tensor).sync = sync
}
}
}
func (c *Context) Reserve() {
if c.batchSize > 0 {
C.ggml_backend_sched_set_batch_size(c.b.sched, C.int(c.batchSize))
}
reserved := C.ggml_backend_sched_reserve(c.b.sched, c.graph)
slog.Debug("compute graph", "nodes", C.ggml_graph_n_nodes(c.graph), "splits", C.ggml_backend_sched_get_n_splits(c.b.sched))
// Reserve may get called multiple times for different graphs - we just want the last run, which will contain the max allocations
for _, bt := range c.b.schedBufts {
c.b.btDeviceMemory[bt].Graph = 0
}
for i := range c.b.schedBackends {
bufferSize := C.ggml_backend_sched_get_attempted_buffer_size(c.b.sched, c.b.schedBackends[i])
c.b.btDeviceMemory[c.b.schedBufts[i]].Graph += uint64(bufferSize)
logutil.Trace("compute graph", "backend", C.GoString(C.ggml_backend_name(c.b.schedBackends[i])),
"buffer_type", C.GoString(C.ggml_backend_buft_name(c.b.schedBufts[i])), "size", format.HumanBytes2(uint64(bufferSize)))
}
if !reserved {
panic(ml.ErrNoMem{BackendMemory: *c.b.requiredMemory})
}
}
func (c *Context) MaxGraphNodes() int {
return c.maxGraphNodes
}
func shapeToGGML(shape []int) *C.int64_t {
sh := make([]C.int64_t, len(shape))
for i, s := range shape {
sh[i] = C.int64_t(s)
}
return &sh[0]
}
func pad(length, pad C.size_t) C.size_t {
return ((length + pad - 1) / pad) * pad
}
func (c *Context) newTensor(dtype ml.DType, shape []int) *Tensor {
if c.buft == nil {
panic("set Input or Layer before creating tensors")
}
cdtype := ggmlDType(dtype)
if len(shape) < 1 || shape[0] == 0 {
var shape C.int64_t = 0
return &Tensor{b: c.b, t: C.ggml_new_tensor(c.ctx, cdtype, 1, &shape)}
} else if len(shape) > 4 {
panic("unsupported number of dimensions")
}
for _, dim := range shape {
if dim < 1 {
panic("invalid shape")
}
}
t := C.ggml_new_tensor(c.ctx, cdtype, C.int(len(shape)), shapeToGGML(shape))
size := pad(C.ggml_backend_buft_get_alloc_size(c.buft, t), C.ggml_backend_buft_get_alignment(c.buft))
b := C.ggml_backend_buft_alloc_buffer(c.buft, size)
if c.layer >= 0 {
c.b.btDeviceMemory[c.buft].Cache[c.layer] += uint64(size)
}
if b == nil {
panic(ml.ErrNoMem{BackendMemory: *c.b.requiredMemory})
}
*c.allocatedBuffers = append(*c.allocatedBuffers, b)
C.ggml_backend_tensor_alloc(b, t, C.ggml_backend_buffer_get_base(b))
return &Tensor{b: c.b, t: t}
}
func (c *Context) Empty(dtype ml.DType, shape ...int) ml.Tensor {
return c.newTensor(dtype, shape)
}
func (c *Context) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
t := c.newTensor(dtype, shape)
if c.b.allocMemory {
C.ggml_set_zero(t.t)
}
return t
}
func checkShape[S ~[]E, E any](s S, shape ...int) {
n := len(s)
if n == 0 {
return
}
for _, v := range shape {
n /= v
}
if n != 1 {
panic(fmt.Errorf("invalid shape: %v", shape))
}
}
func (c Context) FromBytes(dtype ml.DType, s []uint8, shape ...int) ml.Tensor {
// Unchecked to handle quantized types
t := c.newTensor(dtype, shape)
if c.b.allocMemory {
t.FromBytes(s)
}
return t
}
func (c *Context) FromFloats(s []float32, shape ...int) ml.Tensor {
checkShape(s, shape...)
t := c.newTensor(ml.DTypeF32, shape)
if c.b.allocMemory {
t.FromFloats(s)
}
return t
}
func (c *Context) FromInts(s []int32, shape ...int) ml.Tensor {
checkShape(s, shape...)
t := c.newTensor(ml.DTypeI32, shape)
if c.b.allocMemory {
t.FromInts(s)
}
return t
}
func (c Context) Arange(start, stop, step float32, dtype ml.DType) ml.Tensor {
switch dtype {
case ml.DTypeF32:
// ggml_arange creates a float32 tensor
return &Tensor{
b: c.b,
t: C.ggml_arange(c.ctx, C.float(start), C.float(stop), C.float(step)),
}
case ml.DTypeI32:
// ggml_cast does not support float32 to int32 conversion
arange := make([]int32, 0, int((stop-start)/step))
for i := start; i < stop; i += step {
arange = append(arange, int32(i))
}
return c.Input().FromInts(arange, len(arange))
default:
panic("unsupported dtype for arange")
}
}
func (c *Context) Close() {
if c != nil {
for _, b := range *c.allocatedBuffers {
C.ggml_backend_buffer_free(b)
}
*c.allocatedBuffers = nil
C.ggml_free(c.ctx)
}
}
type Tensor struct {
b *Backend
t *C.struct_ggml_tensor
sync func()
}
func (t *Tensor) LogValue() slog.Value {
return slog.GroupValue(
slog.String("name", C.GoString(C.ggml_get_name(t.t))),
slog.String("type", C.GoString(C.ggml_type_name(t.t._type))),
slog.Any("shape", t.Shape()),
)
}
func (t *Tensor) Dim(n int) int {
return int(t.t.ne[n])
}
func (t *Tensor) Stride(n int) int {
return int(t.t.nb[n])
}
func (t *Tensor) Shape() []int {
shape := make([]int, C.ggml_n_dims(t.t))
for i := range shape {
shape[i] = t.Dim(i)
}
return shape
}
func (t *Tensor) Bytes() (data []byte) {
if t.sync != nil {
data = make([]byte, C.ggml_nbytes(t.t))
t.sync()
C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
}
return
}
func (t *Tensor) Floats() (data []float32) {
if t.sync != nil {
data = make([]float32, C.ggml_nelements(t.t))
t.sync()
C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
}
return
}
func tensorSet[S ~[]E, E byte | float32 | int32](t *Tensor, s S) {
if len(s) == 0 {
return
}
if int(C.ggml_nbytes(t.t)) != len(s)*binary.Size(s[0]) {
panic("data size does not match tensor size")
}
C.ggml_backend_tensor_set(t.t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.t))
}
func (t *Tensor) FromBytes(s []byte) {
tensorSet(t, s)
}
func (t *Tensor) FromFloats(s []float32) {
tensorSet(t, s)
}
func (t *Tensor) FromInts(s []int32) {
tensorSet(t, s)
}
func (t *Tensor) DType() ml.DType {
switch t.t._type {
case C.GGML_TYPE_F32:
return ml.DTypeF32
case C.GGML_TYPE_F16:
return ml.DTypeF16
case C.GGML_TYPE_Q8_0:
return ml.DTypeQ80
case C.GGML_TYPE_Q4_0:
return ml.DTypeQ40
case C.GGML_TYPE_I32:
return ml.DTypeI32
case C.GGML_TYPE_MXFP4:
return ml.DTypeMXFP4
default:
return ml.DTypeOther
}
}
func ggmlDType(dtype ml.DType) uint32 {
switch dtype {
case ml.DTypeF32:
return C.GGML_TYPE_F32
case ml.DTypeF16:
return C.GGML_TYPE_F16
case ml.DTypeQ80:
return C.GGML_TYPE_Q8_0
case ml.DTypeQ40:
return C.GGML_TYPE_Q4_0
case ml.DTypeI32:
return C.GGML_TYPE_I32
case ml.DTypeMXFP4:
return C.GGML_TYPE_MXFP4
default:
panic("unsupported dtype")
}
}
func (t *Tensor) Cast(ctx ml.Context, dtype ml.DType) ml.Tensor {
return &Tensor{
b: t.b,
t: C.ggml_cast(ctx.(*Context).ctx, t.t, ggmlDType(dtype)),
}
}
func (t *Tensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
return &Tensor{
b: t.b,
t: C.ggml_add(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
}
}
func (t *Tensor) Sub(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
return &Tensor{
b: t.b,
t: C.ggml_sub(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
}
}
func (t *Tensor) Repeat(ctx ml.Context, dim, n int) ml.Tensor {
if dim < 0 || dim >= C.GGML_MAX_DIMS {
panic("invalid dimension")
}
shape := make([]C.int64_t, C.GGML_MAX_DIMS)
for i := range C.GGML_MAX_DIMS {
if i == dim {
shape[i] = C.int64_t(t.Dim(i) * n)
} else {
shape[i] = C.int64_t(t.Dim(i))
}
}
tmpl := C.ggml_new_tensor(ctx.(*Context).ctx, t.t._type, C.int(len(shape)), unsafe.SliceData(shape))
return &Tensor{
b: t.b,
t: C.ggml_repeat(ctx.(*Context).ctx, t.t, tmpl),
}
}
func (t *Tensor) Stack(ctx ml.Context, dim int, s ...ml.Tensor) ml.Tensor {
if len(s) > 0 {
return t.Concat(ctx, s[0].Stack(ctx, dim, s[1:]...), dim)
}
return t
}
func (t *Tensor) Concat(ctx ml.Context, t2 ml.Tensor, dim int) ml.Tensor {
return &Tensor{
b: t.b,
t: C.ggml_concat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.int(dim)),
}
}
func (t *Tensor) Contiguous(ctx ml.Context, shape ...int) ml.Tensor {
if slices.Contains(shape, -1) {
inferShape(t, shape)
}
switch len(shape) {
case 0:
return &Tensor{
b: t.b,
t: C.ggml_cont(ctx.(*Context).ctx, t.t),
}
case 1:
return &Tensor{
b: t.b,
t: C.ggml_cont_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0])),
}
case 2:
return &Tensor{
b: t.b,
t: C.ggml_cont_2d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1])),
}
case 3:
return &Tensor{
b: t.b,
t: C.ggml_cont_3d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1]), C.int64_t(shape[2])),
}
case 4:
return &Tensor{
b: t.b,
t: C.ggml_cont_4d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1]), C.int64_t(shape[2]), C.int64_t(shape[3])),
}
default:
panic("unsupported number of dimensions")
}
}
func (t *Tensor) Mul(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
return &Tensor{
b: t.b,
t: C.ggml_mul(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
}
}
func (t *Tensor) Div(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
return &Tensor{
b: t.b,
t: C.ggml_div(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
}
}
// Mulmat performs matrix multiplication between two tensors.
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | true |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml_darwin_arm64.go | ml/backend/ggml/ggml/src/ggml_darwin_arm64.go | package ggml
// #cgo CPPFLAGS: -DGGML_USE_METAL -DGGML_METAL_EMBED_LIBRARY -DGGML_USE_BLAS
// #cgo LDFLAGS: -framework Foundation
import "C"
import (
_ "github.com/ollama/ollama/ml/backend/ggml/ggml/src/ggml-blas"
_ "github.com/ollama/ollama/ml/backend/ggml/ggml/src/ggml-metal"
)
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml.go | ml/backend/ggml/ggml/src/ggml.go | package ggml
// #cgo CXXFLAGS: -std=c++17
// #cgo CPPFLAGS: -DNDEBUG -DGGML_USE_CPU -DGGML_VERSION=0x0 -DGGML_COMMIT=0x0
// #cgo CPPFLAGS: -I${SRCDIR}/../include -I${SRCDIR}/ggml-cpu
// #cgo windows CFLAGS: -Wno-dll-attribute-on-redeclaration
// #cgo windows LDFLAGS: -lmsvcrt -static -static-libgcc -static-libstdc++
// #include <stdlib.h>
// #include "ggml-backend.h"
// extern void sink(int level, char *text, void *user_data);
// static struct ggml_backend_feature * first_feature(ggml_backend_get_features_t fp, ggml_backend_reg_t reg) { return fp(reg); }
// static struct ggml_backend_feature * next_feature(struct ggml_backend_feature * feature) { return &feature[1]; }
/*
typedef enum { COMPILER_CLANG, COMPILER_GNUC, COMPILER_UNKNOWN } COMPILER;
static COMPILER compiler_name(void) {
#if defined(__clang__)
return COMPILER_CLANG;
#elif defined(__GNUC__)
return COMPILER_GNUC;
#else
return COMPILER_UNKNOWN;
#endif
}
*/
import "C"
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"unsafe"
_ "github.com/ollama/ollama/ml/backend/ggml/ggml/src/ggml-cpu"
)
func init() {
C.ggml_log_set(C.ggml_log_callback(C.sink), nil)
}
//export sink
func sink(level C.int, text *C.char, _ unsafe.Pointer) {
// slog levels zeros INFO and are multiples of 4
if slog.Default().Enabled(context.TODO(), slog.Level(int(level-C.GGML_LOG_LEVEL_INFO)*4)) {
fmt.Fprint(os.Stderr, C.GoString(text))
}
}
var OnceLoad = sync.OnceFunc(func() {
exe, err := os.Executable()
if err != nil {
slog.Warn("failed to get executable path", "error", err)
exe = "."
}
var value string
switch runtime.GOOS {
case "darwin":
value = filepath.Dir(exe)
case "windows":
value = filepath.Join(filepath.Dir(exe), "lib", "ollama")
default:
value = filepath.Join(filepath.Dir(exe), "..", "lib", "ollama")
}
// Avoid potentially loading incompatible GGML libraries
paths, ok := os.LookupEnv("OLLAMA_LIBRARY_PATH")
if !ok {
slog.Debug("OLLAMA_LIBRARY_PATH not set, falling back to default", "search", value)
paths = value
}
libPaths = filepath.SplitList(paths)
visited := make(map[string]struct{}, len(libPaths))
for _, path := range libPaths {
abspath, err := filepath.Abs(path)
if err != nil {
slog.Error("failed to get absolute path", "error", err)
continue
}
if abspath != filepath.Dir(exe) && !strings.Contains(abspath, filepath.FromSlash("lib/ollama")) {
slog.Debug("skipping path which is not part of ollama", "path", abspath)
continue
}
if _, ok := visited[abspath]; !ok {
func() {
slog.Debug("ggml backend load all from path", "path", abspath)
cpath := C.CString(abspath)
defer C.free(unsafe.Pointer(cpath))
C.ggml_backend_load_all_from_path(cpath)
}()
visited[abspath] = struct{}{}
}
}
slog.Info("system", "", system{})
})
var libPaths []string
func LibPaths() []string {
return libPaths
}
type system struct{}
func (system) LogValue() slog.Value {
var attrs []slog.Attr
names := make(map[string]int)
for i := range C.ggml_backend_dev_count() {
r := C.ggml_backend_dev_backend_reg(C.ggml_backend_dev_get(i))
func() {
fName := C.CString("ggml_backend_get_features")
defer C.free(unsafe.Pointer(fName))
if fn := C.ggml_backend_reg_get_proc_address(r, fName); fn != nil {
var features []any
for f := C.first_feature(C.ggml_backend_get_features_t(fn), r); f.name != nil; f = C.next_feature(f) {
features = append(features, C.GoString(f.name), C.GoString(f.value))
}
name := C.GoString(C.ggml_backend_reg_name(r))
attrs = append(attrs, slog.Group(name+"."+strconv.Itoa(names[name]), features...))
names[name] += 1
}
}()
}
switch C.compiler_name() {
case C.COMPILER_CLANG:
attrs = append(attrs, slog.String("compiler", "cgo(clang)"))
case C.COMPILER_GNUC:
attrs = append(attrs, slog.String("compiler", "cgo(gcc)"))
default:
attrs = append(attrs, slog.String("compiler", "cgo(unknown)"))
}
return slog.GroupValue(attrs...)
}
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-metal/metal.go | ml/backend/ggml/ggml/src/ggml-metal/metal.go | //go:build darwin && arm64
package metal
//go:generate sh -c "{ echo // Code generated by 'go generate'. DO NOT EDIT.; sed -e '/__embed_ggml-common.h__/r ../ggml-common.h' -e '/__embed_ggml-common.h__/d' -e '/#include \"ggml-metal-impl.h\"/r ggml-metal-impl.h' -e '/#include \"ggml-metal-impl.h\"/d' ggml-metal.metal; } >ggml-metal-embed.metal"
// #cgo CXXFLAGS: -std=c++17
// #cgo CPPFLAGS: -DGGML_METAL_NDEBUG -DGGML_METAL_EMBED_LIBRARY -DGGML_METAL_HAS_BF16 -I.. -I../../include
// #cgo LDFLAGS: -framework Metal -framework MetalKit
import "C"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-cpu/cpu_debug.go | ml/backend/ggml/ggml/src/ggml-cpu/cpu_debug.go | //go:build debug
package cpu
// #cgo CPPFLAGS: -DOLLAMA_DEBUG
import "C"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-cpu/cpu_amd64.go | ml/backend/ggml/ggml/src/ggml-cpu/cpu_amd64.go | package cpu
import _ "github.com/ollama/ollama/ml/backend/ggml/ggml/src/ggml-cpu/arch/x86"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-cpu/cpu_arm64.go | ml/backend/ggml/ggml/src/ggml-cpu/cpu_arm64.go | package cpu
import _ "github.com/ollama/ollama/ml/backend/ggml/ggml/src/ggml-cpu/arch/arm"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-cpu/cpu.go | ml/backend/ggml/ggml/src/ggml-cpu/cpu.go | package cpu
// #cgo CFLAGS: -O3 -Wno-implicit-function-declaration
// #cgo CXXFLAGS: -std=c++17
// #cgo CPPFLAGS: -I${SRCDIR}/amx -I${SRCDIR}/llamafile -I${SRCDIR}/.. -I${SRCDIR}/../../include
// #cgo CPPFLAGS: -DNDEBUG -DGGML_USE_LLAMAFILE
// #cgo linux CPPFLAGS: -D_GNU_SOURCE
// #cgo darwin,arm64 CPPFLAGS: -DGGML_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
// #cgo darwin,arm64 LDFLAGS: -framework Accelerate
import "C"
import _ "github.com/ollama/ollama/ml/backend/ggml/ggml/src/ggml-cpu/llamafile"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-cpu/llamafile/llamafile.go | ml/backend/ggml/ggml/src/ggml-cpu/llamafile/llamafile.go | package llamafile
// #cgo CXXFLAGS: -std=c++17
// #cgo CPPFLAGS: -I${SRCDIR}/.. -I${SRCDIR}/../.. -I${SRCDIR}/../../../include
import "C"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-cpu/arch/arm/arm.go | ml/backend/ggml/ggml/src/ggml-cpu/arch/arm/arm.go | //go:build arm64
package arm
// #cgo CXXFLAGS: -std=c++17
// #cgo CPPFLAGS: -I${SRCDIR}/../.. -I${SRCDIR}/../../.. -I${SRCDIR}/../../../../include -DHWCAP2_SVE2="2"
import "C"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-cpu/arch/x86/x86.go | ml/backend/ggml/ggml/src/ggml-cpu/arch/x86/x86.go | package x86
// #cgo CXXFLAGS: -std=c++17
// #cgo CPPFLAGS: -I${SRCDIR}/../.. -I${SRCDIR}/../../.. -I${SRCDIR}/../../../../include
import "C"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
ollama/ollama | https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/ml/backend/ggml/ggml/src/ggml-blas/blas.go | ml/backend/ggml/ggml/src/ggml-blas/blas.go | //go:build darwin && arm64
package blas
// #cgo CXXFLAGS: -std=c++11
// #cgo CPPFLAGS: -DGGML_USE_BLAS
// #cgo CPPFLAGS: -I${SRCDIR}/.. -I${SRCDIR}/../../include
// #cgo darwin,arm64 CPPFLAGS: -DGGML_BLAS_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
// #cgo darwin,arm64 LDFLAGS: -framework Accelerate
import "C"
| go | MIT | 626af2d80973270c4d59b8df7153ac47ad67ed7b | 2026-01-07T08:35:43.337630Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.