diff --git a/.gitignore b/.gitignore index e1aafe67..61f2f1ea 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ *.dll *.so *.dylib +cycloid-cli # Test binary, built with `go test -c` *.test @@ -30,4 +31,3 @@ gst # direnv .direnv -cycloid-cli diff --git a/Makefile b/Makefile index 3d3c84ac..77f37020 100644 --- a/Makefile +++ b/Makefile @@ -152,4 +152,3 @@ ci-test: .git/hooks/pre-commit: pre-commit-install - diff --git a/client/client/cost_estimation/cost_estimate_form_responses.go b/client/client/cost_estimation/cost_estimate_form_responses.go index 89441d80..4bd5c002 100644 --- a/client/client/cost_estimation/cost_estimate_form_responses.go +++ b/client/client/cost_estimation/cost_estimate_form_responses.go @@ -414,6 +414,11 @@ type CostEstimateFormBody struct { // Required: true ServiceCatalogRef *string `json:"service_catalog_ref"` + // Is the ID of the new SCS Version used + // Required: true + // Minimum: 1 + ServiceCatalogSourceVersionID *uint32 `json:"service_catalog_source_version_id"` + // use case // Required: true // Max Length: 100 @@ -438,6 +443,10 @@ func (o *CostEstimateFormBody) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := o.validateServiceCatalogSourceVersionID(formats); err != nil { + res = append(res, err) + } + if err := o.validateUseCase(formats); err != nil { res = append(res, err) } @@ -482,6 +491,19 @@ func (o *CostEstimateFormBody) validateServiceCatalogRef(formats strfmt.Registry return nil } +func (o *CostEstimateFormBody) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { + + if err := validate.Required("body"+"."+"service_catalog_source_version_id", "body", o.ServiceCatalogSourceVersionID); err != nil { + return err + } + + if err := validate.MinimumUint("body"+"."+"service_catalog_source_version_id", "body", uint64(*o.ServiceCatalogSourceVersionID), 1, false); err != nil { + return err + } + + return nil +} + func (o *CostEstimateFormBody) validateUseCase(formats strfmt.Registry) error { if err := validate.Required("body"+"."+"use_case", "body", o.UseCase); err != nil { diff --git a/client/client/organization_components/get_component_stack_configuration_parameters.go b/client/client/organization_components/get_component_stack_configuration_parameters.go index 4c7669e4..b0b55abb 100644 --- a/client/client/organization_components/get_component_stack_configuration_parameters.go +++ b/client/client/organization_components/get_component_stack_configuration_parameters.go @@ -14,6 +14,7 @@ import ( "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" ) // NewGetComponentStackConfigurationParams creates a new GetComponentStackConfigurationParams object, @@ -85,6 +86,23 @@ type GetComponentStackConfigurationParams struct { */ ProjectCanonical string + /* ServiceCatalogSourceVersionCommitHash. + + The HASH of the SCS Version + + Format: uint32 + */ + ServiceCatalogSourceVersionCommitHash string + + /* ServiceCatalogSourceVersionID. + + The ID of the SCS Version + + Format: uint32 + Default: 1 + */ + ServiceCatalogSourceVersionID uint32 + /* UseCase. A use case of a stack to be selectd from the stack config @@ -108,7 +126,18 @@ func (o *GetComponentStackConfigurationParams) WithDefaults() *GetComponentStack // // All values with no default are reset to their zero value. func (o *GetComponentStackConfigurationParams) SetDefaults() { - // no default values defined for this parameter + var ( + serviceCatalogSourceVersionIDDefault = uint32(1) + ) + + val := GetComponentStackConfigurationParams{ + ServiceCatalogSourceVersionID: serviceCatalogSourceVersionIDDefault, + } + + val.timeout = o.timeout + val.Context = o.Context + val.HTTPClient = o.HTTPClient + *o = val } // WithTimeout adds the timeout to the get component stack configuration params @@ -188,6 +217,28 @@ func (o *GetComponentStackConfigurationParams) SetProjectCanonical(projectCanoni o.ProjectCanonical = projectCanonical } +// WithServiceCatalogSourceVersionCommitHash adds the serviceCatalogSourceVersionCommitHash to the get component stack configuration params +func (o *GetComponentStackConfigurationParams) WithServiceCatalogSourceVersionCommitHash(serviceCatalogSourceVersionCommitHash string) *GetComponentStackConfigurationParams { + o.SetServiceCatalogSourceVersionCommitHash(serviceCatalogSourceVersionCommitHash) + return o +} + +// SetServiceCatalogSourceVersionCommitHash adds the serviceCatalogSourceVersionCommitHash to the get component stack configuration params +func (o *GetComponentStackConfigurationParams) SetServiceCatalogSourceVersionCommitHash(serviceCatalogSourceVersionCommitHash string) { + o.ServiceCatalogSourceVersionCommitHash = serviceCatalogSourceVersionCommitHash +} + +// WithServiceCatalogSourceVersionID adds the serviceCatalogSourceVersionID to the get component stack configuration params +func (o *GetComponentStackConfigurationParams) WithServiceCatalogSourceVersionID(serviceCatalogSourceVersionID uint32) *GetComponentStackConfigurationParams { + o.SetServiceCatalogSourceVersionID(serviceCatalogSourceVersionID) + return o +} + +// SetServiceCatalogSourceVersionID adds the serviceCatalogSourceVersionId to the get component stack configuration params +func (o *GetComponentStackConfigurationParams) SetServiceCatalogSourceVersionID(serviceCatalogSourceVersionID uint32) { + o.ServiceCatalogSourceVersionID = serviceCatalogSourceVersionID +} + // WithUseCase adds the useCase to the get component stack configuration params func (o *GetComponentStackConfigurationParams) WithUseCase(useCase *string) *GetComponentStackConfigurationParams { o.SetUseCase(useCase) @@ -227,6 +278,26 @@ func (o *GetComponentStackConfigurationParams) WriteToRequest(r runtime.ClientRe return err } + // query param service_catalog_source_version_commit_hash + qrServiceCatalogSourceVersionCommitHash := o.ServiceCatalogSourceVersionCommitHash + qServiceCatalogSourceVersionCommitHash := qrServiceCatalogSourceVersionCommitHash + if qServiceCatalogSourceVersionCommitHash != "" { + + if err := r.SetQueryParam("service_catalog_source_version_commit_hash", qServiceCatalogSourceVersionCommitHash); err != nil { + return err + } + } + + // query param service_catalog_source_version_id + qrServiceCatalogSourceVersionID := o.ServiceCatalogSourceVersionID + qServiceCatalogSourceVersionID := swag.FormatUint32(qrServiceCatalogSourceVersionID) + if qServiceCatalogSourceVersionID != "" { + + if err := r.SetQueryParam("service_catalog_source_version_id", qServiceCatalogSourceVersionID); err != nil { + return err + } + } + if o.UseCase != nil { // query param use_case diff --git a/client/client/organization_forms/interpolate_forms_config_responses.go b/client/client/organization_forms/interpolate_forms_config_responses.go index f2d87e83..9006985b 100644 --- a/client/client/organization_forms/interpolate_forms_config_responses.go +++ b/client/client/organization_forms/interpolate_forms_config_responses.go @@ -510,6 +510,11 @@ type InterpolateFormsConfigBody struct { // Required: true ServiceCatalogRef *string `json:"service_catalog_ref"` + // Is the ID of the new SCS Version used + // Required: true + // Minimum: 1 + ServiceCatalogSourceVersionID *uint32 `json:"service_catalog_source_version_id"` + // use case // Required: true // Max Length: 100 @@ -534,6 +539,10 @@ func (o *InterpolateFormsConfigBody) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := o.validateServiceCatalogSourceVersionID(formats); err != nil { + res = append(res, err) + } + if err := o.validateUseCase(formats); err != nil { res = append(res, err) } @@ -578,6 +587,19 @@ func (o *InterpolateFormsConfigBody) validateServiceCatalogRef(formats strfmt.Re return nil } +func (o *InterpolateFormsConfigBody) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { + + if err := validate.Required("body"+"."+"service_catalog_source_version_id", "body", o.ServiceCatalogSourceVersionID); err != nil { + return err + } + + if err := validate.MinimumUint("body"+"."+"service_catalog_source_version_id", "body", uint64(*o.ServiceCatalogSourceVersionID), 1, false); err != nil { + return err + } + + return nil +} + func (o *InterpolateFormsConfigBody) validateUseCase(formats strfmt.Registry) error { if err := validate.Required("body"+"."+"use_case", "body", o.UseCase); err != nil { diff --git a/client/client/organization_service_catalog_sources/list_service_catalog_source_versions_parameters.go b/client/client/organization_service_catalog_sources/list_service_catalog_source_versions_parameters.go new file mode 100644 index 00000000..f0715f60 --- /dev/null +++ b/client/client/organization_service_catalog_sources/list_service_catalog_source_versions_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organization_service_catalog_sources + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListServiceCatalogSourceVersionsParams creates a new ListServiceCatalogSourceVersionsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewListServiceCatalogSourceVersionsParams() *ListServiceCatalogSourceVersionsParams { + return &ListServiceCatalogSourceVersionsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListServiceCatalogSourceVersionsParamsWithTimeout creates a new ListServiceCatalogSourceVersionsParams object +// with the ability to set a timeout on a request. +func NewListServiceCatalogSourceVersionsParamsWithTimeout(timeout time.Duration) *ListServiceCatalogSourceVersionsParams { + return &ListServiceCatalogSourceVersionsParams{ + timeout: timeout, + } +} + +// NewListServiceCatalogSourceVersionsParamsWithContext creates a new ListServiceCatalogSourceVersionsParams object +// with the ability to set a context for a request. +func NewListServiceCatalogSourceVersionsParamsWithContext(ctx context.Context) *ListServiceCatalogSourceVersionsParams { + return &ListServiceCatalogSourceVersionsParams{ + Context: ctx, + } +} + +// NewListServiceCatalogSourceVersionsParamsWithHTTPClient creates a new ListServiceCatalogSourceVersionsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListServiceCatalogSourceVersionsParamsWithHTTPClient(client *http.Client) *ListServiceCatalogSourceVersionsParams { + return &ListServiceCatalogSourceVersionsParams{ + HTTPClient: client, + } +} + +/* +ListServiceCatalogSourceVersionsParams contains all the parameters to send to the API endpoint + + for the list service catalog source versions operation. + + Typically these are written to a http.Request. +*/ +type ListServiceCatalogSourceVersionsParams struct { + + /* OrganizationCanonical. + + A canonical of an organization. + */ + OrganizationCanonical string + + /* ServiceCatalogSourceCanonical. + + Organization Service Catalog Sources canonical + */ + ServiceCatalogSourceCanonical string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list service catalog source versions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListServiceCatalogSourceVersionsParams) WithDefaults() *ListServiceCatalogSourceVersionsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list service catalog source versions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListServiceCatalogSourceVersionsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) WithTimeout(timeout time.Duration) *ListServiceCatalogSourceVersionsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) WithContext(ctx context.Context) *ListServiceCatalogSourceVersionsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) WithHTTPClient(client *http.Client) *ListServiceCatalogSourceVersionsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrganizationCanonical adds the organizationCanonical to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) WithOrganizationCanonical(organizationCanonical string) *ListServiceCatalogSourceVersionsParams { + o.SetOrganizationCanonical(organizationCanonical) + return o +} + +// SetOrganizationCanonical adds the organizationCanonical to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) SetOrganizationCanonical(organizationCanonical string) { + o.OrganizationCanonical = organizationCanonical +} + +// WithServiceCatalogSourceCanonical adds the serviceCatalogSourceCanonical to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) WithServiceCatalogSourceCanonical(serviceCatalogSourceCanonical string) *ListServiceCatalogSourceVersionsParams { + o.SetServiceCatalogSourceCanonical(serviceCatalogSourceCanonical) + return o +} + +// SetServiceCatalogSourceCanonical adds the serviceCatalogSourceCanonical to the list service catalog source versions params +func (o *ListServiceCatalogSourceVersionsParams) SetServiceCatalogSourceCanonical(serviceCatalogSourceCanonical string) { + o.ServiceCatalogSourceCanonical = serviceCatalogSourceCanonical +} + +// WriteToRequest writes these params to a swagger request +func (o *ListServiceCatalogSourceVersionsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param organization_canonical + if err := r.SetPathParam("organization_canonical", o.OrganizationCanonical); err != nil { + return err + } + + // path param service_catalog_source_canonical + if err := r.SetPathParam("service_catalog_source_canonical", o.ServiceCatalogSourceCanonical); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/client/organization_service_catalog_sources/list_service_catalog_source_versions_responses.go b/client/client/organization_service_catalog_sources/list_service_catalog_source_versions_responses.go new file mode 100644 index 00000000..ec5be468 --- /dev/null +++ b/client/client/organization_service_catalog_sources/list_service_catalog_source_versions_responses.go @@ -0,0 +1,671 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organization_service_catalog_sources + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + stderrors "errors" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "github.com/cycloidio/cycloid-cli/client/models" +) + +// ListServiceCatalogSourceVersionsReader is a Reader for the ListServiceCatalogSourceVersions structure. +type ListServiceCatalogSourceVersionsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListServiceCatalogSourceVersionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (any, error) { + switch response.Code() { + case 200: + result := NewListServiceCatalogSourceVersionsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 403: + result := NewListServiceCatalogSourceVersionsForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewListServiceCatalogSourceVersionsNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 411: + result := NewListServiceCatalogSourceVersionsLengthRequired() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewListServiceCatalogSourceVersionsUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + result := NewListServiceCatalogSourceVersionsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewListServiceCatalogSourceVersionsOK creates a ListServiceCatalogSourceVersionsOK with default headers values +func NewListServiceCatalogSourceVersionsOK() *ListServiceCatalogSourceVersionsOK { + return &ListServiceCatalogSourceVersionsOK{} +} + +/* +ListServiceCatalogSourceVersionsOK describes a response with status code 200, with default header values. + +List of the Service catalog source version +*/ +type ListServiceCatalogSourceVersionsOK struct { + Payload *ListServiceCatalogSourceVersionsOKBody +} + +// IsSuccess returns true when this list service catalog source versions o k response has a 2xx status code +func (o *ListServiceCatalogSourceVersionsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list service catalog source versions o k response has a 3xx status code +func (o *ListServiceCatalogSourceVersionsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list service catalog source versions o k response has a 4xx status code +func (o *ListServiceCatalogSourceVersionsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list service catalog source versions o k response has a 5xx status code +func (o *ListServiceCatalogSourceVersionsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list service catalog source versions o k response a status code equal to that given +func (o *ListServiceCatalogSourceVersionsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list service catalog source versions o k response +func (o *ListServiceCatalogSourceVersionsOK) Code() int { + return 200 +} + +func (o *ListServiceCatalogSourceVersionsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsOK %s", 200, payload) +} + +func (o *ListServiceCatalogSourceVersionsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsOK %s", 200, payload) +} + +func (o *ListServiceCatalogSourceVersionsOK) GetPayload() *ListServiceCatalogSourceVersionsOKBody { + return o.Payload +} + +func (o *ListServiceCatalogSourceVersionsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(ListServiceCatalogSourceVersionsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewListServiceCatalogSourceVersionsForbidden creates a ListServiceCatalogSourceVersionsForbidden with default headers values +func NewListServiceCatalogSourceVersionsForbidden() *ListServiceCatalogSourceVersionsForbidden { + return &ListServiceCatalogSourceVersionsForbidden{} +} + +/* +ListServiceCatalogSourceVersionsForbidden describes a response with status code 403, with default header values. + +The authenticated user cannot perform the operation because, it doesn't have permissions for such operation. +*/ +type ListServiceCatalogSourceVersionsForbidden struct { + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this list service catalog source versions forbidden response has a 2xx status code +func (o *ListServiceCatalogSourceVersionsForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list service catalog source versions forbidden response has a 3xx status code +func (o *ListServiceCatalogSourceVersionsForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list service catalog source versions forbidden response has a 4xx status code +func (o *ListServiceCatalogSourceVersionsForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this list service catalog source versions forbidden response has a 5xx status code +func (o *ListServiceCatalogSourceVersionsForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this list service catalog source versions forbidden response a status code equal to that given +func (o *ListServiceCatalogSourceVersionsForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the list service catalog source versions forbidden response +func (o *ListServiceCatalogSourceVersionsForbidden) Code() int { + return 403 +} + +func (o *ListServiceCatalogSourceVersionsForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsForbidden %s", 403, payload) +} + +func (o *ListServiceCatalogSourceVersionsForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsForbidden %s", 403, payload) +} + +func (o *ListServiceCatalogSourceVersionsForbidden) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *ListServiceCatalogSourceVersionsForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewListServiceCatalogSourceVersionsNotFound creates a ListServiceCatalogSourceVersionsNotFound with default headers values +func NewListServiceCatalogSourceVersionsNotFound() *ListServiceCatalogSourceVersionsNotFound { + return &ListServiceCatalogSourceVersionsNotFound{} +} + +/* +ListServiceCatalogSourceVersionsNotFound describes a response with status code 404, with default header values. + +The response sent when any of the entities present in the path is not found. +*/ +type ListServiceCatalogSourceVersionsNotFound struct { + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this list service catalog source versions not found response has a 2xx status code +func (o *ListServiceCatalogSourceVersionsNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list service catalog source versions not found response has a 3xx status code +func (o *ListServiceCatalogSourceVersionsNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list service catalog source versions not found response has a 4xx status code +func (o *ListServiceCatalogSourceVersionsNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this list service catalog source versions not found response has a 5xx status code +func (o *ListServiceCatalogSourceVersionsNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this list service catalog source versions not found response a status code equal to that given +func (o *ListServiceCatalogSourceVersionsNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the list service catalog source versions not found response +func (o *ListServiceCatalogSourceVersionsNotFound) Code() int { + return 404 +} + +func (o *ListServiceCatalogSourceVersionsNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsNotFound %s", 404, payload) +} + +func (o *ListServiceCatalogSourceVersionsNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsNotFound %s", 404, payload) +} + +func (o *ListServiceCatalogSourceVersionsNotFound) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *ListServiceCatalogSourceVersionsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewListServiceCatalogSourceVersionsLengthRequired creates a ListServiceCatalogSourceVersionsLengthRequired with default headers values +func NewListServiceCatalogSourceVersionsLengthRequired() *ListServiceCatalogSourceVersionsLengthRequired { + return &ListServiceCatalogSourceVersionsLengthRequired{} +} + +/* +ListServiceCatalogSourceVersionsLengthRequired describes a response with status code 411, with default header values. + +The request has a body but it doesn't have a Content-Length header. +*/ +type ListServiceCatalogSourceVersionsLengthRequired struct { +} + +// IsSuccess returns true when this list service catalog source versions length required response has a 2xx status code +func (o *ListServiceCatalogSourceVersionsLengthRequired) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list service catalog source versions length required response has a 3xx status code +func (o *ListServiceCatalogSourceVersionsLengthRequired) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list service catalog source versions length required response has a 4xx status code +func (o *ListServiceCatalogSourceVersionsLengthRequired) IsClientError() bool { + return true +} + +// IsServerError returns true when this list service catalog source versions length required response has a 5xx status code +func (o *ListServiceCatalogSourceVersionsLengthRequired) IsServerError() bool { + return false +} + +// IsCode returns true when this list service catalog source versions length required response a status code equal to that given +func (o *ListServiceCatalogSourceVersionsLengthRequired) IsCode(code int) bool { + return code == 411 +} + +// Code gets the status code for the list service catalog source versions length required response +func (o *ListServiceCatalogSourceVersionsLengthRequired) Code() int { + return 411 +} + +func (o *ListServiceCatalogSourceVersionsLengthRequired) Error() string { + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsLengthRequired", 411) +} + +func (o *ListServiceCatalogSourceVersionsLengthRequired) String() string { + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsLengthRequired", 411) +} + +func (o *ListServiceCatalogSourceVersionsLengthRequired) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewListServiceCatalogSourceVersionsUnprocessableEntity creates a ListServiceCatalogSourceVersionsUnprocessableEntity with default headers values +func NewListServiceCatalogSourceVersionsUnprocessableEntity() *ListServiceCatalogSourceVersionsUnprocessableEntity { + return &ListServiceCatalogSourceVersionsUnprocessableEntity{} +} + +/* +ListServiceCatalogSourceVersionsUnprocessableEntity describes a response with status code 422, with default header values. + +All the custom errors that are generated from the Cycloid API +*/ +type ListServiceCatalogSourceVersionsUnprocessableEntity struct { + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this list service catalog source versions unprocessable entity response has a 2xx status code +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list service catalog source versions unprocessable entity response has a 3xx status code +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list service catalog source versions unprocessable entity response has a 4xx status code +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this list service catalog source versions unprocessable entity response has a 5xx status code +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this list service catalog source versions unprocessable entity response a status code equal to that given +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the list service catalog source versions unprocessable entity response +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) Code() int { + return 422 +} + +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsUnprocessableEntity %s", 422, payload) +} + +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersionsUnprocessableEntity %s", 422, payload) +} + +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *ListServiceCatalogSourceVersionsUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewListServiceCatalogSourceVersionsDefault creates a ListServiceCatalogSourceVersionsDefault with default headers values +func NewListServiceCatalogSourceVersionsDefault(code int) *ListServiceCatalogSourceVersionsDefault { + return &ListServiceCatalogSourceVersionsDefault{ + _statusCode: code, + } +} + +/* +ListServiceCatalogSourceVersionsDefault describes a response with status code -1, with default header values. + +The response sent when an unexpected error happened, as known as an internal server error. +*/ +type ListServiceCatalogSourceVersionsDefault struct { + _statusCode int + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this list service catalog source versions default response has a 2xx status code +func (o *ListServiceCatalogSourceVersionsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list service catalog source versions default response has a 3xx status code +func (o *ListServiceCatalogSourceVersionsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list service catalog source versions default response has a 4xx status code +func (o *ListServiceCatalogSourceVersionsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list service catalog source versions default response has a 5xx status code +func (o *ListServiceCatalogSourceVersionsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list service catalog source versions default response a status code equal to that given +func (o *ListServiceCatalogSourceVersionsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list service catalog source versions default response +func (o *ListServiceCatalogSourceVersionsDefault) Code() int { + return o._statusCode +} + +func (o *ListServiceCatalogSourceVersionsDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersions default %s", o._statusCode, payload) +} + +func (o *ListServiceCatalogSourceVersionsDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions][%d] listServiceCatalogSourceVersions default %s", o._statusCode, payload) +} + +func (o *ListServiceCatalogSourceVersionsDefault) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *ListServiceCatalogSourceVersionsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +/* +ListServiceCatalogSourceVersionsOKBody list service catalog source versions o k body +swagger:model ListServiceCatalogSourceVersionsOKBody +*/ +type ListServiceCatalogSourceVersionsOKBody struct { + + // data + // Required: true + Data []*models.ServiceCatalogSourceVersion `json:"data"` +} + +// Validate validates this list service catalog source versions o k body +func (o *ListServiceCatalogSourceVersionsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ListServiceCatalogSourceVersionsOKBody) validateData(formats strfmt.Registry) error { + + if err := validate.Required("listServiceCatalogSourceVersionsOK"+"."+"data", "body", o.Data); err != nil { + return err + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("listServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("listServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// ContextValidate validate this list service catalog source versions o k body based on the context it is used +func (o *ListServiceCatalogSourceVersionsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ListServiceCatalogSourceVersionsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("listServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("listServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ListServiceCatalogSourceVersionsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ListServiceCatalogSourceVersionsOKBody) UnmarshalBinary(b []byte) error { + var res ListServiceCatalogSourceVersionsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/client/client/organization_service_catalog_sources/organization_service_catalog_sources_client.go b/client/client/organization_service_catalog_sources/organization_service_catalog_sources_client.go index b9d71954..46f3b036 100644 --- a/client/client/organization_service_catalog_sources/organization_service_catalog_sources_client.go +++ b/client/client/organization_service_catalog_sources/organization_service_catalog_sources_client.go @@ -111,8 +111,12 @@ type ClientService interface { GetServiceCatalogSources(params *GetServiceCatalogSourcesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetServiceCatalogSourcesOK, error) + ListServiceCatalogSourceVersions(params *ListServiceCatalogSourceVersionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListServiceCatalogSourceVersionsOK, error) + RefreshServiceCatalogSource(params *RefreshServiceCatalogSourceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RefreshServiceCatalogSourceOK, error) + RefreshServiceCatalogSourceVersions(params *RefreshServiceCatalogSourceVersionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RefreshServiceCatalogSourceVersionsOK, error) + UpdateServiceCatalogSource(params *UpdateServiceCatalogSourceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateServiceCatalogSourceOK, error) ValidateServiceCatalogSource(params *ValidateServiceCatalogSourceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ValidateServiceCatalogSourceNoContent, error) @@ -292,6 +296,49 @@ func (a *Client) GetServiceCatalogSources(params *GetServiceCatalogSourcesParams return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +ListServiceCatalogSourceVersions List Service catalog source versions +*/ +func (a *Client) ListServiceCatalogSourceVersions(params *ListServiceCatalogSourceVersionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListServiceCatalogSourceVersionsOK, error) { + // NOTE: parameters are not validated before sending + if params == nil { + params = NewListServiceCatalogSourceVersionsParams() + } + op := &runtime.ClientOperation{ + ID: "listServiceCatalogSourceVersions", + Method: "GET", + PathPattern: "/organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/vnd.cycloid.io.v1+json", "application/x-www-form-urlencoded"}, + Schemes: []string{"https"}, + Params: params, + Reader: &ListServiceCatalogSourceVersionsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + + // only one success response has to be checked + success, ok := result.(*ListServiceCatalogSourceVersionsOK) + if ok { + return success, nil + } + + // unexpected success response. + // + // a default response is provided: fill this and return an error + unexpectedSuccess := result.(*ListServiceCatalogSourceVersionsDefault) + + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* RefreshServiceCatalogSource Refresh a Service catalog source */ @@ -335,6 +382,49 @@ func (a *Client) RefreshServiceCatalogSource(params *RefreshServiceCatalogSource return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +RefreshServiceCatalogSourceVersions List Service catalog source versions +*/ +func (a *Client) RefreshServiceCatalogSourceVersions(params *RefreshServiceCatalogSourceVersionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RefreshServiceCatalogSourceVersionsOK, error) { + // NOTE: parameters are not validated before sending + if params == nil { + params = NewRefreshServiceCatalogSourceVersionsParams() + } + op := &runtime.ClientOperation{ + ID: "refreshServiceCatalogSourceVersions", + Method: "GET", + PathPattern: "/organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/vnd.cycloid.io.v1+json", "application/x-www-form-urlencoded"}, + Schemes: []string{"https"}, + Params: params, + Reader: &RefreshServiceCatalogSourceVersionsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + + // only one success response has to be checked + success, ok := result.(*RefreshServiceCatalogSourceVersionsOK) + if ok { + return success, nil + } + + // unexpected success response. + // + // a default response is provided: fill this and return an error + unexpectedSuccess := result.(*RefreshServiceCatalogSourceVersionsDefault) + + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* UpdateServiceCatalogSource Update a Service catalog source */ diff --git a/client/client/organization_service_catalog_sources/refresh_service_catalog_source_versions_parameters.go b/client/client/organization_service_catalog_sources/refresh_service_catalog_source_versions_parameters.go new file mode 100644 index 00000000..7ac677da --- /dev/null +++ b/client/client/organization_service_catalog_sources/refresh_service_catalog_source_versions_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organization_service_catalog_sources + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewRefreshServiceCatalogSourceVersionsParams creates a new RefreshServiceCatalogSourceVersionsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRefreshServiceCatalogSourceVersionsParams() *RefreshServiceCatalogSourceVersionsParams { + return &RefreshServiceCatalogSourceVersionsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRefreshServiceCatalogSourceVersionsParamsWithTimeout creates a new RefreshServiceCatalogSourceVersionsParams object +// with the ability to set a timeout on a request. +func NewRefreshServiceCatalogSourceVersionsParamsWithTimeout(timeout time.Duration) *RefreshServiceCatalogSourceVersionsParams { + return &RefreshServiceCatalogSourceVersionsParams{ + timeout: timeout, + } +} + +// NewRefreshServiceCatalogSourceVersionsParamsWithContext creates a new RefreshServiceCatalogSourceVersionsParams object +// with the ability to set a context for a request. +func NewRefreshServiceCatalogSourceVersionsParamsWithContext(ctx context.Context) *RefreshServiceCatalogSourceVersionsParams { + return &RefreshServiceCatalogSourceVersionsParams{ + Context: ctx, + } +} + +// NewRefreshServiceCatalogSourceVersionsParamsWithHTTPClient creates a new RefreshServiceCatalogSourceVersionsParams object +// with the ability to set a custom HTTPClient for a request. +func NewRefreshServiceCatalogSourceVersionsParamsWithHTTPClient(client *http.Client) *RefreshServiceCatalogSourceVersionsParams { + return &RefreshServiceCatalogSourceVersionsParams{ + HTTPClient: client, + } +} + +/* +RefreshServiceCatalogSourceVersionsParams contains all the parameters to send to the API endpoint + + for the refresh service catalog source versions operation. + + Typically these are written to a http.Request. +*/ +type RefreshServiceCatalogSourceVersionsParams struct { + + /* OrganizationCanonical. + + A canonical of an organization. + */ + OrganizationCanonical string + + /* ServiceCatalogSourceCanonical. + + Organization Service Catalog Sources canonical + */ + ServiceCatalogSourceCanonical string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the refresh service catalog source versions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RefreshServiceCatalogSourceVersionsParams) WithDefaults() *RefreshServiceCatalogSourceVersionsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the refresh service catalog source versions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RefreshServiceCatalogSourceVersionsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) WithTimeout(timeout time.Duration) *RefreshServiceCatalogSourceVersionsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) WithContext(ctx context.Context) *RefreshServiceCatalogSourceVersionsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) WithHTTPClient(client *http.Client) *RefreshServiceCatalogSourceVersionsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrganizationCanonical adds the organizationCanonical to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) WithOrganizationCanonical(organizationCanonical string) *RefreshServiceCatalogSourceVersionsParams { + o.SetOrganizationCanonical(organizationCanonical) + return o +} + +// SetOrganizationCanonical adds the organizationCanonical to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) SetOrganizationCanonical(organizationCanonical string) { + o.OrganizationCanonical = organizationCanonical +} + +// WithServiceCatalogSourceCanonical adds the serviceCatalogSourceCanonical to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) WithServiceCatalogSourceCanonical(serviceCatalogSourceCanonical string) *RefreshServiceCatalogSourceVersionsParams { + o.SetServiceCatalogSourceCanonical(serviceCatalogSourceCanonical) + return o +} + +// SetServiceCatalogSourceCanonical adds the serviceCatalogSourceCanonical to the refresh service catalog source versions params +func (o *RefreshServiceCatalogSourceVersionsParams) SetServiceCatalogSourceCanonical(serviceCatalogSourceCanonical string) { + o.ServiceCatalogSourceCanonical = serviceCatalogSourceCanonical +} + +// WriteToRequest writes these params to a swagger request +func (o *RefreshServiceCatalogSourceVersionsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param organization_canonical + if err := r.SetPathParam("organization_canonical", o.OrganizationCanonical); err != nil { + return err + } + + // path param service_catalog_source_canonical + if err := r.SetPathParam("service_catalog_source_canonical", o.ServiceCatalogSourceCanonical); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/client/organization_service_catalog_sources/refresh_service_catalog_source_versions_responses.go b/client/client/organization_service_catalog_sources/refresh_service_catalog_source_versions_responses.go new file mode 100644 index 00000000..8a5b4ffe --- /dev/null +++ b/client/client/organization_service_catalog_sources/refresh_service_catalog_source_versions_responses.go @@ -0,0 +1,671 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organization_service_catalog_sources + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + stderrors "errors" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "github.com/cycloidio/cycloid-cli/client/models" +) + +// RefreshServiceCatalogSourceVersionsReader is a Reader for the RefreshServiceCatalogSourceVersions structure. +type RefreshServiceCatalogSourceVersionsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RefreshServiceCatalogSourceVersionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (any, error) { + switch response.Code() { + case 200: + result := NewRefreshServiceCatalogSourceVersionsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 403: + result := NewRefreshServiceCatalogSourceVersionsForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewRefreshServiceCatalogSourceVersionsNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 411: + result := NewRefreshServiceCatalogSourceVersionsLengthRequired() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewRefreshServiceCatalogSourceVersionsUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + result := NewRefreshServiceCatalogSourceVersionsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRefreshServiceCatalogSourceVersionsOK creates a RefreshServiceCatalogSourceVersionsOK with default headers values +func NewRefreshServiceCatalogSourceVersionsOK() *RefreshServiceCatalogSourceVersionsOK { + return &RefreshServiceCatalogSourceVersionsOK{} +} + +/* +RefreshServiceCatalogSourceVersionsOK describes a response with status code 200, with default header values. + +List of the Service catalog source version +*/ +type RefreshServiceCatalogSourceVersionsOK struct { + Payload *RefreshServiceCatalogSourceVersionsOKBody +} + +// IsSuccess returns true when this refresh service catalog source versions o k response has a 2xx status code +func (o *RefreshServiceCatalogSourceVersionsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this refresh service catalog source versions o k response has a 3xx status code +func (o *RefreshServiceCatalogSourceVersionsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this refresh service catalog source versions o k response has a 4xx status code +func (o *RefreshServiceCatalogSourceVersionsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this refresh service catalog source versions o k response has a 5xx status code +func (o *RefreshServiceCatalogSourceVersionsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this refresh service catalog source versions o k response a status code equal to that given +func (o *RefreshServiceCatalogSourceVersionsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the refresh service catalog source versions o k response +func (o *RefreshServiceCatalogSourceVersionsOK) Code() int { + return 200 +} + +func (o *RefreshServiceCatalogSourceVersionsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsOK %s", 200, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsOK %s", 200, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsOK) GetPayload() *RefreshServiceCatalogSourceVersionsOKBody { + return o.Payload +} + +func (o *RefreshServiceCatalogSourceVersionsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(RefreshServiceCatalogSourceVersionsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewRefreshServiceCatalogSourceVersionsForbidden creates a RefreshServiceCatalogSourceVersionsForbidden with default headers values +func NewRefreshServiceCatalogSourceVersionsForbidden() *RefreshServiceCatalogSourceVersionsForbidden { + return &RefreshServiceCatalogSourceVersionsForbidden{} +} + +/* +RefreshServiceCatalogSourceVersionsForbidden describes a response with status code 403, with default header values. + +The authenticated user cannot perform the operation because, it doesn't have permissions for such operation. +*/ +type RefreshServiceCatalogSourceVersionsForbidden struct { + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this refresh service catalog source versions forbidden response has a 2xx status code +func (o *RefreshServiceCatalogSourceVersionsForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this refresh service catalog source versions forbidden response has a 3xx status code +func (o *RefreshServiceCatalogSourceVersionsForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this refresh service catalog source versions forbidden response has a 4xx status code +func (o *RefreshServiceCatalogSourceVersionsForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this refresh service catalog source versions forbidden response has a 5xx status code +func (o *RefreshServiceCatalogSourceVersionsForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this refresh service catalog source versions forbidden response a status code equal to that given +func (o *RefreshServiceCatalogSourceVersionsForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the refresh service catalog source versions forbidden response +func (o *RefreshServiceCatalogSourceVersionsForbidden) Code() int { + return 403 +} + +func (o *RefreshServiceCatalogSourceVersionsForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsForbidden %s", 403, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsForbidden %s", 403, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsForbidden) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *RefreshServiceCatalogSourceVersionsForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewRefreshServiceCatalogSourceVersionsNotFound creates a RefreshServiceCatalogSourceVersionsNotFound with default headers values +func NewRefreshServiceCatalogSourceVersionsNotFound() *RefreshServiceCatalogSourceVersionsNotFound { + return &RefreshServiceCatalogSourceVersionsNotFound{} +} + +/* +RefreshServiceCatalogSourceVersionsNotFound describes a response with status code 404, with default header values. + +The response sent when any of the entities present in the path is not found. +*/ +type RefreshServiceCatalogSourceVersionsNotFound struct { + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this refresh service catalog source versions not found response has a 2xx status code +func (o *RefreshServiceCatalogSourceVersionsNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this refresh service catalog source versions not found response has a 3xx status code +func (o *RefreshServiceCatalogSourceVersionsNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this refresh service catalog source versions not found response has a 4xx status code +func (o *RefreshServiceCatalogSourceVersionsNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this refresh service catalog source versions not found response has a 5xx status code +func (o *RefreshServiceCatalogSourceVersionsNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this refresh service catalog source versions not found response a status code equal to that given +func (o *RefreshServiceCatalogSourceVersionsNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the refresh service catalog source versions not found response +func (o *RefreshServiceCatalogSourceVersionsNotFound) Code() int { + return 404 +} + +func (o *RefreshServiceCatalogSourceVersionsNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsNotFound %s", 404, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsNotFound %s", 404, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsNotFound) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *RefreshServiceCatalogSourceVersionsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewRefreshServiceCatalogSourceVersionsLengthRequired creates a RefreshServiceCatalogSourceVersionsLengthRequired with default headers values +func NewRefreshServiceCatalogSourceVersionsLengthRequired() *RefreshServiceCatalogSourceVersionsLengthRequired { + return &RefreshServiceCatalogSourceVersionsLengthRequired{} +} + +/* +RefreshServiceCatalogSourceVersionsLengthRequired describes a response with status code 411, with default header values. + +The request has a body but it doesn't have a Content-Length header. +*/ +type RefreshServiceCatalogSourceVersionsLengthRequired struct { +} + +// IsSuccess returns true when this refresh service catalog source versions length required response has a 2xx status code +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this refresh service catalog source versions length required response has a 3xx status code +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) IsRedirect() bool { + return false +} + +// IsClientError returns true when this refresh service catalog source versions length required response has a 4xx status code +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) IsClientError() bool { + return true +} + +// IsServerError returns true when this refresh service catalog source versions length required response has a 5xx status code +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) IsServerError() bool { + return false +} + +// IsCode returns true when this refresh service catalog source versions length required response a status code equal to that given +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) IsCode(code int) bool { + return code == 411 +} + +// Code gets the status code for the refresh service catalog source versions length required response +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) Code() int { + return 411 +} + +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) Error() string { + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsLengthRequired", 411) +} + +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) String() string { + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsLengthRequired", 411) +} + +func (o *RefreshServiceCatalogSourceVersionsLengthRequired) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewRefreshServiceCatalogSourceVersionsUnprocessableEntity creates a RefreshServiceCatalogSourceVersionsUnprocessableEntity with default headers values +func NewRefreshServiceCatalogSourceVersionsUnprocessableEntity() *RefreshServiceCatalogSourceVersionsUnprocessableEntity { + return &RefreshServiceCatalogSourceVersionsUnprocessableEntity{} +} + +/* +RefreshServiceCatalogSourceVersionsUnprocessableEntity describes a response with status code 422, with default header values. + +All the custom errors that are generated from the Cycloid API +*/ +type RefreshServiceCatalogSourceVersionsUnprocessableEntity struct { + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this refresh service catalog source versions unprocessable entity response has a 2xx status code +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this refresh service catalog source versions unprocessable entity response has a 3xx status code +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this refresh service catalog source versions unprocessable entity response has a 4xx status code +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this refresh service catalog source versions unprocessable entity response has a 5xx status code +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this refresh service catalog source versions unprocessable entity response a status code equal to that given +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the refresh service catalog source versions unprocessable entity response +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) Code() int { + return 422 +} + +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsUnprocessableEntity %s", 422, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersionsUnprocessableEntity %s", 422, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *RefreshServiceCatalogSourceVersionsUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewRefreshServiceCatalogSourceVersionsDefault creates a RefreshServiceCatalogSourceVersionsDefault with default headers values +func NewRefreshServiceCatalogSourceVersionsDefault(code int) *RefreshServiceCatalogSourceVersionsDefault { + return &RefreshServiceCatalogSourceVersionsDefault{ + _statusCode: code, + } +} + +/* +RefreshServiceCatalogSourceVersionsDefault describes a response with status code -1, with default header values. + +The response sent when an unexpected error happened, as known as an internal server error. +*/ +type RefreshServiceCatalogSourceVersionsDefault struct { + _statusCode int + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this refresh service catalog source versions default response has a 2xx status code +func (o *RefreshServiceCatalogSourceVersionsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this refresh service catalog source versions default response has a 3xx status code +func (o *RefreshServiceCatalogSourceVersionsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this refresh service catalog source versions default response has a 4xx status code +func (o *RefreshServiceCatalogSourceVersionsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this refresh service catalog source versions default response has a 5xx status code +func (o *RefreshServiceCatalogSourceVersionsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this refresh service catalog source versions default response a status code equal to that given +func (o *RefreshServiceCatalogSourceVersionsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the refresh service catalog source versions default response +func (o *RefreshServiceCatalogSourceVersionsDefault) Code() int { + return o._statusCode +} + +func (o *RefreshServiceCatalogSourceVersionsDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersions default %s", o._statusCode, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalog_sources/{service_catalog_source_canonical}/versions/refresh][%d] refreshServiceCatalogSourceVersions default %s", o._statusCode, payload) +} + +func (o *RefreshServiceCatalogSourceVersionsDefault) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *RefreshServiceCatalogSourceVersionsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +/* +RefreshServiceCatalogSourceVersionsOKBody refresh service catalog source versions o k body +swagger:model RefreshServiceCatalogSourceVersionsOKBody +*/ +type RefreshServiceCatalogSourceVersionsOKBody struct { + + // data + // Required: true + Data []*models.ServiceCatalogSourceVersion `json:"data"` +} + +// Validate validates this refresh service catalog source versions o k body +func (o *RefreshServiceCatalogSourceVersionsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RefreshServiceCatalogSourceVersionsOKBody) validateData(formats strfmt.Registry) error { + + if err := validate.Required("refreshServiceCatalogSourceVersionsOK"+"."+"data", "body", o.Data); err != nil { + return err + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("refreshServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("refreshServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// ContextValidate validate this refresh service catalog source versions o k body based on the context it is used +func (o *RefreshServiceCatalogSourceVersionsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RefreshServiceCatalogSourceVersionsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("refreshServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("refreshServiceCatalogSourceVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RefreshServiceCatalogSourceVersionsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RefreshServiceCatalogSourceVersionsOKBody) UnmarshalBinary(b []byte) error { + var res RefreshServiceCatalogSourceVersionsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/client/client/service_catalogs/get_service_catalog_usage_parameters.go b/client/client/service_catalogs/get_service_catalog_usage_parameters.go new file mode 100644 index 00000000..c48fa5ca --- /dev/null +++ b/client/client/service_catalogs/get_service_catalog_usage_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package service_catalogs + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetServiceCatalogUsageParams creates a new GetServiceCatalogUsageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetServiceCatalogUsageParams() *GetServiceCatalogUsageParams { + return &GetServiceCatalogUsageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetServiceCatalogUsageParamsWithTimeout creates a new GetServiceCatalogUsageParams object +// with the ability to set a timeout on a request. +func NewGetServiceCatalogUsageParamsWithTimeout(timeout time.Duration) *GetServiceCatalogUsageParams { + return &GetServiceCatalogUsageParams{ + timeout: timeout, + } +} + +// NewGetServiceCatalogUsageParamsWithContext creates a new GetServiceCatalogUsageParams object +// with the ability to set a context for a request. +func NewGetServiceCatalogUsageParamsWithContext(ctx context.Context) *GetServiceCatalogUsageParams { + return &GetServiceCatalogUsageParams{ + Context: ctx, + } +} + +// NewGetServiceCatalogUsageParamsWithHTTPClient creates a new GetServiceCatalogUsageParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetServiceCatalogUsageParamsWithHTTPClient(client *http.Client) *GetServiceCatalogUsageParams { + return &GetServiceCatalogUsageParams{ + HTTPClient: client, + } +} + +/* +GetServiceCatalogUsageParams contains all the parameters to send to the API endpoint + + for the get service catalog usage operation. + + Typically these are written to a http.Request. +*/ +type GetServiceCatalogUsageParams struct { + + /* OrganizationCanonical. + + A canonical of an organization. + */ + OrganizationCanonical string + + /* ServiceCatalogRef. + + A Service Catalog name + */ + ServiceCatalogRef string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get service catalog usage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetServiceCatalogUsageParams) WithDefaults() *GetServiceCatalogUsageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get service catalog usage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetServiceCatalogUsageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) WithTimeout(timeout time.Duration) *GetServiceCatalogUsageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) WithContext(ctx context.Context) *GetServiceCatalogUsageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) WithHTTPClient(client *http.Client) *GetServiceCatalogUsageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrganizationCanonical adds the organizationCanonical to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) WithOrganizationCanonical(organizationCanonical string) *GetServiceCatalogUsageParams { + o.SetOrganizationCanonical(organizationCanonical) + return o +} + +// SetOrganizationCanonical adds the organizationCanonical to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) SetOrganizationCanonical(organizationCanonical string) { + o.OrganizationCanonical = organizationCanonical +} + +// WithServiceCatalogRef adds the serviceCatalogRef to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) WithServiceCatalogRef(serviceCatalogRef string) *GetServiceCatalogUsageParams { + o.SetServiceCatalogRef(serviceCatalogRef) + return o +} + +// SetServiceCatalogRef adds the serviceCatalogRef to the get service catalog usage params +func (o *GetServiceCatalogUsageParams) SetServiceCatalogRef(serviceCatalogRef string) { + o.ServiceCatalogRef = serviceCatalogRef +} + +// WriteToRequest writes these params to a swagger request +func (o *GetServiceCatalogUsageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param organization_canonical + if err := r.SetPathParam("organization_canonical", o.OrganizationCanonical); err != nil { + return err + } + + // path param service_catalog_ref + if err := r.SetPathParam("service_catalog_ref", o.ServiceCatalogRef); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/client/service_catalogs/get_service_catalog_usage_responses.go b/client/client/service_catalogs/get_service_catalog_usage_responses.go new file mode 100644 index 00000000..afd65358 --- /dev/null +++ b/client/client/service_catalogs/get_service_catalog_usage_responses.go @@ -0,0 +1,229 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package service_catalogs + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + stderrors "errors" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "github.com/cycloidio/cycloid-cli/client/models" +) + +// GetServiceCatalogUsageReader is a Reader for the GetServiceCatalogUsage structure. +type GetServiceCatalogUsageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetServiceCatalogUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (any, error) { + switch response.Code() { + case 200: + result := NewGetServiceCatalogUsageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/usage] getServiceCatalogUsage", response, response.Code()) + } +} + +// NewGetServiceCatalogUsageOK creates a GetServiceCatalogUsageOK with default headers values +func NewGetServiceCatalogUsageOK() *GetServiceCatalogUsageOK { + return &GetServiceCatalogUsageOK{} +} + +/* +GetServiceCatalogUsageOK describes a response with status code 200, with default header values. + +List of the Components using the Service Catalog +*/ +type GetServiceCatalogUsageOK struct { + Payload *GetServiceCatalogUsageOKBody +} + +// IsSuccess returns true when this get service catalog usage o k response has a 2xx status code +func (o *GetServiceCatalogUsageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get service catalog usage o k response has a 3xx status code +func (o *GetServiceCatalogUsageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get service catalog usage o k response has a 4xx status code +func (o *GetServiceCatalogUsageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get service catalog usage o k response has a 5xx status code +func (o *GetServiceCatalogUsageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get service catalog usage o k response a status code equal to that given +func (o *GetServiceCatalogUsageOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get service catalog usage o k response +func (o *GetServiceCatalogUsageOK) Code() int { + return 200 +} + +func (o *GetServiceCatalogUsageOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/usage][%d] getServiceCatalogUsageOK %s", 200, payload) +} + +func (o *GetServiceCatalogUsageOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/usage][%d] getServiceCatalogUsageOK %s", 200, payload) +} + +func (o *GetServiceCatalogUsageOK) GetPayload() *GetServiceCatalogUsageOKBody { + return o.Payload +} + +func (o *GetServiceCatalogUsageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetServiceCatalogUsageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +/* +GetServiceCatalogUsageOKBody get service catalog usage o k body +swagger:model GetServiceCatalogUsageOKBody +*/ +type GetServiceCatalogUsageOKBody struct { + + // data + // Required: true + Data []*models.Component `json:"data"` +} + +// Validate validates this get service catalog usage o k body +func (o *GetServiceCatalogUsageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetServiceCatalogUsageOKBody) validateData(formats strfmt.Registry) error { + + if err := validate.Required("getServiceCatalogUsageOK"+"."+"data", "body", o.Data); err != nil { + return err + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("getServiceCatalogUsageOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("getServiceCatalogUsageOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get service catalog usage o k body based on the context it is used +func (o *GetServiceCatalogUsageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetServiceCatalogUsageOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("getServiceCatalogUsageOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("getServiceCatalogUsageOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetServiceCatalogUsageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetServiceCatalogUsageOKBody) UnmarshalBinary(b []byte) error { + var res GetServiceCatalogUsageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/client/client/service_catalogs/get_service_catalog_use_cases_parameters.go b/client/client/service_catalogs/get_service_catalog_use_cases_parameters.go index 9a061b4d..bbd0364d 100644 --- a/client/client/service_catalogs/get_service_catalog_use_cases_parameters.go +++ b/client/client/service_catalogs/get_service_catalog_use_cases_parameters.go @@ -14,6 +14,7 @@ import ( "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" ) // NewGetServiceCatalogUseCasesParams creates a new GetServiceCatalogUseCasesParams object, @@ -73,6 +74,15 @@ type GetServiceCatalogUseCasesParams struct { */ ServiceCatalogRef string + /* ServiceCatalogSourceVersionID. + + The ID of the SCS Version + + Format: uint32 + Default: 1 + */ + ServiceCatalogSourceVersionID uint32 + timeout time.Duration Context context.Context HTTPClient *http.Client @@ -90,7 +100,18 @@ func (o *GetServiceCatalogUseCasesParams) WithDefaults() *GetServiceCatalogUseCa // // All values with no default are reset to their zero value. func (o *GetServiceCatalogUseCasesParams) SetDefaults() { - // no default values defined for this parameter + var ( + serviceCatalogSourceVersionIDDefault = uint32(1) + ) + + val := GetServiceCatalogUseCasesParams{ + ServiceCatalogSourceVersionID: serviceCatalogSourceVersionIDDefault, + } + + val.timeout = o.timeout + val.Context = o.Context + val.HTTPClient = o.HTTPClient + *o = val } // WithTimeout adds the timeout to the get service catalog use cases params @@ -148,6 +169,17 @@ func (o *GetServiceCatalogUseCasesParams) SetServiceCatalogRef(serviceCatalogRef o.ServiceCatalogRef = serviceCatalogRef } +// WithServiceCatalogSourceVersionID adds the serviceCatalogSourceVersionID to the get service catalog use cases params +func (o *GetServiceCatalogUseCasesParams) WithServiceCatalogSourceVersionID(serviceCatalogSourceVersionID uint32) *GetServiceCatalogUseCasesParams { + o.SetServiceCatalogSourceVersionID(serviceCatalogSourceVersionID) + return o +} + +// SetServiceCatalogSourceVersionID adds the serviceCatalogSourceVersionId to the get service catalog use cases params +func (o *GetServiceCatalogUseCasesParams) SetServiceCatalogSourceVersionID(serviceCatalogSourceVersionID uint32) { + o.ServiceCatalogSourceVersionID = serviceCatalogSourceVersionID +} + // WriteToRequest writes these params to a swagger request func (o *GetServiceCatalogUseCasesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { @@ -166,6 +198,16 @@ func (o *GetServiceCatalogUseCasesParams) WriteToRequest(r runtime.ClientRequest return err } + // query param service_catalog_source_version_id + qrServiceCatalogSourceVersionID := o.ServiceCatalogSourceVersionID + qServiceCatalogSourceVersionID := swag.FormatUint32(qrServiceCatalogSourceVersionID) + if qServiceCatalogSourceVersionID != "" { + + if err := r.SetQueryParam("service_catalog_source_version_id", qServiceCatalogSourceVersionID); err != nil { + return err + } + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } diff --git a/client/client/service_catalogs/get_service_catalog_versions_parameters.go b/client/client/service_catalogs/get_service_catalog_versions_parameters.go new file mode 100644 index 00000000..63a62cd6 --- /dev/null +++ b/client/client/service_catalogs/get_service_catalog_versions_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package service_catalogs + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetServiceCatalogVersionsParams creates a new GetServiceCatalogVersionsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetServiceCatalogVersionsParams() *GetServiceCatalogVersionsParams { + return &GetServiceCatalogVersionsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetServiceCatalogVersionsParamsWithTimeout creates a new GetServiceCatalogVersionsParams object +// with the ability to set a timeout on a request. +func NewGetServiceCatalogVersionsParamsWithTimeout(timeout time.Duration) *GetServiceCatalogVersionsParams { + return &GetServiceCatalogVersionsParams{ + timeout: timeout, + } +} + +// NewGetServiceCatalogVersionsParamsWithContext creates a new GetServiceCatalogVersionsParams object +// with the ability to set a context for a request. +func NewGetServiceCatalogVersionsParamsWithContext(ctx context.Context) *GetServiceCatalogVersionsParams { + return &GetServiceCatalogVersionsParams{ + Context: ctx, + } +} + +// NewGetServiceCatalogVersionsParamsWithHTTPClient creates a new GetServiceCatalogVersionsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetServiceCatalogVersionsParamsWithHTTPClient(client *http.Client) *GetServiceCatalogVersionsParams { + return &GetServiceCatalogVersionsParams{ + HTTPClient: client, + } +} + +/* +GetServiceCatalogVersionsParams contains all the parameters to send to the API endpoint + + for the get service catalog versions operation. + + Typically these are written to a http.Request. +*/ +type GetServiceCatalogVersionsParams struct { + + /* OrganizationCanonical. + + A canonical of an organization. + */ + OrganizationCanonical string + + /* ServiceCatalogRef. + + A Service Catalog name + */ + ServiceCatalogRef string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get service catalog versions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetServiceCatalogVersionsParams) WithDefaults() *GetServiceCatalogVersionsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get service catalog versions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetServiceCatalogVersionsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) WithTimeout(timeout time.Duration) *GetServiceCatalogVersionsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) WithContext(ctx context.Context) *GetServiceCatalogVersionsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) WithHTTPClient(client *http.Client) *GetServiceCatalogVersionsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrganizationCanonical adds the organizationCanonical to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) WithOrganizationCanonical(organizationCanonical string) *GetServiceCatalogVersionsParams { + o.SetOrganizationCanonical(organizationCanonical) + return o +} + +// SetOrganizationCanonical adds the organizationCanonical to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) SetOrganizationCanonical(organizationCanonical string) { + o.OrganizationCanonical = organizationCanonical +} + +// WithServiceCatalogRef adds the serviceCatalogRef to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) WithServiceCatalogRef(serviceCatalogRef string) *GetServiceCatalogVersionsParams { + o.SetServiceCatalogRef(serviceCatalogRef) + return o +} + +// SetServiceCatalogRef adds the serviceCatalogRef to the get service catalog versions params +func (o *GetServiceCatalogVersionsParams) SetServiceCatalogRef(serviceCatalogRef string) { + o.ServiceCatalogRef = serviceCatalogRef +} + +// WriteToRequest writes these params to a swagger request +func (o *GetServiceCatalogVersionsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param organization_canonical + if err := r.SetPathParam("organization_canonical", o.OrganizationCanonical); err != nil { + return err + } + + // path param service_catalog_ref + if err := r.SetPathParam("service_catalog_ref", o.ServiceCatalogRef); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/client/service_catalogs/get_service_catalog_versions_responses.go b/client/client/service_catalogs/get_service_catalog_versions_responses.go new file mode 100644 index 00000000..e7dd5863 --- /dev/null +++ b/client/client/service_catalogs/get_service_catalog_versions_responses.go @@ -0,0 +1,327 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package service_catalogs + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + stderrors "errors" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "github.com/cycloidio/cycloid-cli/client/models" +) + +// GetServiceCatalogVersionsReader is a Reader for the GetServiceCatalogVersions structure. +type GetServiceCatalogVersionsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetServiceCatalogVersionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (any, error) { + switch response.Code() { + case 200: + result := NewGetServiceCatalogVersionsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetServiceCatalogVersionsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetServiceCatalogVersionsOK creates a GetServiceCatalogVersionsOK with default headers values +func NewGetServiceCatalogVersionsOK() *GetServiceCatalogVersionsOK { + return &GetServiceCatalogVersionsOK{} +} + +/* +GetServiceCatalogVersionsOK describes a response with status code 200, with default header values. + +The information of the service catalog versions. +*/ +type GetServiceCatalogVersionsOK struct { + Payload *GetServiceCatalogVersionsOKBody +} + +// IsSuccess returns true when this get service catalog versions o k response has a 2xx status code +func (o *GetServiceCatalogVersionsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get service catalog versions o k response has a 3xx status code +func (o *GetServiceCatalogVersionsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get service catalog versions o k response has a 4xx status code +func (o *GetServiceCatalogVersionsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get service catalog versions o k response has a 5xx status code +func (o *GetServiceCatalogVersionsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get service catalog versions o k response a status code equal to that given +func (o *GetServiceCatalogVersionsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get service catalog versions o k response +func (o *GetServiceCatalogVersionsOK) Code() int { + return 200 +} + +func (o *GetServiceCatalogVersionsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/versions][%d] getServiceCatalogVersionsOK %s", 200, payload) +} + +func (o *GetServiceCatalogVersionsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/versions][%d] getServiceCatalogVersionsOK %s", 200, payload) +} + +func (o *GetServiceCatalogVersionsOK) GetPayload() *GetServiceCatalogVersionsOKBody { + return o.Payload +} + +func (o *GetServiceCatalogVersionsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetServiceCatalogVersionsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +// NewGetServiceCatalogVersionsDefault creates a GetServiceCatalogVersionsDefault with default headers values +func NewGetServiceCatalogVersionsDefault(code int) *GetServiceCatalogVersionsDefault { + return &GetServiceCatalogVersionsDefault{ + _statusCode: code, + } +} + +/* +GetServiceCatalogVersionsDefault describes a response with status code -1, with default header values. + +The response sent when an unexpected error happened, as known as an internal server error. +*/ +type GetServiceCatalogVersionsDefault struct { + _statusCode int + + /* The length of the response body in octets (8-bit bytes). + + Format: uint64 + */ + ContentLength uint64 + + Payload *models.ErrorPayload +} + +// IsSuccess returns true when this get service catalog versions default response has a 2xx status code +func (o *GetServiceCatalogVersionsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get service catalog versions default response has a 3xx status code +func (o *GetServiceCatalogVersionsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get service catalog versions default response has a 4xx status code +func (o *GetServiceCatalogVersionsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get service catalog versions default response has a 5xx status code +func (o *GetServiceCatalogVersionsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get service catalog versions default response a status code equal to that given +func (o *GetServiceCatalogVersionsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get service catalog versions default response +func (o *GetServiceCatalogVersionsDefault) Code() int { + return o._statusCode +} + +func (o *GetServiceCatalogVersionsDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/versions][%d] getServiceCatalogVersions default %s", o._statusCode, payload) +} + +func (o *GetServiceCatalogVersionsDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/versions][%d] getServiceCatalogVersions default %s", o._statusCode, payload) +} + +func (o *GetServiceCatalogVersionsDefault) GetPayload() *models.ErrorPayload { + return o.Payload +} + +func (o *GetServiceCatalogVersionsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header Content-Length + hdrContentLength := response.GetHeader("Content-Length") + + if hdrContentLength != "" { + valcontentLength, err := swag.ConvertUint64(hdrContentLength) + if err != nil { + return errors.InvalidType("Content-Length", "header", "uint64", hdrContentLength) + } + o.ContentLength = valcontentLength + } + + o.Payload = new(models.ErrorPayload) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && !stderrors.Is(err, io.EOF) { + return err + } + + return nil +} + +/* +GetServiceCatalogVersionsOKBody get service catalog versions o k body +swagger:model GetServiceCatalogVersionsOKBody +*/ +type GetServiceCatalogVersionsOKBody struct { + + // data + // Required: true + Data []*models.ServiceCatalogSourceVersion `json:"data"` +} + +// Validate validates this get service catalog versions o k body +func (o *GetServiceCatalogVersionsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetServiceCatalogVersionsOKBody) validateData(formats strfmt.Registry) error { + + if err := validate.Required("getServiceCatalogVersionsOK"+"."+"data", "body", o.Data); err != nil { + return err + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("getServiceCatalogVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("getServiceCatalogVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get service catalog versions o k body based on the context it is used +func (o *GetServiceCatalogVersionsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetServiceCatalogVersionsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("getServiceCatalogVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("getServiceCatalogVersionsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetServiceCatalogVersionsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetServiceCatalogVersionsOKBody) UnmarshalBinary(b []byte) error { + var res GetServiceCatalogVersionsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/client/client/service_catalogs/service_catalogs_client.go b/client/client/service_catalogs/service_catalogs_client.go index 0e97ec51..a11c8dd5 100644 --- a/client/client/service_catalogs/service_catalogs_client.go +++ b/client/client/service_catalogs/service_catalogs_client.go @@ -117,8 +117,12 @@ type ClientService interface { GetServiceCatalogTerraformImage(params *GetServiceCatalogTerraformImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetServiceCatalogTerraformImageOK, error) + GetServiceCatalogUsage(params *GetServiceCatalogUsageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetServiceCatalogUsageOK, error) + GetServiceCatalogUseCases(params *GetServiceCatalogUseCasesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetServiceCatalogUseCasesOK, error) + GetServiceCatalogVersions(params *GetServiceCatalogVersionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetServiceCatalogVersionsOK, error) + ListServiceCatalogs(params *ListServiceCatalogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListServiceCatalogsOK, error) UpdateServiceCatalog(params *UpdateServiceCatalogParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateServiceCatalogOK, error) @@ -393,6 +397,50 @@ func (a *Client) GetServiceCatalogTerraformImage(params *GetServiceCatalogTerraf return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +GetServiceCatalogUsage Get the usage of the Service Catalog +*/ +func (a *Client) GetServiceCatalogUsage(params *GetServiceCatalogUsageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetServiceCatalogUsageOK, error) { + // NOTE: parameters are not validated before sending + if params == nil { + params = NewGetServiceCatalogUsageParams() + } + op := &runtime.ClientOperation{ + ID: "getServiceCatalogUsage", + Method: "GET", + PathPattern: "/organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/usage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/vnd.cycloid.io.v1+json", "application/x-www-form-urlencoded"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetServiceCatalogUsageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + + // only one success response has to be checked + success, ok := result.(*GetServiceCatalogUsageOK) + if ok { + return success, nil + } + + // unexpected success response. + + // no default response is defined. + // + // safeguard: normally, in the absence of a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for getServiceCatalogUsage: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + /* GetServiceCatalogUseCases Fetch the use cases available for a given Service Catalog */ @@ -436,6 +484,49 @@ func (a *Client) GetServiceCatalogUseCases(params *GetServiceCatalogUseCasesPara return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +GetServiceCatalogVersions Fetch the versions available for a given Service Catalog +*/ +func (a *Client) GetServiceCatalogVersions(params *GetServiceCatalogVersionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetServiceCatalogVersionsOK, error) { + // NOTE: parameters are not validated before sending + if params == nil { + params = NewGetServiceCatalogVersionsParams() + } + op := &runtime.ClientOperation{ + ID: "getServiceCatalogVersions", + Method: "GET", + PathPattern: "/organizations/{organization_canonical}/service_catalogs/{service_catalog_ref}/versions", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/vnd.cycloid.io.v1+json", "application/x-www-form-urlencoded"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetServiceCatalogVersionsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + + // only one success response has to be checked + success, ok := result.(*GetServiceCatalogVersionsOK) + if ok { + return success, nil + } + + // unexpected success response. + // + // a default response is provided: fill this and return an error + unexpectedSuccess := result.(*GetServiceCatalogVersionsDefault) + + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* ListServiceCatalogs Return all the service catalogs */ diff --git a/client/models/component.go b/client/models/component.go index 5ac78e71..e140482b 100644 --- a/client/models/component.go +++ b/client/models/component.go @@ -83,6 +83,10 @@ type Component struct { // Min Length: 1 // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) UseCase string `json:"use_case,omitempty"` + + // The version used by the Component + // Required: true + Version *ServiceCatalogSourceVersion `json:"version"` } // Validate validates this component @@ -133,6 +137,10 @@ func (m *Component) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -372,6 +380,30 @@ func (m *Component) validateUseCase(formats strfmt.Registry) error { return nil } +func (m *Component) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if m.Version != nil { + if err := m.Version.Validate(formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("version") + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("version") + } + + return err + } + } + + return nil +} + // ContextValidate validate this component based on the context it is used func (m *Component) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error @@ -392,6 +424,10 @@ func (m *Component) ContextValidate(ctx context.Context, formats strfmt.Registry res = append(res, err) } + if err := m.contextValidateVersion(ctx, formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -486,6 +522,27 @@ func (m *Component) contextValidateServiceCatalog(ctx context.Context, formats s return nil } +func (m *Component) contextValidateVersion(ctx context.Context, formats strfmt.Registry) error { + + if m.Version != nil { + + if err := m.Version.ContextValidate(ctx, formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("version") + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("version") + } + + return err + } + } + + return nil +} + // MarshalBinary interface implementation func (m *Component) MarshalBinary() ([]byte, error) { if m == nil { diff --git a/client/models/component_simple.go b/client/models/component_simple.go index 7a377ed0..dfe10d76 100644 --- a/client/models/component_simple.go +++ b/client/models/component_simple.go @@ -67,6 +67,10 @@ type ComponentSimple struct { // Min Length: 1 // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) UseCase string `json:"use_case,omitempty"` + + // The version used by the Component + // Required: true + Version *ServiceCatalogSourceVersion `json:"version"` } // Validate validates this component simple @@ -105,6 +109,10 @@ func (m *ComponentSimple) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -251,6 +259,30 @@ func (m *ComponentSimple) validateUseCase(formats strfmt.Registry) error { return nil } +func (m *ComponentSimple) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if m.Version != nil { + if err := m.Version.Validate(formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("version") + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("version") + } + + return err + } + } + + return nil +} + // ContextValidate validate this component simple based on the context it is used func (m *ComponentSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error @@ -263,6 +295,10 @@ func (m *ComponentSimple) ContextValidate(ctx context.Context, formats strfmt.Re res = append(res, err) } + if err := m.contextValidateVersion(ctx, formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -315,6 +351,27 @@ func (m *ComponentSimple) contextValidateServiceCatalog(ctx context.Context, for return nil } +func (m *ComponentSimple) contextValidateVersion(ctx context.Context, formats strfmt.Registry) error { + + if m.Version != nil { + + if err := m.Version.ContextValidate(ctx, formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("version") + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("version") + } + + return err + } + } + + return nil +} + // MarshalBinary interface implementation func (m *ComponentSimple) MarshalBinary() ([]byte, error) { if m == nil { diff --git a/client/models/configure_component.go b/client/models/configure_component.go index dc471db2..ab40f176 100644 --- a/client/models/configure_component.go +++ b/client/models/configure_component.go @@ -22,6 +22,16 @@ import ( // swagger:model ConfigureComponent type ConfigureComponent struct { + // Is the CommitHash of the version, if the component updated the version this should be the new hash. We need the ID+HASH as the ID alone we do not know if the version was updated or not (same ID could have been used with a different hash). With both we can assert if it did or did not change the version + // + // Required: true + ServiceCatalogSourceVersionCommitHash *string `json:"service_catalog_source_version_commit_hash"` + + // Is the ID of the new SCS Version used + // Required: true + // Minimum: 1 + ServiceCatalogSourceVersionID *uint32 `json:"service_catalog_source_version_id"` + // use case // Required: true // Max Length: 100 @@ -37,6 +47,14 @@ type ConfigureComponent struct { func (m *ConfigureComponent) Validate(formats strfmt.Registry) error { var res []error + if err := m.validateServiceCatalogSourceVersionCommitHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateServiceCatalogSourceVersionID(formats); err != nil { + res = append(res, err) + } + if err := m.validateUseCase(formats); err != nil { res = append(res, err) } @@ -51,6 +69,28 @@ func (m *ConfigureComponent) Validate(formats strfmt.Registry) error { return nil } +func (m *ConfigureComponent) validateServiceCatalogSourceVersionCommitHash(formats strfmt.Registry) error { + + if err := validate.Required("service_catalog_source_version_commit_hash", "body", m.ServiceCatalogSourceVersionCommitHash); err != nil { + return err + } + + return nil +} + +func (m *ConfigureComponent) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { + + if err := validate.Required("service_catalog_source_version_id", "body", m.ServiceCatalogSourceVersionID); err != nil { + return err + } + + if err := validate.MinimumUint("service_catalog_source_version_id", "body", uint64(*m.ServiceCatalogSourceVersionID), 1, false); err != nil { + return err + } + + return nil +} + func (m *ConfigureComponent) validateUseCase(formats strfmt.Registry) error { if err := validate.Required("use_case", "body", m.UseCase); err != nil { diff --git a/client/models/environment.go b/client/models/environment.go index bd12f904..e65c8996 100644 --- a/client/models/environment.go +++ b/client/models/environment.go @@ -7,6 +7,7 @@ package models import ( "context" + "encoding/json" stderrors "errors" "strconv" @@ -57,6 +58,9 @@ type Environment struct { // Required: true // Minimum: 0 UpdatedAt *uint64 `json:"updated_at"` + + // When the environment is returned alongside Project this will be set with the aggregated value of the Components Version.Status it has + VersionStatus []string `json:"version_status"` } // Validate validates this environment @@ -91,6 +95,10 @@ func (m *Environment) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateVersionStatus(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -216,6 +224,42 @@ func (m *Environment) validateUpdatedAt(formats strfmt.Registry) error { return nil } +var environmentVersionStatusItemsEnum []any + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["no_status","latest","active","deleted","outdated"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + environmentVersionStatusItemsEnum = append(environmentVersionStatusItemsEnum, v) + } +} + +func (m *Environment) validateVersionStatusItemsEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, environmentVersionStatusItemsEnum, true); err != nil { + return err + } + return nil +} + +func (m *Environment) validateVersionStatus(formats strfmt.Registry) error { + if swag.IsZero(m.VersionStatus) { // not required + return nil + } + + for i := 0; i < len(m.VersionStatus); i++ { + + // value enum + if err := m.validateVersionStatusItemsEnum("version_status"+"."+strconv.Itoa(i), "body", m.VersionStatus[i]); err != nil { + return err + } + + } + + return nil +} + // ContextValidate validate this environment based on the context it is used func (m *Environment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error diff --git a/client/models/new_and_configured_component.go b/client/models/new_and_configured_component.go index ba5af5ef..9980f0ea 100644 --- a/client/models/new_and_configured_component.go +++ b/client/models/new_and_configured_component.go @@ -45,6 +45,16 @@ type NewAndConfiguredComponent struct { // It's the ref of the Stack, like 'cycloidio:stack-magento' ServiceCatalogRef string `json:"service_catalog_ref,omitempty"` + // Is the CommitHash of the version, if the component updated the version this should be the new hash. We need the ID+HASH as the ID alone we do not know if the version was updated or not (same ID could have been used with a different hash). With both we can assert if it did or did not change the version + // + // Required: true + ServiceCatalogSourceVersionCommitHash *string `json:"service_catalog_source_version_commit_hash"` + + // Is the ID of the new SCS Version used + // Required: true + // Minimum: 1 + ServiceCatalogSourceVersionID *uint32 `json:"service_catalog_source_version_id"` + // use case // Max Length: 100 // Min Length: 1 @@ -71,6 +81,14 @@ func (m *NewAndConfiguredComponent) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateServiceCatalogSourceVersionCommitHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateServiceCatalogSourceVersionID(formats); err != nil { + res = append(res, err) + } + if err := m.validateUseCase(formats); err != nil { res = append(res, err) } @@ -138,6 +156,28 @@ func (m *NewAndConfiguredComponent) validateName(formats strfmt.Registry) error return nil } +func (m *NewAndConfiguredComponent) validateServiceCatalogSourceVersionCommitHash(formats strfmt.Registry) error { + + if err := validate.Required("service_catalog_source_version_commit_hash", "body", m.ServiceCatalogSourceVersionCommitHash); err != nil { + return err + } + + return nil +} + +func (m *NewAndConfiguredComponent) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { + + if err := validate.Required("service_catalog_source_version_id", "body", m.ServiceCatalogSourceVersionID); err != nil { + return err + } + + if err := validate.MinimumUint("service_catalog_source_version_id", "body", uint64(*m.ServiceCatalogSourceVersionID), 1, false); err != nil { + return err + } + + return nil +} + func (m *NewAndConfiguredComponent) validateUseCase(formats strfmt.Registry) error { if swag.IsZero(m.UseCase) { // not required return nil diff --git a/client/models/new_component.go b/client/models/new_component.go index 48ce81fc..1f190f55 100644 --- a/client/models/new_component.go +++ b/client/models/new_component.go @@ -44,6 +44,11 @@ type NewComponent struct { // It's the ref of the Stack, like 'cycloidio:stack-magento' // Required: true ServiceCatalogRef *string `json:"service_catalog_ref"` + + // service catalog source version id + // Required: true + // Minimum: 1 + ServiceCatalogSourceVersionID *uint32 `json:"service_catalog_source_version_id"` } // Validate validates this new component @@ -66,6 +71,10 @@ func (m *NewComponent) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateServiceCatalogSourceVersionID(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -134,6 +143,19 @@ func (m *NewComponent) validateServiceCatalogRef(formats strfmt.Registry) error return nil } +func (m *NewComponent) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { + + if err := validate.Required("service_catalog_source_version_id", "body", m.ServiceCatalogSourceVersionID); err != nil { + return err + } + + if err := validate.MinimumUint("service_catalog_source_version_id", "body", uint64(*m.ServiceCatalogSourceVersionID), 1, false); err != nil { + return err + } + + return nil +} + // ContextValidate validates this new component based on context it is used func (m *NewComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { return nil diff --git a/client/models/project.go b/client/models/project.go index 8e67525d..138896d0 100644 --- a/client/models/project.go +++ b/client/models/project.go @@ -7,6 +7,7 @@ package models import ( "context" + "encoding/json" stderrors "errors" "strconv" @@ -84,6 +85,9 @@ type Project struct { // Required: true // Minimum: 0 UpdatedAt *uint64 `json:"updated_at"` + + // Aggregated value of the Environments Components Version.Status + VersionStatus []string `json:"version_status"` } // Validate validates this project @@ -134,6 +138,10 @@ func (m *Project) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateVersionStatus(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -336,6 +344,42 @@ func (m *Project) validateUpdatedAt(formats strfmt.Registry) error { return nil } +var projectVersionStatusItemsEnum []any + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["no_status","latest","active","deleted","outdated"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + projectVersionStatusItemsEnum = append(projectVersionStatusItemsEnum, v) + } +} + +func (m *Project) validateVersionStatusItemsEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, projectVersionStatusItemsEnum, true); err != nil { + return err + } + return nil +} + +func (m *Project) validateVersionStatus(formats strfmt.Registry) error { + if swag.IsZero(m.VersionStatus) { // not required + return nil + } + + for i := 0; i < len(m.VersionStatus); i++ { + + // value enum + if err := m.validateVersionStatusItemsEnum("version_status"+"."+strconv.Itoa(i), "body", m.VersionStatus[i]); err != nil { + return err + } + + } + + return nil +} + // ContextValidate validate this project based on the context it is used func (m *Project) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error diff --git a/client/models/service_catalog_changes.go b/client/models/service_catalog_changes.go index 61953c95..80efafaa 100644 --- a/client/models/service_catalog_changes.go +++ b/client/models/service_catalog_changes.go @@ -34,6 +34,9 @@ type ServiceCatalogChanges struct { // updated // Required: true Updated []*ServiceCatalog `json:"updated"` + + // versions + Versions []*ServiceCatalogSourceVersion `json:"versions"` } // Validate validates this service catalog changes @@ -52,6 +55,10 @@ func (m *ServiceCatalogChanges) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateVersions(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -151,6 +158,36 @@ func (m *ServiceCatalogChanges) validateUpdated(formats strfmt.Registry) error { return nil } +func (m *ServiceCatalogChanges) validateVersions(formats strfmt.Registry) error { + if swag.IsZero(m.Versions) { // not required + return nil + } + + for i := 0; i < len(m.Versions); i++ { + if swag.IsZero(m.Versions[i]) { // not required + continue + } + + if m.Versions[i] != nil { + if err := m.Versions[i].Validate(formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("versions" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("versions" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + // ContextValidate validate this service catalog changes based on the context it is used func (m *ServiceCatalogChanges) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error @@ -167,6 +204,10 @@ func (m *ServiceCatalogChanges) ContextValidate(ctx context.Context, formats str res = append(res, err) } + if err := m.contextValidateVersions(ctx, formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -260,6 +301,35 @@ func (m *ServiceCatalogChanges) contextValidateUpdated(ctx context.Context, form return nil } +func (m *ServiceCatalogChanges) contextValidateVersions(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Versions); i++ { + + if m.Versions[i] != nil { + + if swag.IsZero(m.Versions[i]) { // not required + return nil + } + + if err := m.Versions[i].ContextValidate(ctx, formats); err != nil { + ve := new(errors.Validation) + if stderrors.As(err, &ve) { + return ve.ValidateName("versions" + "." + strconv.Itoa(i)) + } + ce := new(errors.CompositeError) + if stderrors.As(err, &ce) { + return ce.ValidateName("versions" + "." + strconv.Itoa(i)) + } + + return err + } + } + + } + + return nil +} + // MarshalBinary interface implementation func (m *ServiceCatalogChanges) MarshalBinary() ([]byte, error) { if m == nil { diff --git a/client/models/service_catalog_source_version.go b/client/models/service_catalog_source_version.go new file mode 100644 index 00000000..62e6d506 --- /dev/null +++ b/client/models/service_catalog_source_version.go @@ -0,0 +1,262 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ServiceCatalogSourceVersion Version +// +// # Version of a SCS for the Stacks +// +// swagger:model ServiceCatalogSourceVersion +type ServiceCatalogSourceVersion struct { + + // Last commit hash that references it + // Required: true + // Min Length: 1 + CommitHash *string `json:"commit_hash"` + + // id + // Required: true + // Minimum: 1 + ID *uint32 `json:"id"` + + // If it's the latest + // Required: true + IsLatest *bool `json:"is_latest"` + + // Name of the version + // Required: true + Name *string `json:"name"` + + // Status of the version + // Required: true + // Enum: ["no_status","active","deleted","outdated"] + Status *string `json:"status"` + + // Type of the version + // Required: true + // Enum: ["tag","branch"] + Type *string `json:"type"` + + // How many stacks use it + // Required: true + Usage *int64 `json:"usage"` +} + +// Validate validates this service catalog source version +func (m *ServiceCatalogSourceVersion) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCommitHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIsLatest(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUsage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ServiceCatalogSourceVersion) validateCommitHash(formats strfmt.Registry) error { + + if err := validate.Required("commit_hash", "body", m.CommitHash); err != nil { + return err + } + + if err := validate.MinLength("commit_hash", "body", *m.CommitHash, 1); err != nil { + return err + } + + return nil +} + +func (m *ServiceCatalogSourceVersion) validateID(formats strfmt.Registry) error { + + if err := validate.Required("id", "body", m.ID); err != nil { + return err + } + + if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { + return err + } + + return nil +} + +func (m *ServiceCatalogSourceVersion) validateIsLatest(formats strfmt.Registry) error { + + if err := validate.Required("is_latest", "body", m.IsLatest); err != nil { + return err + } + + return nil +} + +func (m *ServiceCatalogSourceVersion) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +var serviceCatalogSourceVersionTypeStatusPropEnum []any + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["no_status","active","deleted","outdated"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + serviceCatalogSourceVersionTypeStatusPropEnum = append(serviceCatalogSourceVersionTypeStatusPropEnum, v) + } +} + +const ( + + // ServiceCatalogSourceVersionStatusNoStatus captures enum value "no_status" + ServiceCatalogSourceVersionStatusNoStatus string = "no_status" + + // ServiceCatalogSourceVersionStatusActive captures enum value "active" + ServiceCatalogSourceVersionStatusActive string = "active" + + // ServiceCatalogSourceVersionStatusDeleted captures enum value "deleted" + ServiceCatalogSourceVersionStatusDeleted string = "deleted" + + // ServiceCatalogSourceVersionStatusOutdated captures enum value "outdated" + ServiceCatalogSourceVersionStatusOutdated string = "outdated" +) + +// prop value enum +func (m *ServiceCatalogSourceVersion) validateStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, serviceCatalogSourceVersionTypeStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *ServiceCatalogSourceVersion) validateStatus(formats strfmt.Registry) error { + + if err := validate.Required("status", "body", m.Status); err != nil { + return err + } + + // value enum + if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { + return err + } + + return nil +} + +var serviceCatalogSourceVersionTypeTypePropEnum []any + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["tag","branch"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + serviceCatalogSourceVersionTypeTypePropEnum = append(serviceCatalogSourceVersionTypeTypePropEnum, v) + } +} + +const ( + + // ServiceCatalogSourceVersionTypeTag captures enum value "tag" + ServiceCatalogSourceVersionTypeTag string = "tag" + + // ServiceCatalogSourceVersionTypeBranch captures enum value "branch" + ServiceCatalogSourceVersionTypeBranch string = "branch" +) + +// prop value enum +func (m *ServiceCatalogSourceVersion) validateTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, serviceCatalogSourceVersionTypeTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *ServiceCatalogSourceVersion) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + // value enum + if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { + return err + } + + return nil +} + +func (m *ServiceCatalogSourceVersion) validateUsage(formats strfmt.Registry) error { + + if err := validate.Required("usage", "body", m.Usage); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this service catalog source version based on context it is used +func (m *ServiceCatalogSourceVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ServiceCatalogSourceVersion) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ServiceCatalogSourceVersion) UnmarshalBinary(b []byte) error { + var res ServiceCatalogSourceVersion + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/cmd/cycloid/beta/config/interpolate.go b/cmd/cycloid/beta/config/interpolate.go index cd432faf..0e56ed28 100644 --- a/cmd/cycloid/beta/config/interpolate.go +++ b/cmd/cycloid/beta/config/interpolate.go @@ -25,6 +25,7 @@ func NewInterpolateCmd() *cobra.Command { cyargs.AddStackRefFlag(cmd) cyargs.AddCyContext(cmd) cyargs.AddStackFormsInputFlags(cmd) + cyargs.AddStackVersionFlags(cmd) return cmd } @@ -57,8 +58,14 @@ func interpolate(cmd *cobra.Command, args []string) error { api := common.NewAPI() m := middleware.NewMiddleware(api) + // Get the stack version flags + tag, branch, hash, err := cyargs.GetStackVersionFlags(cmd) + if err != nil { + return errors.Wrap(err, "failed to read stack version flags") + } + // Get default to stacks - stackConfig, err := m.GetComponentStackConfig(org, project, env, component, useCase) + stackConfig, err := m.GetComponentStackConfig(org, project, env, component, useCase, tag, branch, hash) if err != nil { return err } diff --git a/cmd/cycloid/components/create.go b/cmd/cycloid/components/create.go index 4c84b9c2..2b2a92c1 100644 --- a/cmd/cycloid/components/create.go +++ b/cmd/cycloid/components/create.go @@ -27,8 +27,9 @@ func NewCreateComponentCommand() *cobra.Command { cyargs.AddNameFlag(cmd) cyargs.AddComponentDescriptionFlag(cmd) cmd.MarkFlagRequired(cyargs.AddUseCaseFlag(cmd)) + cyargs.AddStackVersionFlags(cmd) cyargs.AddCloudProviderFlag(cmd) - cyargs.AddComponentStackRefFlag(cmd) + cmd.MarkFlagRequired(cyargs.AddComponentStackRefFlag(cmd)) cyargs.AddStackFormsInputFlags(cmd) cmd.Flags().Bool("update", false, "If the component exists, update it.") return cmd @@ -83,6 +84,12 @@ func createComponent(cmd *cobra.Command, args []string) error { api := common.NewAPI() m := middleware.NewMiddleware(api) + // Get the stack version flags + tag, branch, hash, err := cyargs.GetStackVersionFlags(cmd) + if err != nil { + return errors.Wrap(err, "failed to read stack version flags") + } + p, err := factory.GetPrinter(output) if err != nil { return errors.Wrap(err, "unable to get printer") @@ -115,7 +122,7 @@ func createComponent(cmd *cobra.Command, args []string) error { } // ConfigureComponent will reconfigure the component - componentOutput, err := m.CreateAndConfigureComponent(org, project, env, component, *description, &name, stackRef, useCase, *cloudProvider, inputs) + componentOutput, err := m.CreateAndConfigureComponent(org, project, env, component, *description, name, stackRef, tag, branch, hash, useCase, *cloudProvider, inputs) if err != nil { return printer.SmartPrint(p, nil, err, "failed to configure component '"+component+"'", printer.Options{}, cmd.OutOrStderr()) } @@ -134,7 +141,7 @@ func createComponent(cmd *cobra.Command, args []string) error { return err } - componentOutput, err := m.CreateAndConfigureComponent(org, project, env, component, *description, &name, stackRef, useCase, *cloudProvider, inputs) + componentOutput, err := m.CreateAndConfigureComponent(org, project, env, component, *description, name, stackRef, tag, branch, hash, useCase, *cloudProvider, inputs) if err != nil { return printer.SmartPrint(p, nil, err, "failed to create and configure component '"+component+"'", printer.Options{}, cmd.OutOrStderr()) } diff --git a/cmd/cycloid/components/update.go b/cmd/cycloid/components/update.go index fdec670d..6dda9b70 100644 --- a/cmd/cycloid/components/update.go +++ b/cmd/cycloid/components/update.go @@ -25,9 +25,11 @@ func NewUpdateComponentCommand() *cobra.Command { cyargs.AddNameFlag(cmd) cyargs.AddComponentDescriptionFlag(cmd) cyargs.AddUseCaseFlag(cmd) + cyargs.AddStackVersionFlags(cmd) cyargs.AddStackFormsInputFlags(cmd) cyargs.AddStackRefFlag(cmd) cyargs.AddCloudProviderFlag(cmd) + return cmd } @@ -42,6 +44,11 @@ func updateComponent(cmd *cobra.Command, args []string) error { return err } + if name == "" { + // if name is empty, use the canonical + name = component + } + description, err := cyargs.GetComponentDescription(cmd) if err != nil { return err @@ -90,6 +97,12 @@ func updateComponent(cmd *cobra.Command, args []string) error { useCase = currentComponent.UseCase } + // Get the stack version flags + tag, branch, hash, err := cyargs.GetStackVersionFlags(cmd) + if err != nil { + return errors.Wrap(err, "failed to read stack version flags") + } + var currentConfig = make(models.FormVariables) if currentComponent.IsConfigured { currentConfig, err = m.GetComponentConfig(org, project, env, component) @@ -104,7 +117,7 @@ func updateComponent(cmd *cobra.Command, args []string) error { } // CreateComponent will reconfigure the component if it already exists - updatedComponent, err := m.CreateAndConfigureComponent(org, project, env, component, *description, &name, stackRef, useCase, *cloudProvider, inputs) + updatedComponent, err := m.CreateAndConfigureComponent(org, project, env, component, *description, name, stackRef, tag, branch, hash, useCase, *cloudProvider, inputs) if err != nil { return printer.SmartPrint(p, nil, err, "failed to configure component '"+component+"'", printer.Options{}, cmd.OutOrStderr()) } diff --git a/cmd/cycloid/middleware/component_pipelines_test.go b/cmd/cycloid/middleware/component_pipelines_test.go index ba45fdd4..15f055b9 100644 --- a/cmd/cycloid/middleware/component_pipelines_test.go +++ b/cmd/cycloid/middleware/component_pipelines_test.go @@ -2,17 +2,18 @@ package middleware_test import ( "fmt" - "reflect" "strconv" "testing" "time" + + "github.com/stretchr/testify/require" ) func TestComponentPipeline(t *testing.T) { m := config.Middleware component, err := config.NewTestComponent( - *config.Project.Canonical, *config.Environment.Canonical, t.Name(), config.Org+":"+pipelineTestStackCanonical, pipelineTestStackUseCase, pipelineTestDefaultVars, + *config.Project.Canonical, *config.Environment.Canonical, t.Name(), config.Org+":"+pipelineTestStackCanonical, pipelineTestStackUseCase, "", "", *config.CatalogRepoVersionStacks.CommitHash, pipelineTestDefaultVars, ) if err != nil { t.Errorf("failed to setup base component for test %q: %v", t.Name(), err) @@ -26,9 +27,8 @@ func TestComponentPipeline(t *testing.T) { return } - if !reflect.DeepEqual(*got.Component, *component) { - t.Fatalf("component in pipeline doesn't match, got:\n%v\nexpect: %v", *got.Component, *component) - } + got.Component.Project.Owner = component.Project.Owner + require.Equal(t, *got.Component, *component) }) t.Run("PausePipeline", func(t *testing.T) { @@ -129,7 +129,7 @@ jobs: err = m.AbortBuild(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, *updatedPipeline.Name, *pipelineJobs[0].Name, buildIDStr) if err != nil { - t.Fatalf("failed to abort build '%s': %s", buildIDStr, err) + t.Errorf("failed to abort build '%s': %s", buildIDStr, err) } // // Add a bit of time, concourse seems to not like it @@ -137,7 +137,7 @@ jobs: // // _, err = m.RerunBuild(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, *updatedPipeline.Name, *pipelineJobs[0].Name, buildIDStr) // if err != nil { - // t.Fatalf("failed to re-run build '%s': %s", buildIDStr, err) + // t.Errorf("failed to re-run build '%s': %s", buildIDStr, err) // } }) }) diff --git a/cmd/cycloid/middleware/infra_policies.go b/cmd/cycloid/middleware/infra_policies.go index 65805d09..b4fab2ea 100644 --- a/cmd/cycloid/middleware/infra_policies.go +++ b/cmd/cycloid/middleware/infra_policies.go @@ -44,7 +44,7 @@ func (m *middleware) CreateInfraPolicy(org, policyFile, policyCanonical, descrip // Reads file content and converts it into string policyFileContent, err := os.ReadFile(policyFile) if err != nil { - return nil, fmt.Errorf("unable to read rego file: %v", err) + return nil, fmt.Errorf("unable to read rego file: %w", err) } // If canonical empty,use the default one if policyCanonical == "" { @@ -64,7 +64,7 @@ func (m *middleware) CreateInfraPolicy(org, policyFile, policyCanonical, descrip err = body.Validate(strfmt.Default) if err != nil { - return nil, fmt.Errorf("InfraPolicy invalid: %v", err) + return nil, fmt.Errorf("InfraPolicy invalid: %w", err) } params.SetBody(body) @@ -131,7 +131,7 @@ func (m *middleware) UpdateInfraPolicy(org, infraPolicy, policyFile, description // Reads file content and converts it into string policyFileContent, err := os.ReadFile(policyFile) if err != nil { - return nil, fmt.Errorf("unable to read rego file: %v", err) + return nil, fmt.Errorf("unable to read rego file: %w", err) } policyBody := string(policyFileContent) @@ -146,7 +146,7 @@ func (m *middleware) UpdateInfraPolicy(org, infraPolicy, policyFile, description err = body.Validate(strfmt.Default) if err != nil { - return nil, fmt.Errorf("InfraPolicy invalid: %v", err) + return nil, fmt.Errorf("InfraPolicy invalid: %w", err) } params.SetBody(body) diff --git a/cmd/cycloid/middleware/init_first_org.go b/cmd/cycloid/middleware/init_first_org.go index f40aff74..a5e18a54 100644 --- a/cmd/cycloid/middleware/init_first_org.go +++ b/cmd/cycloid/middleware/init_first_org.go @@ -14,8 +14,8 @@ import ( // current console. // If apiKeyCanonical != nil, will also create an api key admin and add it to a // credential. -func (m *middleware) InitFirstOrg(org, username, fullName, email, password, licence string, apiKeyCanonical *string) (*FirstOrgData, error) { - err := m.UserSignup(username, email, password, fullName) +func (m *middleware) InitFirstOrg(org, userName, fullName, email, password, licence string, apiKeyCanonical *string) (*FirstOrgData, error) { + err := m.UserSignup(userName, email, password, fullName) var signupErr *APIError if errors.As(err, &signupErr) { if signupErr.HTTPCode != "409" && err != nil { @@ -50,7 +50,7 @@ func (m *middleware) InitFirstOrg(org, username, fullName, email, password, lice output := &FirstOrgData{ Org: org, - Username: username, + Username: userName, FullName: fullName, Email: email, Password: password, diff --git a/cmd/cycloid/middleware/middleware.go b/cmd/cycloid/middleware/middleware.go index 0f2d0eb7..266fde0d 100644 --- a/cmd/cycloid/middleware/middleware.go +++ b/cmd/cycloid/middleware/middleware.go @@ -35,7 +35,8 @@ type Middleware interface { GetStack(org, ref string) (*models.ServiceCatalog, error) UpdateStack(org, ref, teamCanonical string, visibility *string) (*models.ServiceCatalog, error) ListStacks(org string) ([]*models.ServiceCatalog, error) - ListStackUseCases(org, ref string) ([]*models.StackUseCase, error) + ListStackUseCases(org, ref, versionTag, versionBranch, versionCommitHash string) ([]*models.StackUseCase, error) + ListStackVersions(org, ref string) ([]*models.ServiceCatalogSourceVersion, error) ListBlueprints(org string) ([]*models.ServiceCatalog, error) CreateStackFromBlueprint(org, blueprintRef, name, stack, catalogRepository, useCase string) (*models.ServiceCatalog, error) @@ -133,16 +134,16 @@ type Middleware interface { DeleteEnv(org, project, env string) error // Component - CreateComponent(org, project, env, component, description string, componentName, serviceCatalogRef *string, cloudProviderCanonical string) (*models.Component, error) + CreateComponent(org, project, env, component, description, componentName, serviceCatalogRef, versionTag, versionBranch, versionCommitHash, cloudProviderCanonical string) (*models.Component, error) UpdateComponent(org, project, env, component, description string, componentName *string) (*models.Component, error) - CreateAndConfigureComponent(org, project, env, component, description string, componentName *string, serviceCatalogRef, useCase, cloudProviderCanonical string, vars models.FormVariables) (*models.Component, error) + CreateAndConfigureComponent(org, project, env, component, description, componentName, serviceCatalogRef, versionTag, versionBranch, versionCommitHash, useCase, cloudProviderCanonical string, vars models.FormVariables) (*models.Component, error) ConfigureComponent(org, project, env, component, useCase string, vars models.FormVariables) error ListComponents(org, project, env string) ([]*models.Component, error) GetComponent(org, project, env, component string) (*models.Component, error) MigrateComponent(org, project, env, component, targetProject, targetEnv, newCanonical, newName string) (*models.Component, error) DeleteComponent(org, project, env, component string) error GetComponentConfig(org, project, env, component string) (models.FormVariables, error) - GetComponentStackConfig(org, project, env, component, useCase string) (models.ServiceCatalogConfigs, error) + GetComponentStackConfig(org, project, env, component, useCase, versionTag, versionBranch, versionCommitHash string) (models.ServiceCatalogConfigs, error) DeleteRole(org, role string) error GetRole(org, role string) (*models.Role, error) @@ -170,7 +171,7 @@ type Middleware interface { CostEstimation(org string, plan []byte) (*models.CostEstimationResult, error) // Extra actions out of the api - InitFirstOrg(org, username, fullName, email, password, licence string, apiKeyCanonical *string) (*FirstOrgData, error) + InitFirstOrg(org, userName, fullName, email, password, licence string, apiKeyCanonical *string) (*FirstOrgData, error) } type FirstOrgData struct { diff --git a/cmd/cycloid/middleware/middleware_test.go b/cmd/cycloid/middleware/middleware_test.go index 284e2825..3dbba5e8 100644 --- a/cmd/cycloid/middleware/middleware_test.go +++ b/cmd/cycloid/middleware/middleware_test.go @@ -20,7 +20,7 @@ func runMain(ctx context.Context, main *testing.M) (int, error) { config, err = testcfg.NewConfig("middleware") defer config.Cleanup() if err != nil { - return 1, fmt.Errorf("Config setup failed for package middleware: %v", err) + return 1, fmt.Errorf("config setup failed for package middleware: %w", err) } os.Setenv("CY_API_URL", config.APIUrl) diff --git a/cmd/cycloid/middleware/organization_api_key.go b/cmd/cycloid/middleware/organization_api_key.go index 33141acb..c9385d1c 100644 --- a/cmd/cycloid/middleware/organization_api_key.go +++ b/cmd/cycloid/middleware/organization_api_key.go @@ -57,7 +57,7 @@ func (m *middleware) CreateAPIKey(org, canonical, description, owner string, nam err := body.Validate(strfmt.Default) if err != nil { - return nil, fmt.Errorf("invalid body for createAPIKey: %v", err) + return nil, fmt.Errorf("invalid body for createAPIKey: %w", err) } params.SetBody(&body) diff --git a/cmd/cycloid/middleware/organization_components.go b/cmd/cycloid/middleware/organization_components.go index cdacbe97..b91f32ae 100644 --- a/cmd/cycloid/middleware/organization_components.go +++ b/cmd/cycloid/middleware/organization_components.go @@ -7,6 +7,7 @@ import ( "github.com/cycloidio/cycloid-cli/client/client/organization_components" "github.com/cycloidio/cycloid-cli/client/models" + "github.com/cycloidio/cycloid-cli/internal/ptr" ) func (m *middleware) GetComponentConfig(org, project, env, component string) (models.FormVariables, error) { @@ -59,23 +60,30 @@ func (m *middleware) ListComponents(org, project, env string) ([]*models.Compone return payload.Data, nil } -func (m *middleware) CreateComponent(org, project, env, component, description string, componentName, serviceCatalogRef *string, cloudProviderCanonical string) (*models.Component, error) { +func (m *middleware) CreateComponent(org, project, env, component, description, componentName, serviceCatalogRef, versionTag, versionBranch, versionCommitHash, cloudProviderCanonical string) (*models.Component, error) { + // Resolve version parameters to ID + versionID, _, err := m.resolveStackVersion(org, serviceCatalogRef, versionTag, versionBranch, versionCommitHash) + if err != nil { + return nil, err + } + params := organization_components.NewCreateComponentParams() params.WithOrganizationCanonical(org) params.WithProjectCanonical(project) params.WithEnvironmentCanonical(env) body := &models.NewComponent{ - Name: componentName, - Canonical: component, - Description: description, - ServiceCatalogRef: serviceCatalogRef, - CloudProviderCanonical: cloudProviderCanonical, + Name: ptr.Ptr(componentName), + Canonical: component, + Description: description, + ServiceCatalogRef: ptr.Ptr(serviceCatalogRef), + CloudProviderCanonical: cloudProviderCanonical, + ServiceCatalogSourceVersionID: ptr.Ptr(versionID), } - err := body.Validate(strfmt.Default) + err = body.Validate(strfmt.Default) if err != nil { - return nil, fmt.Errorf("createComponent parameter validation failed, body:\n%v\nerr: %v", body, err) + return nil, fmt.Errorf("createComponent parameter validation failed, body:\n%v\nerr: %w", body, err) } params.WithBody(body) @@ -89,25 +97,33 @@ func (m *middleware) CreateComponent(org, project, env, component, description s return payload.Data, nil } -func (m *middleware) CreateAndConfigureComponent(org, project, env, component, description string, componentName *string, serviceCatalogRef, useCase, cloudProviderCanonical string, vars models.FormVariables) (*models.Component, error) { +func (m *middleware) CreateAndConfigureComponent(org, project, env, component, description, componentName, serviceCatalogRef, versionTag, versionBranch, versionCommitHash, useCase, cloudProviderCanonical string, vars models.FormVariables) (*models.Component, error) { + // Resolve version parameters to ID and commit hash + versionID, commitHash, err := m.resolveStackVersion(org, serviceCatalogRef, versionTag, versionBranch, versionCommitHash) + if err != nil { + return nil, err + } + params := organization_components.NewCreateAndConfigureComponentParams() params.WithOrganizationCanonical(org) params.WithProjectCanonical(project) params.WithEnvironmentCanonical(env) body := &models.NewAndConfiguredComponent{ - Name: componentName, - Canonical: component, - Description: description, - ServiceCatalogRef: serviceCatalogRef, - UseCase: useCase, - Vars: vars, - CloudProviderCanonical: cloudProviderCanonical, + Canonical: component, + CloudProviderCanonical: cloudProviderCanonical, + Description: description, + Name: ptr.Ptr(componentName), + ServiceCatalogRef: serviceCatalogRef, + ServiceCatalogSourceVersionCommitHash: ptr.Ptr(commitHash), + ServiceCatalogSourceVersionID: ptr.Ptr(versionID), + UseCase: useCase, + Vars: vars, } - err := body.Validate(strfmt.Default) + err = body.Validate(strfmt.Default) if err != nil { - return nil, fmt.Errorf("createAndConfigureComponent body validation failed, body:\n%v\nerr: %v", body, err) + return nil, fmt.Errorf("createAndConfigureComponent body validation failed, body:\n%v\nerr: %w", body, err) } params.WithBody(body) @@ -120,7 +136,6 @@ func (m *middleware) CreateAndConfigureComponent(org, project, env, component, d payload := resp.GetPayload() return payload.Data, nil - } func (m *middleware) UpdateComponent(org, project, env, component, description string, componentName *string) (*models.Component, error) { @@ -137,7 +152,7 @@ func (m *middleware) UpdateComponent(org, project, env, component, description s err := body.Validate(strfmt.Default) if err != nil { - return nil, fmt.Errorf("updateComponent parameter validation failed, body:\n%v\nerr: %v", body, err) + return nil, fmt.Errorf("updateComponent parameter validation failed, body:\n%v\nerr: %w", body, err) } params.WithBody(body) @@ -212,13 +227,29 @@ func (m *middleware) DeleteComponent(org, project, env, component string) error return nil } -func (m *middleware) GetComponentStackConfig(org, project, env, component, useCase string) (models.ServiceCatalogConfigs, error) { +func (m *middleware) GetComponentStackConfig(org, project, env, component, useCase, versionTag, versionBranch, versionCommitHash string) (models.ServiceCatalogConfigs, error) { + // Need to get component to determine stack ref + comp, err := m.GetComponent(org, project, env, component) + if err != nil { + return nil, err + } + + stackRef := *comp.ServiceCatalog.Ref + + // Resolve version parameters to ID and commit hash + versionID, commitHash, err := m.resolveStackVersion(org, stackRef, versionTag, versionBranch, versionCommitHash) + if err != nil { + return nil, err + } + params := organization_components.NewGetComponentStackConfigurationParams() params.SetOrganizationCanonical(org) params.SetProjectCanonical(project) params.SetEnvironmentCanonical(env) params.SetComponentCanonical(component) params.SetUseCase(&useCase) + params.SetServiceCatalogSourceVersionCommitHash(commitHash) + params.SetServiceCatalogSourceVersionID(versionID) resp, err := m.api.OrganizationComponents.GetComponentStackConfiguration(params, m.api.Credentials(&org)) if err != nil { diff --git a/cmd/cycloid/middleware/organization_components_test.go b/cmd/cycloid/middleware/organization_components_test.go index 8297f637..a084e2e3 100644 --- a/cmd/cycloid/middleware/organization_components_test.go +++ b/cmd/cycloid/middleware/organization_components_test.go @@ -34,7 +34,7 @@ func TestComponentCRUD(t *testing.T) { // // createdProject, err := m.CreateProject(config.Org, projectName, project, description, configRepository, owner, team, color, icon) // if err != nil { - // t.Fatalf("Failed to create pre-requisite project, create project CRUD tests: %v", err) + // t.Errorf("Failed to create pre-requisite project, create project CRUD tests: %v", err) // } // // var ( @@ -53,7 +53,7 @@ func TestComponentCRUD(t *testing.T) { // // _, err = m.CreateEnv(config.Org, *createdProject.Canonical, env, envName, envColor) // if err != nil { - // t.Fatalf("Failed to create env '%s': %v", env, err) + // t.Errorf("Failed to create env '%s': %v", env, err) // } // end setup @@ -133,9 +133,7 @@ func TestComponentCRUD(t *testing.T) { break } - createdComponent, err = m.CreateAndConfigureComponent( - config.Org, *config.Project.Canonical, *config.Environment.Canonical, component, componentDescription, &componentName, stackRef, useCase, "", *formVars, - ) + createdComponent, err = m.CreateAndConfigureComponent(config.Org, *config.Project.Canonical, *config.Environment.Canonical, component, componentDescription, componentName, stackRef, "", "", "", useCase, "", *formVars) if err != nil { errList = errors.Join(errList, err) continue @@ -146,7 +144,7 @@ func TestComponentCRUD(t *testing.T) { } if errList != nil { - t.Fatalf("Failed to create component '%s':\n%v", component, err) + t.Errorf("Failed to create component '%s':\n%v", component, err) } defer func() { @@ -163,7 +161,7 @@ func TestComponentCRUD(t *testing.T) { ) errList, err = nil, nil for range 3 { - _, err = m.CreateAndConfigureComponent(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *createdComponent.Canonical, newDescription, &newComponentName, stackRef, useCase, "", newVar) + _, err = m.CreateAndConfigureComponent(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *createdComponent.Canonical, newDescription, newComponentName, stackRef, "", "", *config.CatalogRepoVersionStacks.CommitHash, useCase, "", newVar) if err != nil { errList = errors.Join(errList, err) continue @@ -173,7 +171,7 @@ func TestComponentCRUD(t *testing.T) { break } if errList != nil { - t.Fatalf("Failed to update component '%s':\n%v", *createdComponent.Canonical, err) + t.Errorf("Failed to update component '%s':\n%v", *createdComponent.Canonical, err) } // TODO: Fix after issue: https://linear.app/cycloid/issue/BE-801/invalid-response-for-updatecomponent @@ -185,6 +183,6 @@ func TestComponentCRUD(t *testing.T) { _, err := m.ListComponents(config.Org, *config.Project.Canonical, *config.Environment.Canonical) if err != nil { - t.Fatalf("Failed to list components in project '%s':\n%v", *config.Project.Canonical, err) + t.Errorf("Failed to list components in project '%s':\n%v", *config.Project.Canonical, err) } } diff --git a/cmd/cycloid/middleware/organization_forms_test.go b/cmd/cycloid/middleware/organization_forms_test.go index 3a3a4ac3..e577b990 100644 --- a/cmd/cycloid/middleware/organization_forms_test.go +++ b/cmd/cycloid/middleware/organization_forms_test.go @@ -33,6 +33,6 @@ func TestValidateFormYamlAnchors(t *testing.T) { _, err := m.ValidateForm(org, rawForms) if err != nil { - t.Fatalf("Using yaml anchor should not error:\nerr: '%s'\nyaml files: '%v'", err, rawForms) + t.Errorf("Using yaml anchor should not error:\nerr: '%s'\nyaml files: '%v'", err, rawForms) } } diff --git a/cmd/cycloid/middleware/organization_pipelines_test.go b/cmd/cycloid/middleware/organization_pipelines_test.go index b8b31a5d..6a13742f 100644 --- a/cmd/cycloid/middleware/organization_pipelines_test.go +++ b/cmd/cycloid/middleware/organization_pipelines_test.go @@ -31,6 +31,6 @@ func TestGetOrgPipelines(t *testing.T) { }) if index == -1 { - t.Fatalf("failed to find created component in the list: %v\nexpected component: %v", litter.Sdump(got), litter.Sdump(config.Component)) + t.Errorf("failed to find created component in the list: %v\nexpected component: %v", litter.Sdump(got), litter.Sdump(config.Component)) } } diff --git a/cmd/cycloid/middleware/organization_project_environment_test.go b/cmd/cycloid/middleware/organization_project_environment_test.go index 3c373015..70ca9608 100644 --- a/cmd/cycloid/middleware/organization_project_environment_test.go +++ b/cmd/cycloid/middleware/organization_project_environment_test.go @@ -34,7 +34,7 @@ func TestEnvCrud(t *testing.T) { createdProject, err := m.CreateProject(config.Org, projectName, project, description, configRepository, owner, team, color, icon) if err != nil { - t.Fatalf("Failed to create pre-requisite project, create project CRUD tests: %v", err) + t.Errorf("Failed to create pre-requisite project, create project CRUD tests: %v", err) } // end setup @@ -47,7 +47,7 @@ func TestEnvCrud(t *testing.T) { // create createdEnv, err := m.CreateEnv(config.Org, *createdProject.Canonical, env, envName, envColor) if err != nil { - t.Fatalf("Failed to create env '%s': %v", env, err) + t.Errorf("Failed to create env '%s': %v", env, err) } // delete @@ -67,7 +67,7 @@ func TestEnvCrud(t *testing.T) { updatedEnv, err := m.UpdateEnv(config.Org, *createdProject.Canonical, *createdEnv.Canonical, newEnvName, newEnvColor) if err != nil { - t.Fatalf("Failed to update env '%s':\n%v", env, err) + t.Errorf("Failed to update env '%s':\n%v", env, err) } assert.Equal(t, newEnvName, updatedEnv.Name) diff --git a/cmd/cycloid/middleware/organization_projects_test.go b/cmd/cycloid/middleware/organization_projects_test.go index 95c221c9..2fd339cb 100644 --- a/cmd/cycloid/middleware/organization_projects_test.go +++ b/cmd/cycloid/middleware/organization_projects_test.go @@ -23,18 +23,18 @@ func TestProjectCrud(t *testing.T) { createProjet, err := m.CreateProject(config.Org, projectName, project, description, *config.ConfigRepo.Canonical, owner, team, color, icon) if err != nil { - t.Fatalf("Failed to create project '%s': %v", project, err) + t.Errorf("Failed to create project '%s': %v", project, err) } _, err = m.GetProject(config.Org, *createProjet.Canonical) if err != nil { - t.Fatalf("Did not found create project '%s' with get request: %v", *createProjet.Canonical, err) + t.Errorf("Did not found create project '%s' with get request: %v", *createProjet.Canonical, err) } defer func() { err := m.DeleteProject(config.Org, project) if err != nil { - t.Fatalf("Failed to delete project '%s': %v", project, err) + t.Errorf("Failed to delete project '%s': %v", project, err) } }() @@ -50,7 +50,7 @@ func TestProjectCrud(t *testing.T) { owner, team, newColor, newIcon, "aws", ) if err != nil { - t.Fatalf("Failed to update project '%s': %v", project, err) + t.Errorf("Failed to update project '%s': %v", project, err) } assert.Equal(t, newName, *updatedProject.Name) diff --git a/cmd/cycloid/middleware/organization_test.go b/cmd/cycloid/middleware/organization_test.go index f7df8e26..2a115db5 100644 --- a/cmd/cycloid/middleware/organization_test.go +++ b/cmd/cycloid/middleware/organization_test.go @@ -10,7 +10,7 @@ func TestChildOrgCrud(t *testing.T) { // config, err := testcfg.NewConfig() // defer config.Cleanup() // if err != nil { - // t.Fatalf("Config setup failed: %v", err) + // t.Errorf("Config setup failed: %v", err) // } m := config.Middleware @@ -25,23 +25,23 @@ func TestChildOrgCrud(t *testing.T) { _, err := m.CreateOrganizationChild(config.Org, childOrg, nil) if err != nil { - t.Fatalf("Failed to create org '%s': %v", childOrg, err) + t.Errorf("Failed to create org '%s': %v", childOrg, err) return } var newName = "test-update-child-org" newOrg, err := m.UpdateOrganization(childOrg, newName) if err != nil { - t.Fatalf("Failed to update org '%s': %v", childOrg, err) + t.Errorf("Failed to update org '%s': %v", childOrg, err) } if *newOrg.Name != newName { - t.Fatalf("Update org failed.\nExpected: %s | Got: %s", newName, *newOrg.Name) + t.Errorf("Update org failed.\nExpected: %s | Got: %s", newName, *newOrg.Name) } _, err = m.GetOrganization(childOrg) if err != nil { - t.Fatalf("Org '%s' is not created: %v", childOrg, err) + t.Errorf("Org '%s' is not created: %v", childOrg, err) return } } diff --git a/cmd/cycloid/middleware/project_pipelines_test.go b/cmd/cycloid/middleware/project_pipelines_test.go index 59da08b6..c8c31458 100644 --- a/cmd/cycloid/middleware/project_pipelines_test.go +++ b/cmd/cycloid/middleware/project_pipelines_test.go @@ -23,6 +23,6 @@ func TestGetProjectPipelines(t *testing.T) { }) if index == -1 { - t.Fatalf("failed to find created component in the list: %v\nexpected component: %v", litter.Sdump(got), litter.Sdump(config.Component)) + t.Errorf("failed to find created component in the list: %v\nexpected component: %v", litter.Sdump(got), litter.Sdump(config.Component)) } } diff --git a/cmd/cycloid/middleware/stacks.go b/cmd/cycloid/middleware/stacks.go index 4670c0d7..a75cdd24 100644 --- a/cmd/cycloid/middleware/stacks.go +++ b/cmd/cycloid/middleware/stacks.go @@ -11,6 +11,7 @@ import ( "github.com/cycloidio/cycloid-cli/client/client/service_catalogs" "github.com/cycloidio/cycloid-cli/client/models" + "github.com/cycloidio/cycloid-cli/internal/ptr" ) func (m *middleware) GetStack(org, ref string) (*models.ServiceCatalog, error) { @@ -42,10 +43,70 @@ func (m *middleware) ListStacks(org string) ([]*models.ServiceCatalog, error) { return payload.Data, nil } -func (m *middleware) ListStackUseCases(org, ref string) ([]*models.StackUseCase, error) { +// resolveStackVersion resolves versionTag/versionBranch/versionCommitHash to version ID and commit hash. +// Priority: tag > branch > commitHash (whichever is provided first) +// If all parameters are empty, uses the default catalog version (latest tag or branch HEAD). +func (m *middleware) resolveStackVersion(org, stackRef, versionTag, versionBranch, versionCommitHash string) (versionID uint32, commitHash string, err error) { + // If all are empty, use default version + if versionTag == "" && versionBranch == "" && versionCommitHash == "" { + defaultVersion, err := m.getDefaultCatalogVersion(org, stackRef) + if err != nil { + return 0, "", fmt.Errorf("failed to get default stack version: %w", err) + } + if defaultVersion == nil || defaultVersion.ID == nil || defaultVersion.CommitHash == nil { + return 0, "", errors.New("no stack catalog version found") + } + return *defaultVersion.ID, *defaultVersion.CommitHash, nil + } + + // List all versions for the stack + versions, err := m.ListStackVersions(org, stackRef) + if err != nil { + return 0, "", fmt.Errorf("failed to list stack versions: %w", err) + } + + // Priority 1: tag + if versionTag != "" { + for _, version := range versions { + if ptr.Value(version.Type) == "tag" && + ptr.Value(version.Name) == versionTag { + return *version.ID, *version.CommitHash, nil + } + } + return 0, "", fmt.Errorf("stack version tag %q not found", versionTag) + } + + // Priority 2: branch + if versionBranch != "" { + for _, version := range versions { + if ptr.Value(version.Type) == "branch" && + ptr.Value(version.Name) == versionBranch { + return *version.ID, *version.CommitHash, nil + } + } + return 0, "", fmt.Errorf("stack version branch %q not found", versionBranch) + } + + // Priority 3: commit hash + for _, version := range versions { + if ptr.Value(version.CommitHash) == versionCommitHash { + return *version.ID, *version.CommitHash, nil + } + } + return 0, "", fmt.Errorf("stack version commit hash %q not found", versionCommitHash) +} + +func (m *middleware) ListStackUseCases(org, ref, versionTag, versionBranch, versionCommitHash string) ([]*models.StackUseCase, error) { + // Resolve version parameters to ID + versionID, _, err := m.resolveStackVersion(org, ref, versionTag, versionBranch, versionCommitHash) + if err != nil { + return nil, err + } + params := service_catalogs.NewGetServiceCatalogUseCasesParams() params.SetOrganizationCanonical(org) params.SetServiceCatalogRef(ref) + params.SetServiceCatalogSourceVersionID(versionID) resp, err := m.api.ServiceCatalogs.GetServiceCatalogUseCases(params, m.api.Credentials(&org)) if err != nil { @@ -57,6 +118,71 @@ func (m *middleware) ListStackUseCases(org, ref string) ([]*models.StackUseCase, return payload.Data, nil } +func (m *middleware) ListStackVersions(org, ref string) ([]*models.ServiceCatalogSourceVersion, error) { + params := service_catalogs.NewGetServiceCatalogVersionsParams() + params.SetOrganizationCanonical(org) + params.SetServiceCatalogRef(ref) + + resp, err := m.api.ServiceCatalogs.GetServiceCatalogVersions(params, m.api.Credentials(&org)) + if err != nil { + return nil, NewAPIError(err) + } + + payload := resp.GetPayload() + + return payload.Data, nil +} + +// getDefaultCatalogVersion returns the default catalog version for a stack based on priority: +// 1. If a version with is_latest=true and type="tag" exists, use that +// 2. Otherwise, use the latest commit of the branch of the catalog repository of the stack +func (m *middleware) getDefaultCatalogVersion(org, ref string) (*models.ServiceCatalogSourceVersion, error) { + stack, err := m.GetStack(org, ref) + if err != nil { + return nil, err + } + + var catalogRepoBranch string + if stack.ServiceCatalogSourceCanonical != "" { + catalogRepo, err := m.GetCatalogRepository(org, stack.ServiceCatalogSourceCanonical) + if err != nil { + return nil, err + } + catalogRepoBranch = catalogRepo.Branch + } + + versions, err := m.ListStackVersions(org, ref) + if err != nil { + return nil, err + } + + var branchVersion *models.ServiceCatalogSourceVersion + + // Look for latest tag or the stack's branch latest commit + for _, version := range versions { + // Priority 1: is_latest tag (must be a tag, not a branch) + if ptr.Value(version.IsLatest) && + ptr.Value(version.Type) == "tag" { + return version, nil + } + + // Collect the version matching the stack's catalog repository branch + if ptr.Value(version.Type) == "branch" && + ptr.Value(version.Name) == catalogRepoBranch { + // Keep track of this branch version (should be the latest commit) + branchVersion = version + } + } + + // Priority 2: latest commit of the catalog repository branch + if branchVersion != nil { + return branchVersion, nil + } + + // No default found + return nil, nil +} + // ListBlueprints will list stacks that are flagged as blueprint. Uses the same route as ListStack. // TODO: Merge this route with ListStack once we find a way to add LHS filter params to the client. func (m *middleware) ListBlueprints(org string) ([]*models.ServiceCatalog, error) { diff --git a/cmd/cycloid/middleware/stacks_test.go b/cmd/cycloid/middleware/stacks_test.go new file mode 100644 index 00000000..022f8168 --- /dev/null +++ b/cmd/cycloid/middleware/stacks_test.go @@ -0,0 +1,227 @@ +package middleware_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cycloidio/cycloid-cli/internal/ptr" +) + +const ( + testStackCanonical = "stack-e2e-stackforms" + testStackRef = "cycloid:stack-e2e-stackforms" + testStackUseCase = "default" +) + +func TestStacksGetStack(t *testing.T) { + m := config.Middleware + t.Run("GetStackOk", func(t *testing.T) { + stack, err := m.GetStack(config.Org, testStackRef) + require.NoError(t, err) + require.NotNil(t, stack) + assert.Equal(t, testStackCanonical, *stack.Canonical) + assert.NotNil(t, stack.Ref) + assert.Equal(t, testStackRef, *stack.Ref) + }) + t.Run("GetStackNotFound", func(t *testing.T) { + _, err := m.GetStack(config.Org, "org:nonexistent-stack") + require.Error(t, err) + assert.Contains(t, err.Error(), "404") + }) +} +func TestStacksListStacks(t *testing.T) { + m := config.Middleware + t.Run("ListStacksOk", func(t *testing.T) { + stacks, err := m.ListStacks(config.Org) + require.NoError(t, err) + require.NotNil(t, stacks) + assert.NotEmpty(t, stacks, "should have at least one stack") + // Verify the test stack is in the list + found := false + for _, stack := range stacks { + if stack.Canonical != nil && *stack.Canonical == testStackCanonical { + found = true + assert.Equal(t, testStackRef, *stack.Ref) + break + } + } + assert.True(t, found, "test stack should be in the list") + }) +} +func TestStacksListStackVersions(t *testing.T) { + m := config.Middleware + t.Run("ListStackVersionsOk", func(t *testing.T) { + versions, err := m.ListStackVersions(config.Org, testStackRef) + require.NoError(t, err) + require.NotNil(t, versions) + assert.NotEmpty(t, versions, "should have at least one version") + // Verify all versions have required fields + for _, version := range versions { + assert.NotNil(t, version.ID, "version should have an ID") + assert.NotNil(t, version.CommitHash, "version should have a commit hash") + assert.NotNil(t, version.Type, "version should have a type") + assert.NotNil(t, version.Name, "version should have a name") + } + }) + t.Run("ListStackVersionsNotFound", func(t *testing.T) { + _, err := m.ListStackVersions(config.Org, "org:nonexistent-stack") + require.Error(t, err) + }) +} +func TestStacksListStackUseCases(t *testing.T) { + m := config.Middleware + t.Run("ListStackUseCasesWithDefaultVersion", func(t *testing.T) { + // When all version params are empty, should use default version + useCases, err := m.ListStackUseCases(config.Org, testStackRef, "", "", "") + require.NoError(t, err) + require.NotNil(t, useCases) + assert.NotEmpty(t, useCases, "should have at least one use case") + found := false + for _, uc := range useCases { + if uc.UseCase != nil && *uc.UseCase == testStackUseCase { + found = true + assert.NotNil(t, uc.Name, "use case should have a name") + break + } + } + assert.True(t, found, "default use case should be in the list") + }) + t.Run("ListStackUseCasesWithCommitHash", func(t *testing.T) { + // First, get a valid commit hash. We'll use commit hash from the stacks + // branch version to ensure we're getting use cases + versions, err := m.ListStackVersions(config.Org, testStackRef) + require.NoError(t, err) + require.NotEmpty(t, versions) + var commitHash string + for _, version := range versions { + if version.Type != nil && *version.Type == "branch" && version.Name != nil && *version.Name == "stacks" { + commitHash = *version.CommitHash + break + } + } + // Use the commit hash to list use cases + useCases, err := m.ListStackUseCases(config.Org, testStackRef, "", "", commitHash) + require.NoError(t, err) + require.NotNil(t, useCases) + assert.NotEmpty(t, useCases, "should have at least one use case") + }) + t.Run("ListStackUseCasesWithTag", func(t *testing.T) { + versions, err := m.ListStackVersions(config.Org, testStackRef) + require.NoError(t, err) + require.NotEmpty(t, versions) + + useCases, err := m.ListStackUseCases(config.Org, testStackRef, "stack-e2e-stackforms/v1", "", "") + require.NoError(t, err) + require.NotNil(t, useCases) + assert.NotEmpty(t, useCases, "should have at least one use case") + }) + t.Run("ListStackUseCasesWithStacksBranch", func(t *testing.T) { + // Use the branch to list use cases + useCases, err := m.ListStackUseCases(config.Org, testStackRef, "", "stacks", "") + require.NoError(t, err) + require.NotNil(t, useCases) + assert.NotEmpty(t, useCases, "should have at least one use case") + }) + t.Run("ListStackUseCasesTagNotFound", func(t *testing.T) { + _, err := m.ListStackUseCases(config.Org, testStackRef, "v999.999.999", "", "") + require.Error(t, err) + assert.Contains(t, err.Error(), "not found") + }) + t.Run("ListStackUseCasesBranchNotFound", func(t *testing.T) { + _, err := m.ListStackUseCases(config.Org, testStackRef, "", "nonexistent-branch-xyz", "") + require.Error(t, err) + assert.Contains(t, err.Error(), "not found") + }) + t.Run("ListStackUseCasesCommitHashNotFound", func(t *testing.T) { + _, err := m.ListStackUseCases(config.Org, testStackRef, "", "", "0000000000000000000000000000000000000000") + require.Error(t, err) + assert.Contains(t, err.Error(), "not found") + }) + t.Run("ListStackUseCasesStackNotFound", func(t *testing.T) { + _, err := m.ListStackUseCases(config.Org, "org:nonexistent-stack", "", "", "") + require.Error(t, err) + }) +} +func TestStacksUpdateStack(t *testing.T) { + m := config.Middleware + t.Run("UpdateStackVisibility", func(t *testing.T) { + stack, err := m.GetStack(config.Org, testStackRef) + require.NoError(t, err) + originalVisibility := stack.Visibility + teamCanonical := "" + if stack.Team != nil && stack.Team.Canonical != nil { + teamCanonical = *stack.Team.Canonical + } + // Toggle visibility + newVisibility := "local" + if originalVisibility != nil && *originalVisibility == "local" { + newVisibility = "shared" + } + updatedStack, err := m.UpdateStack(config.Org, testStackRef, teamCanonical, ptr.Ptr(newVisibility)) + require.NoError(t, err) + require.NotNil(t, updatedStack) + assert.Equal(t, newVisibility, *updatedStack.Visibility) + + _, err = m.UpdateStack(config.Org, testStackRef, teamCanonical, originalVisibility) + require.NoError(t, err) + }) + t.Run("UpdateStackNotFound", func(t *testing.T) { + _, err := m.UpdateStack(config.Org, "org:nonexistent-stack", "", ptr.Ptr("private")) + require.Error(t, err) + }) +} + +func TestResolveStackVersionIntegration(t *testing.T) { + // These tests verify that resolveStackVersion works correctly through the public method ListStackUseCases + + m := config.Middleware + t.Run("ResolveDefaultVersionThroughListStackUseCases", func(t *testing.T) { + // When no version is specified, should use default version + useCases1, err1 := m.ListStackUseCases(config.Org, testStackRef, "", "", "") + require.NoError(t, err1) + require.NotEmpty(t, useCases1) + // Should return the same use cases each time with default version + useCases2, err2 := m.ListStackUseCases(config.Org, testStackRef, "", "", "") + require.NoError(t, err2) + require.NotEmpty(t, useCases2) + assert.Equal(t, len(useCases1), len(useCases2), "default version should be consistent") + }) + t.Run("ResolveCommitHashThroughListStackUseCases", func(t *testing.T) { + versions, err := m.ListStackVersions(config.Org, testStackRef) + require.NoError(t, err) + require.NotEmpty(t, versions) + commitHash := *versions[0].CommitHash + useCases, err := m.ListStackUseCases(config.Org, testStackRef, "", "", commitHash) + require.NoError(t, err) + require.NotEmpty(t, useCases) + }) + t.Run("PriorityTagOverBranchOverCommitHash", func(t *testing.T) { + versions, err := m.ListStackVersions(config.Org, testStackRef) + require.NoError(t, err) + require.NotEmpty(t, versions) + var commitHash string + // Make sure commit hash is from the stacks branch + for _, version := range versions { + if version.Type != nil && *version.Type == "branch" && version.Name != nil && *version.Name == "stacks" { + commitHash = *version.CommitHash + break + } + } + // If we have a tag, it should be used + useCases, err := m.ListStackUseCases(config.Org, testStackRef, "stack-e2e-stackforms/v1", "", "") + require.NoError(t, err) + require.NotEmpty(t, useCases) + + // If we have a branch, it should be used + useCases, err = m.ListStackUseCases(config.Org, testStackRef, "", "stacks", "") + require.NoError(t, err) + require.NotEmpty(t, useCases) + + // If we have a commit hash, it should be used + useCases, err = m.ListStackUseCases(config.Org, testStackRef, "", "", commitHash) + require.NoError(t, err) + require.NotEmpty(t, useCases) + }) +} diff --git a/cmd/cycloid/middleware/user.go b/cmd/cycloid/middleware/user.go index 2db0212d..44f92928 100644 --- a/cmd/cycloid/middleware/user.go +++ b/cmd/cycloid/middleware/user.go @@ -11,16 +11,12 @@ import ( func (m *middleware) UserSignup(username, email, password, fullName string) error { params := user.NewSignUpParams() body := &models.NewUserAccount{ + Username: username, Email: (*strfmt.Email)(&email), Password: (*strfmt.Password)(&password), FullName: &fullName, } - // Username is optional - if username != "" { - body.Username = username - } - params.WithBody(body) _, err := m.api.User.SignUp(params) diff --git a/cmd/cycloid/stacks/get_config.go b/cmd/cycloid/stacks/get_config.go index 4f073671..feec1722 100644 --- a/cmd/cycloid/stacks/get_config.go +++ b/cmd/cycloid/stacks/get_config.go @@ -25,6 +25,7 @@ cy --org my-org stacks get-config -p my-project -e my-env -c my-component my-use Args: cobra.RangeArgs(0, 2), } cyargs.AddUseCaseFlag(cmd) + cyargs.AddStackVersionFlags(cmd) return cmd } @@ -78,7 +79,13 @@ func getConfig(cmd *cobra.Command, args []string) error { api := common.NewAPI() m := middleware.NewMiddleware(api) - stackConfigs, err := m.GetComponentStackConfig(org, proj, env, component, useCase) + // Get the stack version flags + tag, branch, hash, err := cyargs.GetStackVersionFlags(cmd) + if err != nil { + return errors.Wrap(err, "failed to read stack version flags") + } + + stackConfigs, err := m.GetComponentStackConfig(org, proj, env, component, useCase, tag, branch, hash) if err != nil { return printer.SmartPrint(p, nil, err, "unable to get the stack configuration", printer.Options{}, cmd.OutOrStderr()) } diff --git a/cmd/cycloid/stacks/list.go b/cmd/cycloid/stacks/list.go index edd1d0c8..dc66beee 100644 --- a/cmd/cycloid/stacks/list.go +++ b/cmd/cycloid/stacks/list.go @@ -90,7 +90,8 @@ func list(cmd *cobra.Command, args []string) error { } if stack.Ref != nil { - stackUseCases, err := m.ListStackUseCases(org, *stack.Ref) + // Pass empty version flags to use default/latest version + stackUseCases, err := m.ListStackUseCases(org, *stack.Ref, "", "", "") if err != nil { fmt.Fprintf(cmd.OutOrStderr(), "error: failed to fetch use cases for blueprint '%s': %s\n", *stack.Ref, err.Error()) continue diff --git a/e2e/api_keys_test.go b/e2e/api_keys_test.go index 1f75bd26..f8e9d0cb 100644 --- a/e2e/api_keys_test.go +++ b/e2e/api_keys_test.go @@ -27,7 +27,7 @@ func TestAPIKeysCmd(t *testing.T) { } createOut, createErr := executeCommand(args) if createErr != nil { - t.Fatalf("failed to create api key admin: %s", createErr) + t.Errorf("failed to create api key admin: %s", createErr) } defer t.Run("DeleteAPIKeyOk", func(t *testing.T) { @@ -39,13 +39,13 @@ func TestAPIKeysCmd(t *testing.T) { } _, deleteErr := executeCommand(args) if deleteErr != nil { - t.Fatalf("failed to delete api key admin: %s", deleteErr) + t.Errorf("failed to delete api key admin: %s", deleteErr) } }) err := json.Unmarshal([]byte(createOut), &createdAPIKey) if err != nil { - t.Fatalf("CLI output can't be serialize to models.APIKey, out:\n%s\nerr:\n%s", createOut, err) + t.Errorf("CLI output can't be serialize to models.APIKey, out:\n%s\nerr:\n%s", createOut, err) } assert.Equal(t, *createdAPIKey.Canonical, testKeyCanonical) @@ -59,18 +59,18 @@ func TestAPIKeysCmd(t *testing.T) { } listOut, listErr := executeCommand(args) if listErr != nil { - t.Fatalf("failed to list api keys: %s", listErr) + t.Errorf("failed to list api keys: %s", listErr) } err := json.Unmarshal([]byte(listOut), &APIKeyList) if err != nil { - t.Fatalf("failed to parse cli output as list of api keys, out: %s\nerr: %s", listOut, err) + t.Errorf("failed to parse cli output as list of api keys, out: %s\nerr: %s", listOut, err) } if index := slices.IndexFunc(APIKeyList, func(a *models.APIKey) bool { return *a.Canonical == testKeyCanonical }); index == -1 { - t.Fatalf("failed to find the API key with can '%s' in list: %s", testKeyCanonical, litter.Sdump(APIKeyList)) + t.Errorf("failed to find the API key with can '%s' in list: %s", testKeyCanonical, litter.Sdump(APIKeyList)) } }) }) diff --git a/e2e/components_test.go b/e2e/components_test.go index 348e1d91..a0bc4f49 100644 --- a/e2e/components_test.go +++ b/e2e/components_test.go @@ -28,7 +28,7 @@ func TestComponentCmd(t *testing.T) { testJSONStdin := `{"types": {"tests": {"array": ["hello", false, 1, 1.1]}}}` filename, err := WriteTempFile(testJSONFileContent) if err != nil { - t.Fatalf("comp create setup failed: %v", err) + t.Errorf("comp create setup failed: %v", err) } var stdout, stderr string @@ -51,6 +51,7 @@ func TestComponentCmd(t *testing.T) { "-V", `section with spaces.group with spaces.no_spaces="osef"`, "-s", stackRef, "-u", "default", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, } stdout, stderr, err = executeCommandStdin(testJSONStdin, args) if err != nil { @@ -68,7 +69,7 @@ func TestComponentCmd(t *testing.T) { "-c", component, }) if err != nil { - t.Fatalf("failed to delete and cleanup component '%s' from Create test: %v\nstdout: %s", component, err, out) + t.Errorf("failed to delete and cleanup component '%s' from Create test: %v\nstdout: %s", component, err, out) } }) @@ -83,13 +84,13 @@ func TestComponentCmd(t *testing.T) { } out, err := executeCommand(args) if err != nil { - t.Fatalf("failed to execute cmd '%s': %s", strings.Join(args, " "), err) + t.Errorf("failed to execute cmd '%s': %s", strings.Join(args, " "), err) } var comp models.Component err = json.Unmarshal([]byte(out), &comp) if err != nil { - t.Fatalf("failed to parse output of cy comp get command: %v\noutput: %s", err, out) + t.Errorf("failed to parse output of cy comp get command: %v\noutput: %s", err, out) } assert.NotNil(t, comp) @@ -107,13 +108,13 @@ func TestComponentCmd(t *testing.T) { } out, err = executeCommand(args) if err != nil { - t.Fatalf("failed to execute cmd '%s': %s", strings.Join(args, " "), err) + t.Errorf("failed to execute cmd '%s': %s", strings.Join(args, " "), err) } var comps []models.Component err = json.Unmarshal([]byte(out), &comps) if err != nil { - t.Fatalf("failed to parse output of cy comp get command: %v\noutput: %s", err, out) + t.Errorf("failed to parse output of cy comp get command: %v\noutput: %s", err, out) } }) @@ -132,6 +133,7 @@ func TestComponentCmd(t *testing.T) { "-s", stackRef, "-u", "default", "--update", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, } var err, errList error var stdout, stderr string @@ -146,7 +148,7 @@ func TestComponentCmd(t *testing.T) { } if errList != nil { - t.Fatalf("component creation failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) + t.Errorf("component creation failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) } defer t.Run("DeleteCreateWithUpdateComp", func(t *testing.T) { @@ -158,7 +160,7 @@ func TestComponentCmd(t *testing.T) { "-c", newComp, }) if err != nil { - t.Fatalf("failed to delete and cleanup component '%s' from '%s' test: %v\nstdout: %s", component, t.Name(), err, out) + t.Errorf("failed to delete and cleanup component '%s' from '%s' test: %v\nstdout: %s", component, t.Name(), err, out) } }) }) @@ -170,7 +172,7 @@ func TestComponentCmd(t *testing.T) { testJSONStdin := `{"types": {"tests": {"array": ["hello", false, 1, 1.1]}}}` filename, err := WriteTempFile(testJSONFileContent) if err != nil { - t.Fatalf("comp create setup failed: %v", err) + t.Errorf("comp create setup failed: %v", err) } defer os.Remove(filename) @@ -194,10 +196,11 @@ func TestComponentCmd(t *testing.T) { "-s", stackRef, "-u", "default", "--update", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, } stdout, stderr, err := executeCommandStdin(testJSONStdin, args) if err != nil { - t.Fatalf("component creation failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) + t.Errorf("component creation failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) } defer t.Run("DeleteCreateWithUpdateComp", func(t *testing.T) { out, err := executeCommand([]string{ @@ -208,7 +211,7 @@ func TestComponentCmd(t *testing.T) { "-c", component, }) if err != nil { - t.Fatalf("failed to delete and cleanup component '%s' from '%s' test: %v\nstdout: %s", component, t.Name(), err, out) + t.Errorf("failed to delete and cleanup component '%s' from '%s' test: %v\nstdout: %s", component, t.Name(), err, out) } }) @@ -218,7 +221,7 @@ func TestComponentCmd(t *testing.T) { testJSONStdin = `{"types": {"tests": {"array": []}}}` filename, err = WriteTempFile(testJSONFileContent) if err != nil { - t.Fatalf("comp create setup failed: %v", err) + t.Errorf("comp create setup failed: %v", err) } defer os.Remove(filename) @@ -242,11 +245,12 @@ func TestComponentCmd(t *testing.T) { "-s", stackRef, "-u", "default", "--update", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, } stdout, stderr, err = executeCommandStdin(testJSONStdin, args) if err != nil { - t.Fatalf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) + t.Errorf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) } // get config @@ -259,13 +263,13 @@ func TestComponentCmd(t *testing.T) { } stdout, stderr, err = executeCommandStdin(testJSONStdin, args) if err != nil { - t.Fatalf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) + t.Errorf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) } var outVars models.FormVariables err = json.Unmarshal([]byte(stdout), &outVars) if err != nil { - t.Fatalf("failed to parse output of CLI as JSON:\n%s\n%s", stdout, err) + t.Errorf("failed to parse output of CLI as JSON:\n%s\n%s", stdout, err) } value, _ := outVars["types"]["tests"]["map"].(map[string]any)["update"].(bool) @@ -279,7 +283,7 @@ func TestComponentCmd(t *testing.T) { testJSONStdin = `{"types": {"tests": {"float": 2.2}}}` filename, err = WriteTempFile(testJSONFileContent) if err != nil { - t.Fatalf("comp update setup failed: %v", err) + t.Errorf("comp update setup failed: %v", err) } defer os.Remove(filename) @@ -301,11 +305,12 @@ func TestComponentCmd(t *testing.T) { // Test var=value flag "-V", `section with spaces.group with spaces.no_spaces=update2`, "-u", "default", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, } stdout, stderr, err = executeCommandStdin(testJSONStdin, args) if err != nil { - t.Fatalf("component update failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) + t.Errorf("component update failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) } // check config after update @@ -318,13 +323,13 @@ func TestComponentCmd(t *testing.T) { } stdout, stderr, err = executeCommandStdin(testJSONStdin, args) if err != nil { - t.Fatalf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) + t.Errorf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) } outVars = make(models.FormVariables) err = json.Unmarshal([]byte(stdout), &outVars) if err != nil { - t.Fatalf("failed to parse output of CLI as JSON:\n%s\n%s", stdout, err) + t.Errorf("failed to parse output of CLI as JSON:\n%s\n%s", stdout, err) } assert.Equal(t, "update2", outVars["types"]["tests"]["string"]) @@ -346,6 +351,7 @@ func TestComponentCmd(t *testing.T) { "-d", description, "-s", stackRef, "-u", "default", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, "-V", `section with spaces.thisgroupdoesnotexists.no_spaces=update2`, "-V", `sectiondoesnotexists.thisgroupdoesnotexists.no_spaces=true`, } @@ -353,7 +359,7 @@ func TestComponentCmd(t *testing.T) { cmdOut, cmdErr := executeCommand(args) if cmdErr != nil { // We just check that it doesn't panic for now - t.Fatalf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) + t.Errorf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) } }) @@ -362,8 +368,8 @@ func TestComponentCmd(t *testing.T) { m := config.Middleware created, err := m.CreateComponent(config.Org, *config.Project.Canonical, - *config.Environment.Canonical, component, description, &component, - &stackRef, "") + *config.Environment.Canonical, component, description, component, + stackRef, "", "", *config.CatalogRepoVersionStacks.CommitHash, "") if err != nil { t.Logf("test setup failed: component creation %q reported err: %v", component, err) t.FailNow() @@ -383,12 +389,13 @@ func TestComponentCmd(t *testing.T) { "-d", description, "-s", stackRef, "-u", "default", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, } cmdOut, cmdErr := executeCommand(args) if cmdErr != nil { // We just check that it doesn't panic for now - t.Fatalf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) + t.Errorf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) } }) @@ -397,8 +404,8 @@ func TestComponentCmd(t *testing.T) { m := config.Middleware created, err := m.CreateComponent(config.Org, *config.Project.Canonical, - *config.Environment.Canonical, component, description, &component, - &stackRef, "") + *config.Environment.Canonical, component, description, component, + stackRef, "", "", *config.CatalogRepoVersionStacks.CommitHash, "") if err != nil { t.Logf("test setup failed: component creation %q reported err: %v", component, err) t.FailNow() @@ -416,12 +423,13 @@ func TestComponentCmd(t *testing.T) { "-c", component, "-d", description, "-u", "default", + "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, } cmdOut, cmdErr := executeCommand(args) if cmdErr != nil { // We just check that it doesn't panic for now - t.Fatalf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) + t.Errorf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) } }) } diff --git a/e2e/creds_test.go b/e2e/creds_test.go index 3c2a8326..28380908 100644 --- a/e2e/creds_test.go +++ b/e2e/creds_test.go @@ -60,7 +60,7 @@ func TestCreds(t *testing.T) { "--canonical", "cli-custom-canonical", }) if err != nil { - t.Fatalf("failed to delete cred cli-custom: %s", err.Error()) + t.Errorf("failed to delete cred cli-custom: %s", err.Error()) } }) @@ -68,7 +68,7 @@ func TestCreds(t *testing.T) { var outCred *models.Credential err := json.Unmarshal([]byte(cmdOut), &outCred) if err != nil { - t.Fatalf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) + t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) } // Test that the flag works @@ -98,7 +98,7 @@ func TestCreds(t *testing.T) { var outCred *models.Credential err := json.Unmarshal([]byte(cmdOut), &outCred) if err != nil { - t.Fatalf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) + t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) } cmdOut, cmdErr = executeCommand([]string{ @@ -116,7 +116,7 @@ func TestCreds(t *testing.T) { fileContent := "hello world" fileName, err := WriteTempFile(fileContent) if err != nil { - t.Fatalf("failed to setup test, temp file write failed: %s", err.Error()) + t.Errorf("failed to setup test, temp file write failed: %s", err.Error()) } defer os.Remove(fileName) @@ -140,21 +140,21 @@ func TestCreds(t *testing.T) { "--canonical", "cli-custom-file", }) if err != nil { - t.Fatalf("failed to delete cred 'cli-custom-file'") + t.Errorf("failed to delete cred 'cli-custom-file'") } }) var outCred *models.Credential err = json.Unmarshal([]byte(cmdOut), &outCred) if err != nil { - t.Fatalf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) + t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) } }) t.Run("SuccessCredsCreateSSH", func(t *testing.T) { fileName, err := WriteTempFile(string(TestGitSSHKey)) if err != nil { - t.Fatalf("failed to setup test, temp file write failed: %s", err.Error()) + t.Errorf("failed to setup test, temp file write failed: %s", err.Error()) } defer os.Remove(fileName) cmdOut, cmdErr := executeCommand([]string{ @@ -176,14 +176,14 @@ func TestCreds(t *testing.T) { "--canonical", "cli-ssh", }) if err != nil { - t.Fatalf("failed to delete cred 'cli-ssh'") + t.Errorf("failed to delete cred 'cli-ssh'") } }) var outCred *models.Credential err = json.Unmarshal([]byte(cmdOut), &outCred) if err != nil { - t.Fatalf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) + t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) } }) }) diff --git a/e2e/environments_test.go b/e2e/environments_test.go index 3bdfd5cd..930ab64f 100644 --- a/e2e/environments_test.go +++ b/e2e/environments_test.go @@ -33,7 +33,7 @@ func TestEnvs(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to create env '%s': %v", env, err) + t.Errorf("failed to create env '%s': %v", env, err) } }) @@ -45,7 +45,7 @@ func TestEnvs(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to delete env '%s': %v", env, err) + t.Errorf("failed to delete env '%s': %v", env, err) } }) @@ -58,13 +58,13 @@ func TestEnvs(t *testing.T) { } cmdOut, err := executeCommand(args) if err != nil { - t.Fatalf("failed to get env '%s': %v", env, err) + t.Errorf("failed to get env '%s': %v", env, err) } var got models.Environment err = json.Unmarshal([]byte(cmdOut), &got) if err != nil { - t.Fatalf("failed to marshal json cli output: %s\nerr: %s", cmdOut, err) + t.Errorf("failed to marshal json cli output: %s\nerr: %s", cmdOut, err) } assert.EqualValues(t, env, *got.Canonical) @@ -86,13 +86,13 @@ func TestEnvs(t *testing.T) { } out, err := executeCommand(args) if err != nil { - t.Fatalf("failed to create env '%s': %v", env, err) + t.Errorf("failed to create env '%s': %v", env, err) } var envResult models.Environment err = json.Unmarshal([]byte(out), &envResult) if err != nil { - t.Fatalf("failed to parse json output from the CLI on create --update: %v\noutput: %s", err, out) + t.Errorf("failed to parse json output from the CLI on create --update: %v\noutput: %s", err, out) } assert.Equal(t, createUpdateName, envResult.Name) @@ -111,7 +111,7 @@ func TestEnvs(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to create env '%s': %v", newEnv, err) + t.Errorf("failed to create env '%s': %v", newEnv, err) } defer t.Run("DeleteCreateUpdate", func(t *testing.T) { @@ -122,7 +122,7 @@ func TestEnvs(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to delete env '%s': %v", newEnv, err) + t.Errorf("failed to delete env '%s': %v", newEnv, err) } }) }) @@ -139,13 +139,13 @@ func TestEnvs(t *testing.T) { } out, err := executeCommand(args) if err != nil { - t.Fatalf("failed to update env '%s': %v", env, err) + t.Errorf("failed to update env '%s': %v", env, err) } var envResult models.Environment err = json.Unmarshal([]byte(out), &envResult) if err != nil { - t.Fatalf("failed to parse json output from the CLI on update: %v", err) + t.Errorf("failed to parse json output from the CLI on update: %v", err) } assert.Equal(t, newName, envResult.Name) diff --git a/e2e/helpers_test.go b/e2e/helpers_test.go index f796480e..4cab0055 100644 --- a/e2e/helpers_test.go +++ b/e2e/helpers_test.go @@ -44,12 +44,12 @@ func TestExecuteCommandStdin(t *testing.T) { cmd.SetOut(stdoutBuf) err = cmd.Execute() if err != nil { - t.Fatalf("command failed: %s", err) + t.Errorf("command failed: %s", err) } stdout, err := io.ReadAll(stdoutBuf) if err != nil { - t.Fatalf("failed to read cmd output: %s", err) + t.Errorf("failed to read cmd output: %s", err) } assert.Equal(t, expected, string(stdout)) diff --git a/e2e/pipelines_test.go b/e2e/pipelines_test.go index 1f3b4813..6f381532 100644 --- a/e2e/pipelines_test.go +++ b/e2e/pipelines_test.go @@ -21,16 +21,16 @@ func TestPipelines(t *testing.T) { "pipelines", "list", }) if listErr != nil { - t.Fatalf("List org pipeline should not err, out: %s\nerr: %s", listOut, listErr) + t.Errorf("List org pipeline should not err, out: %s\nerr: %s", listOut, listErr) } err := json.Unmarshal([]byte(listOut), &pipelineList) if err != nil { - t.Fatalf("failed to unmarshall list test output, out: %s\nerr: %s", listOut, err) + t.Errorf("failed to unmarshall list test output, out: %s\nerr: %s", listOut, err) } if len(pipelineList) == 0 { - t.Fatalf("There should be at least one pipeline in this org:\n%s", listOut) + t.Errorf("There should be at least one pipeline in this org:\n%s", listOut) } }) @@ -45,17 +45,17 @@ func TestPipelines(t *testing.T) { "--pipeline", *firstPipeline.Name, }) if getErr != nil { - t.Fatalf("get pipeline should not err, out: %s\nerr: %s", getOut, getErr) + t.Errorf("get pipeline should not err, out: %s\nerr: %s", getOut, getErr) } var getPipeline models.Pipeline err := json.Unmarshal([]byte(getOut), &getPipeline) if err != nil { - t.Fatalf("Failed to parse json output of pipelines get cmd, out: %s\nerr: %s", getOut, err) + t.Errorf("Failed to parse json output of pipelines get cmd, out: %s\nerr: %s", getOut, err) } if assert.ObjectsAreEqualValues(firstPipeline, getPipeline) { - t.Fatalf("both pipelines should be equal:\nexpect: %v\ngot: %v", firstPipeline, getPipeline) + t.Errorf("both pipelines should be equal:\nexpect: %v\ngot: %v", firstPipeline, getPipeline) } }) @@ -69,7 +69,7 @@ func TestPipelines(t *testing.T) { "--pipeline", *firstPipeline.Name, }) if pauseErr != nil { - t.Fatalf("failed to pause pipeline '%s': %s", *firstPipeline.Name, pauseErr) + t.Errorf("failed to pause pipeline '%s': %s", *firstPipeline.Name, pauseErr) } }) @@ -83,7 +83,7 @@ func TestPipelines(t *testing.T) { "--pipeline", *firstPipeline.Name, }) if unpauseErr != nil { - t.Fatalf("failed to unpause pipeline '%s': %s", *firstPipeline.Name, unpauseErr) + t.Errorf("failed to unpause pipeline '%s': %s", *firstPipeline.Name, unpauseErr) } }) @@ -97,7 +97,7 @@ func TestPipelines(t *testing.T) { "--pipeline", *firstPipeline.Name, }) if syncedErr != nil { - t.Fatalf("failed to pause pipeline '%s': %s", *firstPipeline.Name, syncedErr) + t.Errorf("failed to pause pipeline '%s': %s", *firstPipeline.Name, syncedErr) } }) @@ -108,7 +108,7 @@ func TestPipelines(t *testing.T) { "--since-days", "99", }) if cmdErr != nil { - t.Fatalf("failed to list last-used pipelines, out: %s\nerr: %s", cmdOut, cmdErr) + t.Errorf("failed to list last-used pipelines, out: %s\nerr: %s", cmdOut, cmdErr) } }) @@ -129,16 +129,16 @@ func TestPipelines(t *testing.T) { "--pipeline", *firstPipeline.Name, }) if listErr != nil { - t.Fatalf("List job in pipeline %q should not err, out: %s\nerr: %s", *firstPipeline.Name, listOut, listErr) + t.Errorf("List job in pipeline %q should not err, out: %s\nerr: %s", *firstPipeline.Name, listOut, listErr) } err := json.Unmarshal([]byte(listOut), &jobList) if err != nil { - t.Fatalf("failed to marshal output of cy pp job list, out: %s\nerr: %s", listOut, err) + t.Errorf("failed to marshal output of cy pp job list, out: %s\nerr: %s", listOut, err) } if len(jobList) == 0 { - t.Fatalf("job list should not be empty:\n%s", litter.Sdump(jobList)) + t.Errorf("job list should not be empty:\n%s", litter.Sdump(jobList)) } firstJob := jobList[0] @@ -153,13 +153,13 @@ func TestPipelines(t *testing.T) { "--job", *firstJob.Name, }) if getErr != nil { - t.Fatalf("cy get job in pipeline '%s' should not fail, out: %s\nerr: %s", *firstJob.Name, getOut, getErr) + t.Errorf("cy get job in pipeline '%s' should not fail, out: %s\nerr: %s", *firstJob.Name, getOut, getErr) } var getJob *models.Job err := json.Unmarshal([]byte(getOut), &getJob) if err != nil { - t.Fatalf("failed to unmarshall get job cmd output, out: %s\nerr: %s", getOut, err) + t.Errorf("failed to unmarshall get job cmd output, out: %s\nerr: %s", getOut, err) } assert.Equal(t, *firstJob.ID, *getJob.ID) @@ -176,7 +176,7 @@ func TestPipelines(t *testing.T) { "--job", *firstJob.Name, }) if pauseErr != nil { - t.Fatalf("cmd cy pp job pause failed for pipeline '%s', out: %s, err: %s", *firstPipeline.Name, pauseOut, pauseErr) + t.Errorf("cmd cy pp job pause failed for pipeline '%s', out: %s, err: %s", *firstPipeline.Name, pauseOut, pauseErr) } t.Run("UnpauseJobOk", func(t *testing.T) { @@ -190,7 +190,7 @@ func TestPipelines(t *testing.T) { "--job", *firstJob.Name, }) if unpauseErr != nil { - t.Fatalf("cmd cy pp job unpause failed for pipeline '%s', out: %s, err: %s", *firstPipeline.Name, unpauseOut, unpauseErr) + t.Errorf("cmd cy pp job unpause failed for pipeline '%s', out: %s, err: %s", *firstPipeline.Name, unpauseOut, unpauseErr) } }) }) @@ -208,17 +208,17 @@ func TestPipelines(t *testing.T) { "--job", *firstJob.Name, }) if triggerErr != nil { - t.Fatalf("cmd cy pp build create failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, triggerOut, triggerErr) + t.Errorf("cmd cy pp build create failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, triggerOut, triggerErr) } err := json.Unmarshal([]byte(triggerOut), &triggeredBuild) if err != nil { - t.Fatalf("cmd output is not a models.Build, out: %s\nerr: %s", triggerOut, triggerErr) + t.Errorf("cmd output is not a models.Build, out: %s\nerr: %s", triggerOut, triggerErr) } buildIDStr := strconv.Itoa(int(*triggeredBuild.ID)) if err != nil { - t.Fatalf("invalid build id in:\n%v\n%s", triggeredBuild, err) + t.Errorf("invalid build id in:\n%v\n%s", triggeredBuild, err) } t.Run("GetBuildOk", func(t *testing.T) { @@ -233,7 +233,7 @@ func TestPipelines(t *testing.T) { "--build-id", buildIDStr, }) if getErr != nil { - t.Fatalf("cmd cy pp build get failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, getOut, getErr) + t.Errorf("cmd cy pp build get failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, getOut, getErr) } }) @@ -248,7 +248,7 @@ func TestPipelines(t *testing.T) { "--job", *firstJob.Name, }) if listErr != nil { - t.Fatalf("cmd cy pp build list failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, listOut, listErr) + t.Errorf("cmd cy pp build list failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, listOut, listErr) } }) }) diff --git a/e2e/projects_test.go b/e2e/projects_test.go index 7b655a3b..082c6357 100644 --- a/e2e/projects_test.go +++ b/e2e/projects_test.go @@ -38,7 +38,7 @@ func TestProjects(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to create project '%s': %v", project, err) + t.Errorf("failed to create project '%s': %v", project, err) } }) @@ -49,7 +49,7 @@ func TestProjects(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to delete project '%s': %v", project, err) + t.Errorf("failed to delete project '%s': %v", project, err) } }) @@ -72,13 +72,13 @@ func TestProjects(t *testing.T) { } out, err := executeCommand(args) if err != nil { - t.Fatalf("failed to create project '%s': %v", project, err) + t.Errorf("failed to create project '%s': %v", project, err) } var projectResult models.Project err = json.Unmarshal([]byte(out), &projectResult) if err != nil { - t.Fatalf("failed to parse json output from the CLI on create --update: %v\noutput: %s", err, out) + t.Errorf("failed to parse json output from the CLI on create --update: %v\noutput: %s", err, out) } assert.Equal(t, createUpdateName, *projectResult.Name) @@ -100,7 +100,7 @@ func TestProjects(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to create project '%s': %v", newProject, err) + t.Errorf("failed to create project '%s': %v", newProject, err) } defer t.Run("DeleteCreateUpdate", func(t *testing.T) { @@ -110,7 +110,7 @@ func TestProjects(t *testing.T) { } _, err := executeCommand(args) if err != nil { - t.Fatalf("failed to delete project '%s': %v", newProject, err) + t.Errorf("failed to delete project '%s': %v", newProject, err) } }) }) @@ -129,13 +129,13 @@ func TestProjects(t *testing.T) { } jsonOut, err := executeCommand(args) if err != nil { - t.Fatalf("failed to update project '%s': %v", project, err) + t.Errorf("failed to update project '%s': %v", project, err) } var projectResult models.Project err = json.Unmarshal([]byte(jsonOut), &projectResult) if err != nil { - t.Fatalf("failed to parse json output from the CLI on update: %v\noutput: %s", err, jsonOut) + t.Errorf("failed to parse json output from the CLI on update: %v\noutput: %s", err, jsonOut) } assert.Equal(t, updateDesc, projectResult.Description) diff --git a/e2e/stacks_test.go b/e2e/stacks_test.go index 2d295f41..92f5eb0c 100644 --- a/e2e/stacks_test.go +++ b/e2e/stacks_test.go @@ -76,13 +76,13 @@ func TestStacks(t *testing.T) { } jsonBody, err := json.Marshal(body) if err != nil { - t.Fatalf("[preparation]: json serialization shouldn't fail: %s", err.Error()) + t.Errorf("[preparation]: json serialization shouldn't fail: %s", err.Error()) } // team management is not implemented on the CLI, so making the call ourselves request, err := http.NewRequest("POST", fmt.Sprintf("%s/organizations/%s/teams", config.APIUrl, config.Org), bytes.NewBuffer(jsonBody)) if err != nil { - t.Fatalf("[preparation]: request creationg shoudn't fail: %s", err.Error()) + t.Errorf("[preparation]: request creationg shoudn't fail: %s", err.Error()) } request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.APIKey)) @@ -91,7 +91,7 @@ func TestStacks(t *testing.T) { client := &http.Client{} _, err = client.Do(request) if err != nil { - t.Fatalf("[Preparation]: request to create teams shouldn't fail: %s", err.Error()) + t.Errorf("[Preparation]: request to create teams shouldn't fail: %s", err.Error()) } // At this point we should have a team, I assume CR and stacks are present too @@ -165,7 +165,7 @@ use_cases: `) testForms, err := os.CreateTemp("", "test-stackforms.yml") if err != nil { - t.Fatalf("setup failed: error while writing test forms at '%s'", testForms.Name()) + t.Errorf("setup failed: error while writing test forms at '%s'", testForms.Name()) } testFormsPath := testForms.Name() WriteFile(testFormsPath, TestForms) @@ -199,4 +199,171 @@ use_cases: t.Run("SuccessCreateStackFromBlueprint", func(t *testing.T) { t.Skip("Skipping due to missing way to cleanup stack afterwards") }) + + // Completion tests + t.Run("SuccessCompleteStackVersionCommitHash", func(t *testing.T) { + is := is.New(t) + // Test completion for component create with stack-ref + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-commit-hash", "", + }) + is.NoErr(cmdErr) + // The output should contain commit hashes + // Format: commitHash\tDescription\n:4\nCompletion ended with directive: ShellCompDirectiveNoFileComp + is.True(len(cmdOut) > 0) // Should have some output + is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help + is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive (4) + }) + + t.Run("SuccessCompleteStackVersionCommitHashWithPartialInput", func(t *testing.T) { + is := is.New(t) + // First, get a valid commit hash from the stack versions + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-commit-hash", "", + }) + is.NoErr(cmdErr) + + // Parse the first commit hash (before the tab character) + lines := bytes.Split([]byte(cmdOut), []byte("\n")) + if len(lines) > 0 && len(lines[0]) > 3 { + // Take first 3 characters as partial input + partial := string(lines[0][:3]) + + // Test completion with partial input + cmdOut2, cmdErr2 := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-commit-hash", partial, + }) + is.NoErr(cmdErr2) + is.True(len(cmdOut2) > 0) // Should have some output + is.True(!bytes.Contains([]byte(cmdOut2), []byte("_activeHelp"))) // Should not have error help + is.True(bytes.Contains([]byte(cmdOut2), []byte(partial))) // Should contain the partial string + } + }) + + t.Run("FailCompleteStackVersionCommitHashNoStackRef", func(t *testing.T) { + is := is.New(t) + // Test completion without stack-ref should provide helpful error + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-commit-hash", "", + }) + // The command itself doesn't error, but completion should show active help + is.NoErr(cmdErr) + is.True(bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should have error help + is.True(bytes.Contains([]byte(cmdOut), []byte("missing stack-ref"))) // Should mention missing stack-ref + }) + + t.Run("SuccessCompleteStackVersionCommitHashForUpdate", func(t *testing.T) { + is := is.New(t) + // For component update, if we provide stack-ref it should work + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "update", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-commit-hash", "", + }) + is.NoErr(cmdErr) + is.True(len(cmdOut) > 0) // Should have some output + is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help + is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive + }) + + // Stack version tag completion tests + t.Run("SuccessCompleteStackVersionTag", func(t *testing.T) { + is := is.New(t) + // Test completion for component create with stack-ref + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-tag", "", + }) + is.NoErr(cmdErr) + // The output should contain version tags + is.True(len(cmdOut) > 0) // Should have some output + is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help + is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive (4) + }) + + t.Run("SuccessCompleteStackVersionTagWithPartialInput", func(t *testing.T) { + is := is.New(t) + // First, get a valid version tag from the stack versions + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-tag", "", + }) + is.NoErr(cmdErr) + + // Parse the first version tag (before the tab character) + lines := bytes.Split([]byte(cmdOut), []byte("\n")) + if len(lines) > 0 && len(lines[0]) > 0 { + // Take first character as partial input + parts := bytes.Split(lines[0], []byte("\t")) + if len(parts) > 0 && len(parts[0]) > 0 { + partial := string(parts[0][:1]) + + // Test completion with partial input + cmdOut2, cmdErr2 := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-tag", partial, + }) + is.NoErr(cmdErr2) + is.True(len(cmdOut2) > 0) // Should have some output + is.True(!bytes.Contains([]byte(cmdOut2), []byte("_activeHelp"))) // Should not have error help + } + } + }) + + t.Run("FailCompleteStackVersionTagNoStackRef", func(t *testing.T) { + is := is.New(t) + // Test completion without stack-ref should provide helpful error + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "create", + "--org", config.Org, + "--stack-tag", "", + }) + // The command itself doesn't error, but completion should show active help + is.NoErr(cmdErr) + is.True(bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should have error help + is.True(bytes.Contains([]byte(cmdOut), []byte("missing stack-ref"))) // Should mention missing stack-ref + }) + + t.Run("SuccessCompleteStackVersionTagForUpdate", func(t *testing.T) { + is := is.New(t) + // For component update, if we provide stack-ref it should work + cmdOut, cmdErr := executeCommand([]string{ + "__complete", + "component", "update", + "--org", config.Org, + "--stack-ref", testStackRef, + "--stack-tag", "", + }) + is.NoErr(cmdErr) + is.True(len(cmdOut) > 0) // Should have some output + is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help + is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive + }) } diff --git a/e2e/uri_test.go b/e2e/uri_test.go index fdea8489..3c6382b7 100644 --- a/e2e/uri_test.go +++ b/e2e/uri_test.go @@ -90,7 +90,7 @@ func TestGetCmd(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { cmdOut, cmdErr := executeCommand(testCase.args) if cmdErr != nil { - t.Fatalf("failed to get from urls: %v: %s", testCase.args, cmdErr) + t.Errorf("failed to get from urls: %v: %s", testCase.args, cmdErr) } testCase.expect(t, cmdOut) diff --git a/internal/cyargs/common.go b/internal/cyargs/common.go index 9f7b23c7..db2f24ef 100644 --- a/internal/cyargs/common.go +++ b/internal/cyargs/common.go @@ -104,8 +104,10 @@ func GetCyContext(cmd *cobra.Command) (org, project, env, component string, err return org, project, env, component, nil } -func AddNameFlag(cmd *cobra.Command) { - cmd.Flags().StringP("name", "n", "", "set a human friendly name.") +func AddNameFlag(cmd *cobra.Command) string { + flagName := "name" + cmd.Flags().StringP(flagName, "n", "", "set a human friendly name.") + return flagName } func GetName(cmd *cobra.Command) (string, error) { diff --git a/internal/cyargs/common_test.go b/internal/cyargs/common_test.go index ffa9c484..7373f9c6 100644 --- a/internal/cyargs/common_test.go +++ b/internal/cyargs/common_test.go @@ -30,7 +30,7 @@ func parseArgFunc(t *testing.T, cmd *cobra.Command, args []string) { err := cmd.ParseFlags(args) if err != nil { - t.Fatalf("Failed to parse flags '%v' with cmd: %v", args, err) + t.Errorf("Failed to parse flags '%v' with cmd: %v", args, err) } orgArg, projectArg, envArg, componentArg, err := cyargs.GetCyContext(cmd) diff --git a/internal/cyargs/component.go b/internal/cyargs/component.go index 866ba696..f1bf21bd 100644 --- a/internal/cyargs/component.go +++ b/internal/cyargs/component.go @@ -70,12 +70,22 @@ func CompleteUseCase(cmd *cobra.Command, args []string, toComplete string) ([]st } } + // Try to get the stack version flags + tag, branch, hash, err := GetStackVersionFlags(cmd) + if err != nil { + return cobra.AppendActiveHelp(nil, "failed to read stack version flags: "+err.Error()), cobra.ShellCompDirectiveError + } + api := common.NewAPI() m := middleware.NewMiddleware(api) - stackUseCases, err := m.ListStackUseCases(org, stackRef) + // Try to get the stack use cases using the provided flags + // If none are provided yet, this will use default version + stackUseCases, err := m.ListStackUseCases(org, stackRef, tag, branch, hash) if err != nil { - return cobra.AppendActiveHelp(nil, "cannot find stack or blueprint with ref: "+stackRef+", err: "+err.Error()), + // During completion, the version flags might not be set yet + // Return a helpful message to guide the user + return cobra.AppendActiveHelp(nil, "please provide one of --stack-tag, --stack-branch, or --stack-commit-hash first"), cobra.ShellCompDirectiveNoFileComp } diff --git a/internal/cyargs/stackforms_input.go b/internal/cyargs/stackforms_input.go index 4019915f..297aa910 100644 --- a/internal/cyargs/stackforms_input.go +++ b/internal/cyargs/stackforms_input.go @@ -52,7 +52,7 @@ func GetStackformsVars(cmd *cobra.Command, defaults models.FormVariables) (model tempFile, err := os.CreateTemp("", "cy-stdin-*") if err != nil { - return nil, fmt.Errorf("failed to write temp file for stdin: %v", err) + return nil, fmt.Errorf("failed to write temp file for stdin: %w", err) } defer func() { closeErr := tempFile.Close() diff --git a/internal/cyargs/stackforms_input_test.go b/internal/cyargs/stackforms_input_test.go index 36e5b9e0..0c3511fb 100644 --- a/internal/cyargs/stackforms_input_test.go +++ b/internal/cyargs/stackforms_input_test.go @@ -2,9 +2,7 @@ package cyargs_test import ( "encoding/json" - "fmt" "os" - "reflect" "testing" "github.com/spf13/cobra" @@ -41,7 +39,7 @@ func TestGetStackformsVars(t *testing.T) { } expectedJSON, err := json.Marshal(expected) if err != nil { - t.Fatalf("failed setup for test, failed to encode expected value '%v' to json: %s", expected, err) + t.Errorf("failed setup for test, failed to encode expected value '%v' to json: %s", expected, err) } t.Run("VarsStdin", func(t *testing.T) { @@ -50,18 +48,18 @@ func TestGetStackformsVars(t *testing.T) { tempFile, err := os.CreateTemp("", "json-test") if err != nil { - t.Fatalf("failed to setup test, cannot create temp file: %s", err) + t.Errorf("failed to setup test, cannot create temp file: %s", err) } defer os.Remove(tempFile.Name()) _, err = tempFile.Write(expectedJSON) if err != nil { - t.Fatalf("failed to setup test, cannot write to test file %s: %s", tempFile.Name(), err) + t.Errorf("failed to setup test, cannot write to test file %s: %s", tempFile.Name(), err) } _, err = tempFile.Seek(0, 0) if err != nil { - t.Fatalf("failed to setup test, cannot change offset in file reader: %s", err) + t.Errorf("failed to setup test, cannot change offset in file reader: %s", err) } oldStdin := os.Stdin @@ -76,12 +74,12 @@ func TestGetStackformsVars(t *testing.T) { var defaults = make(models.FormVariables) output, err := cyargs.GetStackformsVars(cmd, defaults) if err != nil { - t.Fatalf("stackform var parsing failed: %s", err) + t.Errorf("stackform var parsing failed: %s", err) } gotJSON, err := json.Marshal(output) if err != nil { - t.Fatalf("failed to serialize json output '%v': %s", &output, err) + t.Errorf("failed to serialize json output '%v': %s", &output, err) } assert.Equal(t, string(expectedJSON), string(gotJSON), "should be equal") }) @@ -93,7 +91,7 @@ func TestGetStackformsVars(t *testing.T) { var defaults = make(models.FormVariables) output, err := cyargs.GetStackformsVars(cmd, defaults) if err != nil { - t.Fatalf("Empty default should work: %s", err) + t.Errorf("Empty default should work: %s", err) } assert.Equal(t, defaults, output, "should be empty") @@ -108,12 +106,12 @@ func TestGetStackformsVars(t *testing.T) { var defaults = make(models.FormVariables) output, err := cyargs.GetStackformsVars(cmd, defaults) if err != nil { - t.Fatalf("Empty default should work: %s", err) + t.Errorf("Empty default should work: %s", err) } gotJSON, err := json.Marshal(output) if err != nil { - t.Fatalf("failed to serialize json output '%v': %s", &output, err) + t.Errorf("failed to serialize json output '%v': %s", &output, err) } assert.Equal(t, expectedJSON, gotJSON, "should be equal") }) @@ -129,12 +127,12 @@ func TestGetStackformsVars(t *testing.T) { var defaults = make(models.FormVariables) output, err := cyargs.GetStackformsVars(cmd, defaults) if err != nil { - t.Fatalf("Empty default should work: %s", err) + t.Errorf("Empty default should work: %s", err) } gotJSON, err := json.Marshal(output) if err != nil { - t.Fatalf("failed to serialize json output '%v': %s", &output, err) + t.Errorf("failed to serialize json output '%v': %s", &output, err) } assert.Equal(t, string(expectedJSON), string(gotJSON), "should be equal") }) @@ -145,13 +143,13 @@ func TestGetStackformsVars(t *testing.T) { tempFile, err := os.CreateTemp("", "json-test") if err != nil { - t.Fatalf("failed to setup test, cannot create temp file: %s", err) + t.Errorf("failed to setup test, cannot create temp file: %s", err) } defer os.Remove(tempFile.Name()) _, err = tempFile.Write(expectedJSON) if err != nil { - t.Fatalf("failed to setup test, cannot write to test file %s: %s", tempFile.Name(), err) + t.Errorf("failed to setup test, cannot write to test file %s: %s", tempFile.Name(), err) } cmd.ParseFlags([]string{ @@ -161,12 +159,12 @@ func TestGetStackformsVars(t *testing.T) { var defaults = make(models.FormVariables) output, err := cyargs.GetStackformsVars(cmd, defaults) if err != nil { - t.Fatalf("Empty default should work: %s", err) + t.Errorf("Empty default should work: %s", err) } gotJSON, err := json.Marshal(output) if err != nil { - t.Fatalf("failed to serialize json output '%v': %s", &output, err) + t.Errorf("failed to serialize json output '%v': %s", &output, err) } assert.Equal(t, string(expectedJSON), string(gotJSON), "should be equal") }) @@ -187,7 +185,7 @@ func TestGetStackformsVars(t *testing.T) { var defaults = make(models.FormVariables) parsedVars, err := cyargs.GetStackformsVars(cmd, defaults) if err != nil { - t.Fatalf("Empty default should work: %s", err) + t.Errorf("Empty default should work: %s", err) } value, ok := parsedVars["types"]["string"]["double_quote"].(string) @@ -206,7 +204,6 @@ func TestGetStackformsVars(t *testing.T) { assert.True(t, ok, "type cast to boolean should be okay") assert.Equal(t, true, valueBool, "the output should be a bool") - fmt.Println(reflect.TypeOf(parsedVars["types"]["array"]["no_quote"])) valueArray, ok := parsedVars["types"]["array"]["no_quote"] assert.True(t, ok, "type cast to array should be okay") assert.Equal(t, []any{"string", "hello_there"}, valueArray, "the output should be a array") diff --git a/internal/cyargs/stacks.go b/internal/cyargs/stacks.go index 3d24cd29..a448f4ac 100644 --- a/internal/cyargs/stacks.go +++ b/internal/cyargs/stacks.go @@ -177,10 +177,6 @@ func AddStackNameFlag(cmd *cobra.Command) string { return flagName } -func GetStackName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("name") -} - func AddStackFlag(cmd *cobra.Command) string { flagStack := "stack" cmd.Flags().StringP(flagStack, "s", "", "canonical of the stack") @@ -190,3 +186,240 @@ func AddStackFlag(cmd *cobra.Command) string { func GetStack(cmd *cobra.Command) (string, error) { return cmd.Flags().GetString("stack") } + +// AddStackVersionFlags adds mutually exclusive flags for specifying stack versions. +// Similar to AddStackFormsInputFlags, this groups related version flags together. +// At least one of these flags must be provided. +func AddStackVersionFlags(cmd *cobra.Command) { + cmd.Flags().String("stack-tag", "", "the stack version tag to use (e.g., v1.0.0)") + cmd.Flags().String("stack-branch", "", "the stack version branch to use (e.g., main)") + cmd.Flags().String("stack-commit-hash", "", "the stack version commit hash to use") + + // Register completion functions + cmd.RegisterFlagCompletionFunc("stack-tag", CompleteStackVersionTag) + cmd.RegisterFlagCompletionFunc("stack-branch", CompleteStackVersionBranch) + cmd.RegisterFlagCompletionFunc("stack-commit-hash", CompleteCatalogRepoCommitHash) + + // Make flags mutually exclusive + cmd.MarkFlagsMutuallyExclusive("stack-tag", "stack-branch", "stack-commit-hash") + + // Require at least one of these flags + cmd.MarkFlagsOneRequired("stack-tag", "stack-branch", "stack-commit-hash") +} + +// GetStackVersionFlags reads the stack version flags from the command. +func GetStackVersionFlags(cmd *cobra.Command) (tag, branch, hash string, err error) { + tag, err = cmd.Flags().GetString("stack-tag") + if err != nil { + return "", "", "", err + } + + branch, err = cmd.Flags().GetString("stack-branch") + if err != nil { + return "", "", "", err + } + + hash, err = cmd.Flags().GetString("stack-commit-hash") + if err != nil { + return "", "", "", err + } + + return tag, branch, hash, nil +} + +// CompleteCatalogRepoCommitHash provides completion for the catalog-repo-commit-hash flag. +// It fetches available commit hashes from the stack's catalog repository versions. +// For component create: uses the required stack-ref flag. +// For component update: uses stack-ref flag if provided, otherwise fetches it from the existing component. +func CompleteCatalogRepoCommitHash(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + org, err := GetOrg(cmd) + if err != nil { + return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError + } + + var stackRef string + stackRef, _ = GetStackRef(cmd) + + // If stack-ref is not provided, try to get it from the component (for update command) + if stackRef == "" { + project, errProj := GetProject(cmd) + env, errEnv := GetEnv(cmd) + component, errComp := GetComponent(cmd) + + if errProj == nil && errEnv == nil && errComp == nil { + api := common.NewAPI() + m := middleware.NewMiddleware(api) + + currentComponent, errGet := m.GetComponent(org, project, env, component) + if errGet == nil && currentComponent.ServiceCatalog != nil && currentComponent.ServiceCatalog.Ref != nil { + stackRef = *currentComponent.ServiceCatalog.Ref + } + } + } + + if stackRef == "" { + return cobra.AppendActiveHelp(nil, "missing stack-ref for completion: please provide --stack-ref flag"), + cobra.ShellCompDirectiveNoFileComp + } + + api := common.NewAPI() + m := middleware.NewMiddleware(api) + + versions, err := m.ListStackVersions(org, stackRef) + if err != nil { + return cobra.AppendActiveHelp(nil, "cannot find versions for stack: "+stackRef+", err: "+err.Error()), + cobra.ShellCompDirectiveNoFileComp + } + + var commitHashes []string + for _, version := range versions { + if version.CommitHash != nil && strings.HasPrefix(*version.CommitHash, toComplete) { + // Build description with version name and type + desc := "" + if version.Name != nil { + desc = *version.Name + } + if version.Type != nil { + if desc != "" { + desc = desc + " (" + *version.Type + ")" + } else { + desc = *version.Type + } + } + if version.IsLatest != nil && *version.IsLatest { + desc = desc + " [latest]" + } + + commitHashes = append(commitHashes, cobra.CompletionWithDesc(*version.CommitHash, desc)) + } + } + + return commitHashes, cobra.ShellCompDirectiveNoFileComp +} + +// CompleteStackVersionTag provides completion for the stack-tag flag. +// It fetches available tags from the stack's catalog repository versions. +func CompleteStackVersionTag(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + org, err := GetOrg(cmd) + if err != nil { + return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError + } + + var stackRef string + stackRef, _ = GetStackRef(cmd) + + // If stack-ref is not provided, try to get it from the component (for update command) + if stackRef == "" { + project, errProj := GetProject(cmd) + env, errEnv := GetEnv(cmd) + component, errComp := GetComponent(cmd) + + if errProj == nil && errEnv == nil && errComp == nil { + api := common.NewAPI() + m := middleware.NewMiddleware(api) + + currentComponent, errGet := m.GetComponent(org, project, env, component) + if errGet == nil && currentComponent.ServiceCatalog != nil && currentComponent.ServiceCatalog.Ref != nil { + stackRef = *currentComponent.ServiceCatalog.Ref + } + } + } + + if stackRef == "" { + return cobra.AppendActiveHelp(nil, "missing stack-ref for completion: please provide --stack-ref flag"), + cobra.ShellCompDirectiveNoFileComp + } + + api := common.NewAPI() + m := middleware.NewMiddleware(api) + + versions, err := m.ListStackVersions(org, stackRef) + if err != nil { + return cobra.AppendActiveHelp(nil, "cannot find versions for stack: "+stackRef+", err: "+err.Error()), + cobra.ShellCompDirectiveNoFileComp + } + + var tags []string + for _, version := range versions { + if version.Type != nil && *version.Type == "tag" && version.Name != nil && strings.HasPrefix(*version.Name, toComplete) { + // Build description with commit hash + desc := "" + if version.CommitHash != nil { + commitHashShort := *version.CommitHash + if len(commitHashShort) > 8 { + commitHashShort = commitHashShort[:8] + } + desc = commitHashShort + } + if version.IsLatest != nil && *version.IsLatest { + desc = desc + " [latest]" + } + + tags = append(tags, cobra.CompletionWithDesc(*version.Name, desc)) + } + } + + return tags, cobra.ShellCompDirectiveNoFileComp +} + +// CompleteStackVersionBranch provides completion for the stack-branch flag. +// It fetches available branches from the stack's catalog repository versions. +func CompleteStackVersionBranch(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + org, err := GetOrg(cmd) + if err != nil { + return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError + } + + var stackRef string + stackRef, _ = GetStackRef(cmd) + + // If stack-ref is not provided, try to get it from the component (for update command) + if stackRef == "" { + project, errProj := GetProject(cmd) + env, errEnv := GetEnv(cmd) + component, errComp := GetComponent(cmd) + + if errProj == nil && errEnv == nil && errComp == nil { + api := common.NewAPI() + m := middleware.NewMiddleware(api) + + currentComponent, errGet := m.GetComponent(org, project, env, component) + if errGet == nil && currentComponent.ServiceCatalog != nil && currentComponent.ServiceCatalog.Ref != nil { + stackRef = *currentComponent.ServiceCatalog.Ref + } + } + } + + if stackRef == "" { + return cobra.AppendActiveHelp(nil, "missing stack-ref for completion: please provide --stack-ref flag"), + cobra.ShellCompDirectiveNoFileComp + } + + api := common.NewAPI() + m := middleware.NewMiddleware(api) + + versions, err := m.ListStackVersions(org, stackRef) + if err != nil { + return cobra.AppendActiveHelp(nil, "cannot find versions for stack: "+stackRef+", err: "+err.Error()), + cobra.ShellCompDirectiveNoFileComp + } + + var branches []string + for _, version := range versions { + if version.Type != nil && *version.Type == "branch" && version.Name != nil && strings.HasPrefix(*version.Name, toComplete) { + // Build description with commit hash + desc := "" + if version.CommitHash != nil { + commitHashShort := *version.CommitHash + if len(commitHashShort) > 8 { + commitHashShort = commitHashShort[:8] + } + desc = commitHashShort + } + + branches = append(branches, cobra.CompletionWithDesc(*version.Name, desc)) + } + } + + return branches, cobra.ShellCompDirectiveNoFileComp +} diff --git a/internal/testcfg/config.go b/internal/testcfg/config.go index b20fd4d0..673df6e9 100644 --- a/internal/testcfg/config.go +++ b/internal/testcfg/config.go @@ -11,6 +11,7 @@ import ( "github.com/cycloidio/cycloid-cli/client/models" "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" + "github.com/cycloidio/cycloid-cli/internal/ptr" ) type Config struct { @@ -18,9 +19,10 @@ type Config struct { APIUrl string Org string // GitCredential models.Credential - ConfigRepo *models.ConfigRepository - CatalogRepo *models.ServiceCatalogSource - Middleware middleware.Middleware + ConfigRepo *models.ConfigRepository + CatalogRepo *models.ServiceCatalogSource + CatalogRepoVersionStacks *models.ServiceCatalogSourceVersion + Middleware middleware.Middleware // Common project to use for tests that require one Project *models.Project // Common environment to use for tests that require one @@ -172,6 +174,21 @@ func NewConfig(testName string) (*Config, error) { } } + catalogRepoChanges, err := m.RefreshCatalogRepository(config.Org, *config.CatalogRepo.Canonical) + if err != nil { + return config, fmt.Errorf("failed to refresh catalog repo: %w", err) + } + + for _, v := range catalogRepoChanges.Versions { + if ptr.Value(v.Name) == "stacks" { + config.CatalogRepoVersionStacks = v + break + } + } + if config.CatalogRepoVersionStacks == nil { + return config, fmt.Errorf("failed to find latest catalog repo version after refresh") + } + project, err := config.NewTestProject("common") if err != nil { return config, err @@ -186,14 +203,14 @@ func NewConfig(testName string) (*Config, error) { stackRef := config.Org + ":" + defaultStackCanonical component, err := config.NewTestComponent( - *project.Canonical, *environment.Canonical, "common", stackRef, defaultStackUseCase, nil, + *project.Canonical, *environment.Canonical, "common", stackRef, defaultStackUseCase, "", "", *config.CatalogRepoVersionStacks.CommitHash, nil, ) if err != nil { return config, err } config.Component = component - stackConfig, err := m.GetComponentStackConfig(config.Org, *project.Canonical, *environment.Canonical, *component.Canonical, defaultStackUseCase) + stackConfig, err := m.GetComponentStackConfig(config.Org, *project.Canonical, *environment.Canonical, *component.Canonical, defaultStackUseCase, "", "", *config.CatalogRepoVersionStacks.CommitHash) if err != nil { return config, err } @@ -269,13 +286,11 @@ func (config *Config) NewTestEnv(identifier, project string) (*models.Environmen // setupTestProject will create an component with a random canonical derived from identifier // and return the component, the function to defer for its deletion and error. // The func will always be returned so even if err != nil, defer the func. -func (config *Config) NewTestComponent(project, env, identifier, stackRef, useCase string, inputs models.FormVariables) (*models.Component, error) { +func (config *Config) NewTestComponent(project, env, identifier, stackRef, useCase, versionTag, versionBranch, versionCommitHash string, inputs models.FormVariables) (*models.Component, error) { m := config.Middleware component := RandomCanonical(identifier) - outComponent, err := m.CreateAndConfigureComponent( - config.Org, project, env, component, "", &component, stackRef, useCase, "", inputs, - ) + outComponent, err := m.CreateAndConfigureComponent(config.Org, project, env, component, "", component, stackRef, versionTag, versionBranch, versionCommitHash, useCase, "", inputs) if err != nil { return nil, err }