From 1a0b732690086017861d87851010d0e829b28e01 Mon Sep 17 00:00:00 2001 From: Teodora Sandu Date: Tue, 2 Apr 2024 17:13:06 +0100 Subject: [PATCH 1/3] feat: add client for the orchestration API --- .gitignore | 4 +- Makefile | 1 + internal/orchestration/2024-02-16/client.go | 960 ++++++++++++++++++ .../orchestration/2024-02-16/client_test.go | 313 ++++++ .../2024-02-16/common/common.config.yaml | 6 + .../orchestration/2024-02-16/common/common.go | 227 +++++ internal/orchestration/2024-02-16/gen.go | 7 + .../2024-02-16/parameters/orgs.config.yaml | 6 + .../2024-02-16/parameters/orgs.go | 11 + .../2024-02-16/parameters/scans.config.yaml | 6 + .../2024-02-16/parameters/scans.go | 11 + .../2024-02-16/scans/scans.config.yaml | 8 + .../orchestration/2024-02-16/scans/scans.go | 273 +++++ .../orchestration/2024-02-16/spec.config.yaml | 12 + internal/workspace/2024-03-12/client.go | 5 +- internal/workspace/2024-03-12/client_test.go | 93 +- scripts/download-orchestration-api.sh | 63 ++ 17 files changed, 1997 insertions(+), 9 deletions(-) create mode 100644 internal/orchestration/2024-02-16/client.go create mode 100644 internal/orchestration/2024-02-16/client_test.go create mode 100644 internal/orchestration/2024-02-16/common/common.config.yaml create mode 100644 internal/orchestration/2024-02-16/common/common.go create mode 100644 internal/orchestration/2024-02-16/gen.go create mode 100644 internal/orchestration/2024-02-16/parameters/orgs.config.yaml create mode 100644 internal/orchestration/2024-02-16/parameters/orgs.go create mode 100644 internal/orchestration/2024-02-16/parameters/scans.config.yaml create mode 100644 internal/orchestration/2024-02-16/parameters/scans.go create mode 100644 internal/orchestration/2024-02-16/scans/scans.config.yaml create mode 100644 internal/orchestration/2024-02-16/scans/scans.go create mode 100644 internal/orchestration/2024-02-16/spec.config.yaml create mode 100755 scripts/download-orchestration-api.sh diff --git a/.gitignore b/.gitignore index 4c4e9607..58513598 100644 --- a/.gitignore +++ b/.gitignore @@ -50,4 +50,6 @@ webidentity.json # Development files # ################################# internal/workspace/**/**/*.yaml -!internal/workspace/**/**/*.config.yaml \ No newline at end of file +!internal/workspace/**/**/*.config.yaml +internal/orchestration/**/**/*.yaml +!internal/orchestration/**/**/*.config.yaml \ No newline at end of file diff --git a/Makefile b/Makefile index d4d9124d..72acd895 100644 --- a/Makefile +++ b/Makefile @@ -66,6 +66,7 @@ download-apis: download-workspace-api .PHONY: download-workspace-api download-workspace-api: ./scripts/download-workspace-api.sh + ./scripts/download-orchestration-api.sh .PHONY: help help: diff --git a/internal/orchestration/2024-02-16/client.go b/internal/orchestration/2024-02-16/client.go new file mode 100644 index 00000000..2fff2fad --- /dev/null +++ b/internal/orchestration/2024-02-16/client.go @@ -0,0 +1,960 @@ +// Package v20240216 provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/deepmap/oapi-codegen version v1.13.4 DO NOT EDIT. +package v20240216 + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/deepmap/oapi-codegen/pkg/runtime" + externalRef0 "github.com/snyk/code-client-go/internal/orchestration/2024-02-16/common" + externalRef1 "github.com/snyk/code-client-go/internal/orchestration/2024-02-16/parameters" + externalRef2 "github.com/snyk/code-client-go/internal/orchestration/2024-02-16/scans" +) + +const ( + BearerAuthScopes = "bearerAuth.Scopes" +) + +// CreateScanWorkspaceJobInternalParams defines parameters for CreateScanWorkspaceJobInternal. +type CreateScanWorkspaceJobInternalParams struct { + // Version The requested version of the endpoint to process the request + Version externalRef0.Version `form:"version" json:"version"` +} + +// GetScanWorkspaceJobInternalParams defines parameters for GetScanWorkspaceJobInternal. +type GetScanWorkspaceJobInternalParams struct { + // Version The requested version of the endpoint to process the request + Version externalRef0.Version `form:"version" json:"version"` +} + +// CreateScanWorkspaceJobForUserParams defines parameters for CreateScanWorkspaceJobForUser. +type CreateScanWorkspaceJobForUserParams struct { + // Version The requested version of the endpoint to process the request + Version externalRef0.Version `form:"version" json:"version"` +} + +// GetScanWorkspaceJobForUserParams defines parameters for GetScanWorkspaceJobForUser. +type GetScanWorkspaceJobForUserParams struct { + // Version The requested version of the endpoint to process the request + Version externalRef0.Version `form:"version" json:"version"` +} + +// CreateScanWorkspaceJobInternalApplicationVndAPIPlusJSONRequestBody defines body for CreateScanWorkspaceJobInternal for application/vnd.api+json ContentType. +type CreateScanWorkspaceJobInternalApplicationVndAPIPlusJSONRequestBody = externalRef2.PostScanRequest + +// CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody defines body for CreateScanWorkspaceJobForUser for application/vnd.api+json ContentType. +type CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody = externalRef2.PostScanRequest + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // CreateScanWorkspaceJobInternalWithBody request with any body + CreateScanWorkspaceJobInternalWithBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateScanWorkspaceJobInternalWithApplicationVndAPIPlusJSONBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, body CreateScanWorkspaceJobInternalApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetScanWorkspaceJobInternal request + GetScanWorkspaceJobInternal(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobInternalParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateScanWorkspaceJobForUserWithBody request with any body + CreateScanWorkspaceJobForUserWithBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, body CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetScanWorkspaceJobForUser request + GetScanWorkspaceJobForUser(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobForUserParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) CreateScanWorkspaceJobInternalWithBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateScanWorkspaceJobInternalRequestWithBody(c.Server, orgId, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateScanWorkspaceJobInternalWithApplicationVndAPIPlusJSONBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, body CreateScanWorkspaceJobInternalApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateScanWorkspaceJobInternalRequestWithApplicationVndAPIPlusJSONBody(c.Server, orgId, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetScanWorkspaceJobInternal(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobInternalParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetScanWorkspaceJobInternalRequest(c.Server, orgId, scanjobId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateScanWorkspaceJobForUserWithBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateScanWorkspaceJobForUserRequestWithBody(c.Server, orgId, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBody(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, body CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateScanWorkspaceJobForUserRequestWithApplicationVndAPIPlusJSONBody(c.Server, orgId, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetScanWorkspaceJobForUser(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobForUserParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetScanWorkspaceJobForUserRequest(c.Server, orgId, scanjobId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewCreateScanWorkspaceJobInternalRequestWithApplicationVndAPIPlusJSONBody calls the generic CreateScanWorkspaceJobInternal builder with application/vnd.api+json body +func NewCreateScanWorkspaceJobInternalRequestWithApplicationVndAPIPlusJSONBody(server string, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, body CreateScanWorkspaceJobInternalApplicationVndAPIPlusJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateScanWorkspaceJobInternalRequestWithBody(server, orgId, params, "application/vnd.api+json", bodyReader) +} + +// NewCreateScanWorkspaceJobInternalRequestWithBody generates requests for CreateScanWorkspaceJobInternal with any type of body +func NewCreateScanWorkspaceJobInternalRequestWithBody(server string, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "org_id", runtime.ParamLocationPath, orgId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/internal/orgs/%s/scans", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "version", runtime.ParamLocationQuery, params.Version); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetScanWorkspaceJobInternalRequest generates requests for GetScanWorkspaceJobInternal +func NewGetScanWorkspaceJobInternalRequest(server string, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobInternalParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "org_id", runtime.ParamLocationPath, orgId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "scanjob_id", runtime.ParamLocationPath, scanjobId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/internal/orgs/%s/scans/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "version", runtime.ParamLocationQuery, params.Version); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateScanWorkspaceJobForUserRequestWithApplicationVndAPIPlusJSONBody calls the generic CreateScanWorkspaceJobForUser builder with application/vnd.api+json body +func NewCreateScanWorkspaceJobForUserRequestWithApplicationVndAPIPlusJSONBody(server string, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, body CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateScanWorkspaceJobForUserRequestWithBody(server, orgId, params, "application/vnd.api+json", bodyReader) +} + +// NewCreateScanWorkspaceJobForUserRequestWithBody generates requests for CreateScanWorkspaceJobForUser with any type of body +func NewCreateScanWorkspaceJobForUserRequestWithBody(server string, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "org_id", runtime.ParamLocationPath, orgId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/orgs/%s/scans", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "version", runtime.ParamLocationQuery, params.Version); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetScanWorkspaceJobForUserRequest generates requests for GetScanWorkspaceJobForUser +func NewGetScanWorkspaceJobForUserRequest(server string, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobForUserParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "org_id", runtime.ParamLocationPath, orgId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "scanjob_id", runtime.ParamLocationPath, scanjobId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/orgs/%s/scans/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "version", runtime.ParamLocationQuery, params.Version); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // CreateScanWorkspaceJobInternalWithBodyWithResponse request with any body + CreateScanWorkspaceJobInternalWithBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobInternalResponse, error) + + CreateScanWorkspaceJobInternalWithApplicationVndAPIPlusJSONBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, body CreateScanWorkspaceJobInternalApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobInternalResponse, error) + + // GetScanWorkspaceJobInternalWithResponse request + GetScanWorkspaceJobInternalWithResponse(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobInternalParams, reqEditors ...RequestEditorFn) (*GetScanWorkspaceJobInternalResponse, error) + + // CreateScanWorkspaceJobForUserWithBodyWithResponse request with any body + CreateScanWorkspaceJobForUserWithBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobForUserResponse, error) + + CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, body CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobForUserResponse, error) + + // GetScanWorkspaceJobForUserWithResponse request + GetScanWorkspaceJobForUserWithResponse(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobForUserParams, reqEditors ...RequestEditorFn) (*GetScanWorkspaceJobForUserResponse, error) +} + +type CreateScanWorkspaceJobInternalResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationvndApiJSON201 *externalRef2.ScanResponse + ApplicationvndApiJSON400 *externalRef0.N400 + ApplicationvndApiJSON401 *externalRef0.N401 + ApplicationvndApiJSON403 *externalRef0.N403 + ApplicationvndApiJSON404 *externalRef0.N404 + ApplicationvndApiJSON429 *externalRef0.ErrorDocument + ApplicationvndApiJSON500 *externalRef0.N500 +} + +// Status returns HTTPResponse.Status +func (r CreateScanWorkspaceJobInternalResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateScanWorkspaceJobInternalResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetScanWorkspaceJobInternalResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationvndApiJSON200 *externalRef2.ScanResultsResponse + ApplicationvndApiJSON400 *externalRef0.N400 + ApplicationvndApiJSON401 *externalRef0.N401 + ApplicationvndApiJSON403 *externalRef0.N403 + ApplicationvndApiJSON404 *externalRef0.N404 + ApplicationvndApiJSON429 *externalRef0.ErrorDocument + ApplicationvndApiJSON500 *externalRef0.N500 +} + +// Status returns HTTPResponse.Status +func (r GetScanWorkspaceJobInternalResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetScanWorkspaceJobInternalResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateScanWorkspaceJobForUserResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationvndApiJSON201 *externalRef2.ScanResponse + ApplicationvndApiJSON400 *externalRef0.N400 + ApplicationvndApiJSON401 *externalRef0.N401 + ApplicationvndApiJSON403 *externalRef0.N403 + ApplicationvndApiJSON404 *externalRef0.N404 + ApplicationvndApiJSON429 *externalRef0.ErrorDocument + ApplicationvndApiJSON500 *externalRef0.N500 +} + +// Status returns HTTPResponse.Status +func (r CreateScanWorkspaceJobForUserResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateScanWorkspaceJobForUserResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetScanWorkspaceJobForUserResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationvndApiJSON200 *externalRef2.ScanResultsResponse + ApplicationvndApiJSON400 *externalRef0.N400 + ApplicationvndApiJSON401 *externalRef0.N401 + ApplicationvndApiJSON403 *externalRef0.N403 + ApplicationvndApiJSON404 *externalRef0.N404 + ApplicationvndApiJSON429 *externalRef0.ErrorDocument + ApplicationvndApiJSON500 *externalRef0.N500 +} + +// Status returns HTTPResponse.Status +func (r GetScanWorkspaceJobForUserResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetScanWorkspaceJobForUserResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// CreateScanWorkspaceJobInternalWithBodyWithResponse request with arbitrary body returning *CreateScanWorkspaceJobInternalResponse +func (c *ClientWithResponses) CreateScanWorkspaceJobInternalWithBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobInternalResponse, error) { + rsp, err := c.CreateScanWorkspaceJobInternalWithBody(ctx, orgId, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateScanWorkspaceJobInternalResponse(rsp) +} + +func (c *ClientWithResponses) CreateScanWorkspaceJobInternalWithApplicationVndAPIPlusJSONBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobInternalParams, body CreateScanWorkspaceJobInternalApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobInternalResponse, error) { + rsp, err := c.CreateScanWorkspaceJobInternalWithApplicationVndAPIPlusJSONBody(ctx, orgId, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateScanWorkspaceJobInternalResponse(rsp) +} + +// GetScanWorkspaceJobInternalWithResponse request returning *GetScanWorkspaceJobInternalResponse +func (c *ClientWithResponses) GetScanWorkspaceJobInternalWithResponse(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobInternalParams, reqEditors ...RequestEditorFn) (*GetScanWorkspaceJobInternalResponse, error) { + rsp, err := c.GetScanWorkspaceJobInternal(ctx, orgId, scanjobId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetScanWorkspaceJobInternalResponse(rsp) +} + +// CreateScanWorkspaceJobForUserWithBodyWithResponse request with arbitrary body returning *CreateScanWorkspaceJobForUserResponse +func (c *ClientWithResponses) CreateScanWorkspaceJobForUserWithBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobForUserResponse, error) { + rsp, err := c.CreateScanWorkspaceJobForUserWithBody(ctx, orgId, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateScanWorkspaceJobForUserResponse(rsp) +} + +func (c *ClientWithResponses) CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBodyWithResponse(ctx context.Context, orgId externalRef1.OrgId, params *CreateScanWorkspaceJobForUserParams, body CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateScanWorkspaceJobForUserResponse, error) { + rsp, err := c.CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBody(ctx, orgId, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateScanWorkspaceJobForUserResponse(rsp) +} + +// GetScanWorkspaceJobForUserWithResponse request returning *GetScanWorkspaceJobForUserResponse +func (c *ClientWithResponses) GetScanWorkspaceJobForUserWithResponse(ctx context.Context, orgId externalRef1.OrgId, scanjobId externalRef1.ScanJobId, params *GetScanWorkspaceJobForUserParams, reqEditors ...RequestEditorFn) (*GetScanWorkspaceJobForUserResponse, error) { + rsp, err := c.GetScanWorkspaceJobForUser(ctx, orgId, scanjobId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetScanWorkspaceJobForUserResponse(rsp) +} + +// ParseCreateScanWorkspaceJobInternalResponse parses an HTTP response from a CreateScanWorkspaceJobInternalWithResponse call +func ParseCreateScanWorkspaceJobInternalResponse(rsp *http.Response) (*CreateScanWorkspaceJobInternalResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateScanWorkspaceJobInternalResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest externalRef2.ScanResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest externalRef0.N400 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest externalRef0.N401 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest externalRef0.N403 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest externalRef0.N404 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest externalRef0.ErrorDocument + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest externalRef0.N500 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON500 = &dest + + } + + return response, nil +} + +// ParseGetScanWorkspaceJobInternalResponse parses an HTTP response from a GetScanWorkspaceJobInternalWithResponse call +func ParseGetScanWorkspaceJobInternalResponse(rsp *http.Response) (*GetScanWorkspaceJobInternalResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetScanWorkspaceJobInternalResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest externalRef2.ScanResultsResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest externalRef0.N400 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest externalRef0.N401 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest externalRef0.N403 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest externalRef0.N404 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest externalRef0.ErrorDocument + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest externalRef0.N500 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON500 = &dest + + } + + return response, nil +} + +// ParseCreateScanWorkspaceJobForUserResponse parses an HTTP response from a CreateScanWorkspaceJobForUserWithResponse call +func ParseCreateScanWorkspaceJobForUserResponse(rsp *http.Response) (*CreateScanWorkspaceJobForUserResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateScanWorkspaceJobForUserResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest externalRef2.ScanResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest externalRef0.N400 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest externalRef0.N401 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest externalRef0.N403 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest externalRef0.N404 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest externalRef0.ErrorDocument + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest externalRef0.N500 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON500 = &dest + + } + + return response, nil +} + +// ParseGetScanWorkspaceJobForUserResponse parses an HTTP response from a GetScanWorkspaceJobForUserWithResponse call +func ParseGetScanWorkspaceJobForUserResponse(rsp *http.Response) (*GetScanWorkspaceJobForUserResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetScanWorkspaceJobForUserResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest externalRef2.ScanResultsResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest externalRef0.N400 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest externalRef0.N401 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest externalRef0.N403 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest externalRef0.N404 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest externalRef0.ErrorDocument + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest externalRef0.N500 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationvndApiJSON500 = &dest + + } + + return response, nil +} diff --git a/internal/orchestration/2024-02-16/client_test.go b/internal/orchestration/2024-02-16/client_test.go new file mode 100644 index 00000000..0f0b0a45 --- /dev/null +++ b/internal/orchestration/2024-02-16/client_test.go @@ -0,0 +1,313 @@ +package v20240216_test + +import ( + "bytes" + "context" + "errors" + openapi_types "github.com/deepmap/oapi-codegen/pkg/types" + externalRef2 "github.com/snyk/code-client-go/internal/orchestration/2024-02-16/scans" + "io" + "net/http" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + orchestrationClient "github.com/snyk/code-client-go/internal/orchestration/2024-02-16" +) + +// HTTPRequestDoerMock mocks the interface HttpRequestDoerMock. +type HTTPRequestDoerMock struct { + mock.Mock +} + +func (m *HTTPRequestDoerMock) Do(req *http.Request) (*http.Response, error) { + args := m.Called(req) + if args.Get(0) == nil { + return nil, args.Error(1) + } + return args.Get(0).(*http.Response), args.Error(1) +} + +func TestOrchestration_CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBody_Success(t *testing.T) { + doer := &HTTPRequestDoerMock{} + mockResponse := http.Response{ + Body: io.NopCloser(bytes.NewBufferString(`{ + "data": { + "attributes": { + "created_at": "2017-07-21T17:32:28Z", + "status": "complete" + }, + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "type": "scan_job" + }, + "jsonapi": { + "version": "1.0" + }, + "links": { + "self": "https://example.com/api/this_resource" + } +}`)), + Header: http.Header{ + "Content-Type": []string{"application/json"}, + }, + StatusCode: http.StatusCreated, + } + doer.On("Do", mock.Anything).Return(&mockResponse, nil).Run(func(args mock.Arguments) { + req, ok := args.Get(0).(*http.Request) + assert.True(t, ok) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/scans?version=2024-02-16~experimental", req.URL.String()) + }) + client, err := orchestrationClient.NewClientWithResponses("https://api.snyk.io/rest", orchestrationClient.WithHTTPClient(doer)) + require.NoError(t, err) + + orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") + id := uuid.New() + response, err := client.CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBodyWithResponse( + context.Background(), + orgUUID, + &orchestrationClient.CreateScanWorkspaceJobForUserParams{Version: "2024-02-16~experimental"}, + orchestrationClient.CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody{Data: struct { + Attributes struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + } `json:"attributes"` + Id *openapi_types.UUID `json:"id,omitempty"` + Type externalRef2.PostScanRequestDataType `json:"type"` + }(struct { + Attributes struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + } + Id *openapi_types.UUID + Type externalRef2.PostScanRequestDataType + }{ + Attributes: struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + }(struct { + Flow externalRef2.Flow + WorkspaceUrl string + }{}), + Id: &id, + Type: "cli", + })}) + require.NoError(t, err) + require.NotNil(t, response) + require.Equal(t, 201, response.StatusCode()) + require.Equal(t, "3fa85f64-5717-4562-b3fc-2c963f66afa6", response.ApplicationvndApiJSON201.Data.Id.String()) + doer.AssertExpectations(t) +} + +func TestOrchestration_CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBody_Success_NotFound(t *testing.T) { + doer := &HTTPRequestDoerMock{} + mockResponse := http.Response{ + Body: io.NopCloser(bytes.NewBufferString(`{ + "errors": [], + "jsonapi": { + "version": "1.0" + } +}`)), + Header: http.Header{ + "Content-Type": []string{"application/json"}, + }, + StatusCode: http.StatusNotFound, + } + doer.On("Do", mock.Anything).Return(&mockResponse, nil).Run(func(args mock.Arguments) { + req, ok := args.Get(0).(*http.Request) + assert.True(t, ok) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/scans?version=2024-02-16~experimental", req.URL.String()) + }) + client, err := orchestrationClient.NewClientWithResponses("https://api.snyk.io/rest", orchestrationClient.WithHTTPClient(doer)) + require.NoError(t, err) + + orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") + id := uuid.New() + response, err := client.CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBodyWithResponse( + context.Background(), + orgUUID, + &orchestrationClient.CreateScanWorkspaceJobForUserParams{Version: "2024-02-16~experimental"}, + orchestrationClient.CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody{Data: struct { + Attributes struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + } `json:"attributes"` + Id *openapi_types.UUID `json:"id,omitempty"` + Type externalRef2.PostScanRequestDataType `json:"type"` + }(struct { + Attributes struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + } + Id *openapi_types.UUID + Type externalRef2.PostScanRequestDataType + }{ + Attributes: struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + }(struct { + Flow externalRef2.Flow + WorkspaceUrl string + }{}), + Id: &id, + Type: "cli", + })}) + require.NoError(t, err) + require.NotNil(t, response) + require.Equal(t, http.StatusNotFound, response.StatusCode()) + require.NotNil(t, response.ApplicationvndApiJSON404.Errors) + doer.AssertExpectations(t) +} + +func TestOrchestration_CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBody_Failure(t *testing.T) { + doer := &HTTPRequestDoerMock{} + doer.On("Do", mock.Anything).Return(nil, errors.New("something went wrong")).Run(func(args mock.Arguments) { + req, ok := args.Get(0).(*http.Request) + assert.True(t, ok) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/scans?version=2024-02-16~experimental", req.URL.String()) + }) + client, err := orchestrationClient.NewClientWithResponses("https://api.snyk.io/rest", orchestrationClient.WithHTTPClient(doer)) + require.NoError(t, err) + + orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") + id := uuid.New() + _, err = client.CreateScanWorkspaceJobForUserWithApplicationVndAPIPlusJSONBodyWithResponse( + context.Background(), + orgUUID, + &orchestrationClient.CreateScanWorkspaceJobForUserParams{Version: "2024-02-16~experimental"}, + orchestrationClient.CreateScanWorkspaceJobForUserApplicationVndAPIPlusJSONRequestBody{Data: struct { + Attributes struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + } `json:"attributes"` + Id *openapi_types.UUID `json:"id,omitempty"` + Type externalRef2.PostScanRequestDataType `json:"type"` + }(struct { + Attributes struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + } + Id *openapi_types.UUID + Type externalRef2.PostScanRequestDataType + }{ + Attributes: struct { + Flow externalRef2.Flow `json:"flow"` + WorkspaceUrl string `json:"workspace_url"` + }(struct { + Flow externalRef2.Flow + WorkspaceUrl string + }{}), + Id: &id, + Type: "cli", + })}) + require.Error(t, err) + doer.AssertExpectations(t) +} + +func TestOrchestration_GetScanWorkspaceJobForUserWithResponse_Success(t *testing.T) { + doer := &HTTPRequestDoerMock{} + mockResponse := http.Response{ + Body: io.NopCloser(bytes.NewBufferString(`{ + "data": { + "attributes": { + "components": [ + { + "created_at": "2017-07-21T17:32:28Z", + "findings_url": "http://findings/url", + "id": "123e4567-e89b-12d3-a456-426655440000", + "name": "src/main.ts", + "type": "typescript" + } + ], + "created_at": "2017-07-21T17:32:28Z", + "status": "in_progress" + }, + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "type": "scan_job_results" + } +}`)), + Header: http.Header{ + "Content-Type": []string{"application/json"}, + }, + StatusCode: http.StatusOK, + } + doer.On("Do", mock.Anything).Return(&mockResponse, nil).Run(func(args mock.Arguments) { + req, ok := args.Get(0).(*http.Request) + assert.True(t, ok) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/scans/b23b92f8-6b3e-4daa-9f15-1083224b25d0?version=2024-02-16~experimental", req.URL.String()) + }) + client, err := orchestrationClient.NewClientWithResponses("https://api.snyk.io/rest", orchestrationClient.WithHTTPClient(doer)) + require.NoError(t, err) + + orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") + id := uuid.MustParse("b23b92f8-6b3e-4daa-9f15-1083224b25d0") + response, err := client.GetScanWorkspaceJobForUserWithResponse( + context.Background(), + orgUUID, + id, + &orchestrationClient.GetScanWorkspaceJobForUserParams{Version: "2024-02-16~experimental"}) + require.NoError(t, err) + require.NotNil(t, response) + require.Equal(t, http.StatusOK, response.StatusCode()) + require.Equal(t, externalRef2.ScanJobResultsAttributesStatusInProgress, response.ApplicationvndApiJSON200.Data.Attributes.Status) + doer.AssertExpectations(t) +} + +func TestOrchestration_GetScanWorkspaceJobForUserWithResponse_Success_NotFound(t *testing.T) { + doer := &HTTPRequestDoerMock{} + mockResponse := http.Response{ + Body: io.NopCloser(bytes.NewBufferString(`{ + "errors": [], + "jsonapi": { + "version": "1.0" + } +}`)), + Header: http.Header{ + "Content-Type": []string{"application/json"}, + }, + StatusCode: http.StatusNotFound, + } + doer.On("Do", mock.Anything).Return(&mockResponse, nil).Run(func(args mock.Arguments) { + req, ok := args.Get(0).(*http.Request) + assert.True(t, ok) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/scans/b23b92f8-6b3e-4daa-9f15-1083224b25d0?version=2024-02-16~experimental", req.URL.String()) + }) + client, err := orchestrationClient.NewClientWithResponses("https://api.snyk.io/rest", orchestrationClient.WithHTTPClient(doer)) + require.NoError(t, err) + + orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") + id := uuid.MustParse("b23b92f8-6b3e-4daa-9f15-1083224b25d0") + response, err := client.GetScanWorkspaceJobForUserWithResponse( + context.Background(), + orgUUID, + id, + &orchestrationClient.GetScanWorkspaceJobForUserParams{Version: "2024-02-16~experimental"}) + require.NoError(t, err) + require.NotNil(t, response) + require.Equal(t, http.StatusNotFound, response.StatusCode()) + require.NotNil(t, response.ApplicationvndApiJSON404.Errors) + doer.AssertExpectations(t) +} + +func TestOrchestration_GetScanWorkspaceJobForUserWithResponse_Failure(t *testing.T) { + doer := &HTTPRequestDoerMock{} + doer.On("Do", mock.Anything).Return(nil, errors.New("something went wrong")).Run(func(args mock.Arguments) { + req, ok := args.Get(0).(*http.Request) + assert.True(t, ok) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/scans/b23b92f8-6b3e-4daa-9f15-1083224b25d0?version=2024-02-16~experimental", req.URL.String()) + }) + client, err := orchestrationClient.NewClientWithResponses("https://api.snyk.io/rest", orchestrationClient.WithHTTPClient(doer)) + require.NoError(t, err) + + orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") + id := uuid.MustParse("b23b92f8-6b3e-4daa-9f15-1083224b25d0") + _, err = client.GetScanWorkspaceJobForUserWithResponse( + context.Background(), + orgUUID, + id, + &orchestrationClient.GetScanWorkspaceJobForUserParams{Version: "2024-02-16~experimental"}) + require.Error(t, err) + doer.AssertExpectations(t) +} diff --git a/internal/orchestration/2024-02-16/common/common.config.yaml b/internal/orchestration/2024-02-16/common/common.config.yaml new file mode 100644 index 00000000..05e86664 --- /dev/null +++ b/internal/orchestration/2024-02-16/common/common.config.yaml @@ -0,0 +1,6 @@ +package: v20240216 +generate: + models: true +output-options: + skip-prune: true +output: common/common.go \ No newline at end of file diff --git a/internal/orchestration/2024-02-16/common/common.go b/internal/orchestration/2024-02-16/common/common.go new file mode 100644 index 00000000..931857da --- /dev/null +++ b/internal/orchestration/2024-02-16/common/common.go @@ -0,0 +1,227 @@ +// Package v20240216 provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/deepmap/oapi-codegen version v1.13.4 DO NOT EDIT. +package v20240216 + +import ( + "encoding/json" + + "github.com/deepmap/oapi-codegen/pkg/runtime" + openapi_types "github.com/deepmap/oapi-codegen/pkg/types" +) + +// ActualVersion Resolved API version +type ActualVersion = string + +// Error defines model for Error. +type Error struct { + // Code An application-specific error code, expressed as a string value. + Code *string `json:"code,omitempty"` + + // Detail A human-readable explanation specific to this occurrence of the problem. + Detail string `json:"detail"` + + // Id A unique identifier for this particular occurrence of the problem. + Id *openapi_types.UUID `json:"id,omitempty"` + + // Links A link that leads to further details about this particular occurrance of the problem. + Links *ErrorLink `json:"links,omitempty"` + Meta *map[string]interface{} `json:"meta,omitempty"` + Source *struct { + // Parameter A string indicating which URI query parameter caused the error. + Parameter *string `json:"parameter,omitempty"` + + // Pointer A JSON Pointer [RFC6901] to the associated entity in the request document. + Pointer *string `json:"pointer,omitempty"` + } `json:"source,omitempty"` + + // Status The HTTP status code applicable to this problem, expressed as a string value. + Status string `json:"status"` + + // Title A short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization. + Title *string `json:"title,omitempty"` +} + +// ErrorDocument defines model for ErrorDocument. +type ErrorDocument struct { + Errors []Error `json:"errors"` + Jsonapi JsonApi `json:"jsonapi"` +} + +// ErrorLink A link that leads to further details about this particular occurrance of the problem. +type ErrorLink struct { + About *LinkProperty `json:"about,omitempty"` +} + +// JsonApi defines model for JsonApi. +type JsonApi struct { + // Version Version of the JSON API specification this server supports. + Version string `json:"version"` +} + +// LinkProperty defines model for LinkProperty. +type LinkProperty struct { + union json.RawMessage +} + +// LinkProperty0 A string containing the link’s URL. +type LinkProperty0 = string + +// LinkProperty1 defines model for . +type LinkProperty1 struct { + // Href A string containing the link’s URL. + Href string `json:"href"` + + // Meta Free-form object that may contain non-standard information. + Meta *Meta `json:"meta,omitempty"` +} + +// Links defines model for Links. +type Links struct { + First *LinkProperty `json:"first,omitempty"` + Last *LinkProperty `json:"last,omitempty"` + Next *LinkProperty `json:"next,omitempty"` + Prev *LinkProperty `json:"prev,omitempty"` + Related *LinkProperty `json:"related,omitempty"` + Self *LinkProperty `json:"self,omitempty"` +} + +// Meta Free-form object that may contain non-standard information. +type Meta map[string]interface{} + +// PaginatedLinks defines model for PaginatedLinks. +type PaginatedLinks struct { + First *LinkProperty `json:"first,omitempty"` + Last *LinkProperty `json:"last,omitempty"` + Next *LinkProperty `json:"next,omitempty"` + Prev *LinkProperty `json:"prev,omitempty"` + Self *LinkProperty `json:"self,omitempty"` +} + +// QueryVersion Requested API version +type QueryVersion = string + +// RelatedLink defines model for RelatedLink. +type RelatedLink struct { + Related *LinkProperty `json:"related,omitempty"` +} + +// Relationship defines model for Relationship. +type Relationship struct { + Data struct { + Id openapi_types.UUID `json:"id"` + + // Type Type of the related resource + Type string `json:"type"` + } `json:"data"` + Links RelatedLink `json:"links"` + + // Meta Free-form object that may contain non-standard information. + Meta *Meta `json:"meta,omitempty"` +} + +// SelfLink defines model for SelfLink. +type SelfLink struct { + Self *LinkProperty `json:"self,omitempty"` +} + +// Tag defines model for Tag. +type Tag struct { + Key string `json:"key"` + Value string `json:"value"` +} + +// Types defines model for Types. +type Types = string + +// EndingBefore defines model for EndingBefore. +type EndingBefore = string + +// Limit defines model for Limit. +type Limit = int32 + +// StartingAfter defines model for StartingAfter. +type StartingAfter = string + +// Version Requested API version +type Version = QueryVersion + +// N400 defines model for 400. +type N400 = ErrorDocument + +// N401 defines model for 401. +type N401 = ErrorDocument + +// N403 defines model for 403. +type N403 = ErrorDocument + +// N404 defines model for 404. +type N404 = ErrorDocument + +// N409 defines model for 409. +type N409 = ErrorDocument + +// N500 defines model for 500. +type N500 = ErrorDocument + +// AsLinkProperty0 returns the union data inside the LinkProperty as a LinkProperty0 +func (t LinkProperty) AsLinkProperty0() (LinkProperty0, error) { + var body LinkProperty0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromLinkProperty0 overwrites any union data inside the LinkProperty as the provided LinkProperty0 +func (t *LinkProperty) FromLinkProperty0(v LinkProperty0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeLinkProperty0 performs a merge with any union data inside the LinkProperty, using the provided LinkProperty0 +func (t *LinkProperty) MergeLinkProperty0(v LinkProperty0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +// AsLinkProperty1 returns the union data inside the LinkProperty as a LinkProperty1 +func (t LinkProperty) AsLinkProperty1() (LinkProperty1, error) { + var body LinkProperty1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromLinkProperty1 overwrites any union data inside the LinkProperty as the provided LinkProperty1 +func (t *LinkProperty) FromLinkProperty1(v LinkProperty1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeLinkProperty1 performs a merge with any union data inside the LinkProperty, using the provided LinkProperty1 +func (t *LinkProperty) MergeLinkProperty1(v LinkProperty1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +func (t LinkProperty) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *LinkProperty) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} diff --git a/internal/orchestration/2024-02-16/gen.go b/internal/orchestration/2024-02-16/gen.go new file mode 100644 index 00000000..353dd6f1 --- /dev/null +++ b/internal/orchestration/2024-02-16/gen.go @@ -0,0 +1,7 @@ +package v20240216 + +//go:generate oapi-codegen --config common/common.config.yaml common/common.yaml +//go:generate oapi-codegen --config parameters/orgs.config.yaml parameters/orgs.yaml +//go:generate oapi-codegen --config parameters/scans.config.yaml parameters/scans.yaml +//go:generate oapi-codegen --config scans/scans.config.yaml scans/scans.yaml +//go:generate oapi-codegen --config spec.config.yaml spec.yaml diff --git a/internal/orchestration/2024-02-16/parameters/orgs.config.yaml b/internal/orchestration/2024-02-16/parameters/orgs.config.yaml new file mode 100644 index 00000000..33d9c003 --- /dev/null +++ b/internal/orchestration/2024-02-16/parameters/orgs.config.yaml @@ -0,0 +1,6 @@ +package: v20240216 +generate: + models: true +output-options: + skip-prune: true +output: parameters/orgs.go \ No newline at end of file diff --git a/internal/orchestration/2024-02-16/parameters/orgs.go b/internal/orchestration/2024-02-16/parameters/orgs.go new file mode 100644 index 00000000..0b982c1e --- /dev/null +++ b/internal/orchestration/2024-02-16/parameters/orgs.go @@ -0,0 +1,11 @@ +// Package v20240216 provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/deepmap/oapi-codegen version v1.13.4 DO NOT EDIT. +package v20240216 + +import ( + openapi_types "github.com/deepmap/oapi-codegen/pkg/types" +) + +// OrgId defines model for OrgId. +type OrgId = openapi_types.UUID diff --git a/internal/orchestration/2024-02-16/parameters/scans.config.yaml b/internal/orchestration/2024-02-16/parameters/scans.config.yaml new file mode 100644 index 00000000..e1bd4b03 --- /dev/null +++ b/internal/orchestration/2024-02-16/parameters/scans.config.yaml @@ -0,0 +1,6 @@ +package: v20240216 +generate: + models: true +output-options: + skip-prune: true +output: parameters/scans.go \ No newline at end of file diff --git a/internal/orchestration/2024-02-16/parameters/scans.go b/internal/orchestration/2024-02-16/parameters/scans.go new file mode 100644 index 00000000..39b6af38 --- /dev/null +++ b/internal/orchestration/2024-02-16/parameters/scans.go @@ -0,0 +1,11 @@ +// Package v20240216 provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/deepmap/oapi-codegen version v1.13.4 DO NOT EDIT. +package v20240216 + +import ( + openapi_types "github.com/deepmap/oapi-codegen/pkg/types" +) + +// ScanJobId defines model for ScanJobId. +type ScanJobId = openapi_types.UUID diff --git a/internal/orchestration/2024-02-16/scans/scans.config.yaml b/internal/orchestration/2024-02-16/scans/scans.config.yaml new file mode 100644 index 00000000..0a5f8620 --- /dev/null +++ b/internal/orchestration/2024-02-16/scans/scans.config.yaml @@ -0,0 +1,8 @@ +package: v20240216 +generate: + models: true +output-options: + skip-prune: true +import-mapping: + ../common/common.yaml: github.com/snyk/code-client-go/internal/workspace/2024-03-12/common +output: scans/scans.go \ No newline at end of file diff --git a/internal/orchestration/2024-02-16/scans/scans.go b/internal/orchestration/2024-02-16/scans/scans.go new file mode 100644 index 00000000..1727221e --- /dev/null +++ b/internal/orchestration/2024-02-16/scans/scans.go @@ -0,0 +1,273 @@ +// Package v20240216 provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/deepmap/oapi-codegen version v1.13.4 DO NOT EDIT. +package v20240216 + +import ( + "encoding/json" + "errors" + "time" + + "github.com/deepmap/oapi-codegen/pkg/runtime" + openapi_types "github.com/deepmap/oapi-codegen/pkg/types" + externalRef0 "github.com/snyk/code-client-go/internal/workspace/2024-03-12/common" +) + +// Defines values for CliTestFlowName. +const ( + CliTest CliTestFlowName = "cli_test" +) + +// Defines values for MonitorFlowName. +const ( + Monitor MonitorFlowName = "monitor" +) + +// Defines values for PostScanRequestDataType. +const ( + Workspace PostScanRequestDataType = "workspace" +) + +// Defines values for ScanJobType. +const ( + ScanJobTypeScanJob ScanJobType = "scan_job" +) + +// Defines values for ScanJobBasicAttributesStatus. +const ( + ScanJobBasicAttributesStatusDone ScanJobBasicAttributesStatus = "done" + ScanJobBasicAttributesStatusFailed ScanJobBasicAttributesStatus = "failed" + ScanJobBasicAttributesStatusInProgress ScanJobBasicAttributesStatus = "in_progress" + ScanJobBasicAttributesStatusQueued ScanJobBasicAttributesStatus = "queued" + ScanJobBasicAttributesStatusTimeout ScanJobBasicAttributesStatus = "timeout" + ScanJobBasicAttributesStatusUnknown ScanJobBasicAttributesStatus = "unknown" +) + +// Defines values for ScanJobResultsAttributesStatus. +const ( + ScanJobResultsAttributesStatusDone ScanJobResultsAttributesStatus = "done" + ScanJobResultsAttributesStatusFailed ScanJobResultsAttributesStatus = "failed" + ScanJobResultsAttributesStatusInProgress ScanJobResultsAttributesStatus = "in_progress" + ScanJobResultsAttributesStatusQueued ScanJobResultsAttributesStatus = "queued" + ScanJobResultsAttributesStatusTimeout ScanJobResultsAttributesStatus = "timeout" + ScanJobResultsAttributesStatusUnknown ScanJobResultsAttributesStatus = "unknown" +) + +// Defines values for ScanJobResultsType. +const ( + ScanJobResultsTypeScanJobResults ScanJobResultsType = "scan_job_results" +) + +// CliTestFlow defines model for CliTestFlow. +type CliTestFlow struct { + // Name The flow which the scan is triggered for. + Name CliTestFlowName `json:"name"` +} + +// CliTestFlowName The flow which the scan is triggered for. +type CliTestFlowName string + +// Component defines model for Component. +type Component struct { + // CreatedAt Point in time in which this component was created + CreatedAt time.Time `json:"created_at"` + + // FindingsUrl Optional URL containing the findings for this component + FindingsUrl *string `json:"findings_url,omitempty"` + + // Id ID of this component as provided by the scanner + Id string `json:"id"` + + // Name Human readable name of this component as provided by the scanner + Name string `json:"name"` + + // Type Identifies the type of this component as provided by the scanner among the ones supported by Snyk + Type string `json:"type"` +} + +// Flow defines model for Flow. +type Flow struct { + union json.RawMessage +} + +// LegacyFlowProperties defines model for LegacyFlowProperties. +type LegacyFlowProperties struct { + ImportId openapi_types.UUID `json:"import_id"` + ImportedTargetId openapi_types.UUID `json:"imported_target_id"` + TargetReference *string `json:"target_reference,omitempty"` + WorkspaceUrl string `json:"workspace_url"` +} + +// MonitorFlow defines model for MonitorFlow. +type MonitorFlow struct { + LegacyProperties *LegacyFlowProperties `json:"legacy_properties,omitempty"` + + // Name The flow which the scan is triggered for. + Name MonitorFlowName `json:"name"` +} + +// MonitorFlowName The flow which the scan is triggered for. +type MonitorFlowName string + +// PostScanRequest defines model for PostScanRequest. +type PostScanRequest struct { + Data struct { + Attributes struct { + Flow Flow `json:"flow"` + + // WorkspaceUrl The URI of the workspace to be scanned as returned by the workspace service. + WorkspaceUrl string `json:"workspace_url"` + } `json:"attributes"` + Id *openapi_types.UUID `json:"id,omitempty"` + Type PostScanRequestDataType `json:"type"` + } `json:"data"` +} + +// PostScanRequestDataType defines model for PostScanRequest.Data.Type. +type PostScanRequestDataType string + +// ScanJob defines model for ScanJob. +type ScanJob struct { + Attributes ScanJobBasicAttributes `json:"attributes"` + Id openapi_types.UUID `json:"id"` + Type ScanJobType `json:"type"` +} + +// ScanJobType defines model for ScanJob.Type. +type ScanJobType string + +// ScanJobBasicAttributes defines model for ScanJobBasicAttributes. +type ScanJobBasicAttributes struct { + // CreatedAt Point in time in which this job was created + CreatedAt time.Time `json:"created_at"` + + // Status Defines the completion status of this job. The job is considered finished when: - the status is `done` meaning it successfully completed, although some product lines might have reported errors, or timed out - the status is `failed` meaning it prematurely failed to complete and no product line got a chance to report - the status is `timeout` when the overall job did not manage to complete on time The job is considered in progress when: - the status is either `queued` meaning it hasn't been picked up yet by the orchestrator - the status is `in_progress` meaning it has been picked up by the orchestrator but product lines are still scanning + Status ScanJobBasicAttributesStatus `json:"status"` +} + +// ScanJobBasicAttributesStatus Defines the completion status of this job. The job is considered finished when: - the status is `done` meaning it successfully completed, although some product lines might have reported errors, or timed out - the status is `failed` meaning it prematurely failed to complete and no product line got a chance to report - the status is `timeout` when the overall job did not manage to complete on time The job is considered in progress when: - the status is either `queued` meaning it hasn't been picked up yet by the orchestrator - the status is `in_progress` meaning it has been picked up by the orchestrator but product lines are still scanning +type ScanJobBasicAttributesStatus string + +// ScanJobResults defines model for ScanJobResults. +type ScanJobResults struct { + Attributes struct { + Components []Component `json:"components"` + + // CreatedAt Point in time in which this job was created + CreatedAt time.Time `json:"created_at"` + + // Status Defines the completion status of this job. The job is considered finished when: - the status is `done` meaning it successfully completed, although some product lines might have reported errors, or timed out - the status is `failed` meaning it prematurely failed to complete and no product line got a chance to report - the status is `timeout` when the overall job did not manage to complete on time The job is considered in progress when: - the status is either `queued` meaning it hasn't been picked up yet by the orchestrator - the status is `in_progress` meaning it has been picked up by the orchestrator but product lines are still scanning + Status ScanJobResultsAttributesStatus `json:"status"` + } `json:"attributes"` + Id openapi_types.UUID `json:"id"` + Type ScanJobResultsType `json:"type"` +} + +// ScanJobResultsAttributesStatus Defines the completion status of this job. The job is considered finished when: - the status is `done` meaning it successfully completed, although some product lines might have reported errors, or timed out - the status is `failed` meaning it prematurely failed to complete and no product line got a chance to report - the status is `timeout` when the overall job did not manage to complete on time The job is considered in progress when: - the status is either `queued` meaning it hasn't been picked up yet by the orchestrator - the status is `in_progress` meaning it has been picked up by the orchestrator but product lines are still scanning +type ScanJobResultsAttributesStatus string + +// ScanJobResultsType defines model for ScanJobResults.Type. +type ScanJobResultsType string + +// ScanResponse defines model for ScanResponse. +type ScanResponse struct { + Data ScanJob `json:"data"` + Jsonapi *externalRef0.JsonApi `json:"jsonapi,omitempty"` + Links *externalRef0.SelfLink `json:"links,omitempty"` +} + +// ScanResultsResponse defines model for ScanResultsResponse. +type ScanResultsResponse struct { + Data ScanJobResults `json:"data"` + Jsonapi *externalRef0.JsonApi `json:"jsonapi,omitempty"` + Links *externalRef0.SelfLink `json:"links,omitempty"` +} + +// AsMonitorFlow returns the union data inside the Flow as a MonitorFlow +func (t Flow) AsMonitorFlow() (MonitorFlow, error) { + var body MonitorFlow + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromMonitorFlow overwrites any union data inside the Flow as the provided MonitorFlow +func (t *Flow) FromMonitorFlow(v MonitorFlow) error { + v.Name = "MonitorFlow" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeMonitorFlow performs a merge with any union data inside the Flow, using the provided MonitorFlow +func (t *Flow) MergeMonitorFlow(v MonitorFlow) error { + v.Name = "MonitorFlow" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +// AsCliTestFlow returns the union data inside the Flow as a CliTestFlow +func (t Flow) AsCliTestFlow() (CliTestFlow, error) { + var body CliTestFlow + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCliTestFlow overwrites any union data inside the Flow as the provided CliTestFlow +func (t *Flow) FromCliTestFlow(v CliTestFlow) error { + v.Name = "CliTestFlow" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCliTestFlow performs a merge with any union data inside the Flow, using the provided CliTestFlow +func (t *Flow) MergeCliTestFlow(v CliTestFlow) error { + v.Name = "CliTestFlow" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +func (t Flow) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"name"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t Flow) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "CliTestFlow": + return t.AsCliTestFlow() + case "MonitorFlow": + return t.AsMonitorFlow() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t Flow) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *Flow) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} diff --git a/internal/orchestration/2024-02-16/spec.config.yaml b/internal/orchestration/2024-02-16/spec.config.yaml new file mode 100644 index 00000000..f54ca916 --- /dev/null +++ b/internal/orchestration/2024-02-16/spec.config.yaml @@ -0,0 +1,12 @@ +package: v20240216 +generate: + client: true + models: true +output-options: + skip-prune: true +import-mapping: + ./common/common.yaml: github.com/snyk/code-client-go/internal/orchestration/2024-02-16/common + ./parameters/orgs.yaml: github.com/snyk/code-client-go/internal/orchestration/2024-02-16/parameters + ./parameters/scans.yaml: github.com/snyk/code-client-go/internal/orchestration/2024-02-16/parameters + ./scans/scans.yaml: github.com/snyk/code-client-go/internal/orchestration/2024-02-16/scans +output: client.go \ No newline at end of file diff --git a/internal/workspace/2024-03-12/client.go b/internal/workspace/2024-03-12/client.go index 0d13676a..c49fc592 100644 --- a/internal/workspace/2024-03-12/client.go +++ b/internal/workspace/2024-03-12/client.go @@ -178,16 +178,19 @@ func NewCreateWorkspaceRequestWithBody(server string, orgId externalRef2.OrgId, if err != nil { return nil, err } - + fmt.Println(serverURL) operationPath := fmt.Sprintf("/orgs/%s/workspaces", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } + fmt.Println(operationPath) queryURL, err := serverURL.Parse(operationPath) if err != nil { return nil, err } + fmt.Println("--->") + fmt.Println(queryURL) if params != nil { queryValues := queryURL.Query() diff --git a/internal/workspace/2024-03-12/client_test.go b/internal/workspace/2024-03-12/client_test.go index 8f5b18b7..974324aa 100644 --- a/internal/workspace/2024-03-12/client_test.go +++ b/internal/workspace/2024-03-12/client_test.go @@ -1,8 +1,10 @@ package v20240312_test import ( + "bytes" "context" "errors" + "io" "net/http" "testing" @@ -30,17 +32,91 @@ func (m *HTTPRequestDoerMock) Do(req *http.Request) (*http.Response, error) { func TestWorkspace_CreateWorkspaceWithApplicationVndAPIPlusJSONBody_Success(t *testing.T) { doer := &HTTPRequestDoerMock{} - doer.On("Do", mock.Anything).Return(nil, nil).Run(func(args mock.Arguments) { + mockResponse := http.Response{ + Body: io.NopCloser(bytes.NewBufferString(`{ + "data": { + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "type": "cli" + }, + "jsonapi": { + "version": "1.0" + } +}`)), + Header: http.Header{ + "Content-Type": []string{"application/json"}, + }, + StatusCode: http.StatusCreated, + } + doer.On("Do", mock.Anything).Return(&mockResponse, nil).Run(func(args mock.Arguments) { + req, ok := args.Get(0).(*http.Request) + assert.True(t, ok) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/workspaces?version=2024-03-12~experimental", req.URL.String()) + }) + client, err := workspaceClient.NewClientWithResponses("https://api.snyk.io/rest", workspaceClient.WithHTTPClient(doer)) + require.NoError(t, err) + + orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") + requestId := uuid.New() + response, err := client.CreateWorkspaceWithApplicationVndAPIPlusJSONBodyWithResponse(context.Background(), orgUUID, &workspaceClient.CreateWorkspaceParams{ + Version: "2024-03-12~experimental", + SnykRequestId: requestId, + }, workspaceClient.CreateWorkspaceApplicationVndAPIPlusJSONRequestBody{ + Data: struct { + Attributes struct { + BundleId string `json:"bundle_id"` + RepositoryUri string `json:"repository_uri"` + WorkspaceType externalRef3.WorkspacePostRequestDataAttributesWorkspaceType `json:"workspace_type"` + } `json:"attributes"` + Type externalRef3.WorkspacePostRequestDataType `json:"type"` + }(struct { + Attributes struct { + BundleId string `json:"bundle_id"` + RepositoryUri string `json:"repository_uri"` + WorkspaceType externalRef3.WorkspacePostRequestDataAttributesWorkspaceType `json:"workspace_type"` + } + Type externalRef3.WorkspacePostRequestDataType + }{Attributes: struct { + BundleId string `json:"bundle_id"` + RepositoryUri string `json:"repository_uri"` + WorkspaceType externalRef3.WorkspacePostRequestDataAttributesWorkspaceType `json:"workspace_type"` + }(struct { + BundleId string + RepositoryUri string + WorkspaceType externalRef3.WorkspacePostRequestDataAttributesWorkspaceType + }{BundleId: "bundleId", RepositoryUri: "repositoryUri", WorkspaceType: "workspaceUri"}), Type: "workspace"}), + }) + require.NoError(t, err) + require.NotNil(t, response) + require.Equal(t, 201, response.StatusCode()) + require.Equal(t, "3fa85f64-5717-4562-b3fc-2c963f66afa6", response.ApplicationvndApiJSON201.Data.Id.String()) + doer.AssertExpectations(t) +} + +func TestWorkspace_CreateWorkspaceWithApplicationVndAPIPlusJSONBody_Invalid(t *testing.T) { + doer := &HTTPRequestDoerMock{} + mockResponse := http.Response{ + Body: io.NopCloser(bytes.NewBufferString(`{ + "errors": [], + "jsonapi": { + "version": "1.0" + } +}`)), + Header: http.Header{ + "Content-Type": []string{"application/json"}, + }, + StatusCode: http.StatusBadRequest, + } + doer.On("Do", mock.Anything).Return(&mockResponse, nil).Run(func(args mock.Arguments) { req, ok := args.Get(0).(*http.Request) assert.True(t, ok) - assert.Equal(t, "/https//api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/workspaces?version=2024-03-12~experimental", req.URL.String()) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/workspaces?version=2024-03-12~experimental", req.URL.String()) }) - client, err := workspaceClient.NewClientWithResponses("https//api.snyk.io/rest", workspaceClient.WithHTTPClient(doer)) + client, err := workspaceClient.NewClientWithResponses("https://api.snyk.io/rest", workspaceClient.WithHTTPClient(doer)) require.NoError(t, err) orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") requestId := uuid.New() - _, err = client.CreateWorkspaceWithApplicationVndAPIPlusJSONBody(context.Background(), orgUUID, &workspaceClient.CreateWorkspaceParams{ + response, err := client.CreateWorkspaceWithApplicationVndAPIPlusJSONBodyWithResponse(context.Background(), orgUUID, &workspaceClient.CreateWorkspaceParams{ Version: "2024-03-12~experimental", SnykRequestId: requestId, }, workspaceClient.CreateWorkspaceApplicationVndAPIPlusJSONRequestBody{ @@ -69,6 +145,9 @@ func TestWorkspace_CreateWorkspaceWithApplicationVndAPIPlusJSONBody_Success(t *t }{BundleId: "bundleId", RepositoryUri: "repositoryUri", WorkspaceType: "workspaceUri"}), Type: "workspace"}), }) require.NoError(t, err) + require.NotNil(t, response) + require.Equal(t, http.StatusBadRequest, response.StatusCode()) + require.NotNil(t, response.ApplicationvndApiJSON400.Errors) doer.AssertExpectations(t) } @@ -77,14 +156,14 @@ func TestWorkspace_CreateWorkspaceWithApplicationVndAPIPlusJSONBody_Failure(t *t doer.On("Do", mock.Anything).Return(nil, errors.New("something went wrong")).Run(func(args mock.Arguments) { req, ok := args.Get(0).(*http.Request) assert.True(t, ok) - assert.Equal(t, "/https//api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/workspaces?version=2024-03-12~experimental", req.URL.String()) + assert.Equal(t, "https://api.snyk.io/rest/orgs/e7ea34c9-de0f-422c-bf2c-4654c2e2da90/workspaces?version=2024-03-12~experimental", req.URL.String()) }) - client, err := workspaceClient.NewClientWithResponses("https//api.snyk.io/rest", workspaceClient.WithHTTPClient(doer)) + client, err := workspaceClient.NewClientWithResponses("https://api.snyk.io/rest", workspaceClient.WithHTTPClient(doer)) require.NoError(t, err) orgUUID := uuid.MustParse("e7ea34c9-de0f-422c-bf2c-4654c2e2da90") requestId := uuid.New() - _, err = client.CreateWorkspaceWithApplicationVndAPIPlusJSONBody(context.Background(), orgUUID, &workspaceClient.CreateWorkspaceParams{ + _, err = client.CreateWorkspaceWithApplicationVndAPIPlusJSONBodyWithResponse(context.Background(), orgUUID, &workspaceClient.CreateWorkspaceParams{ Version: "2024-03-12~experimental", SnykRequestId: requestId, }, workspaceClient.CreateWorkspaceApplicationVndAPIPlusJSONRequestBody{ diff --git a/scripts/download-orchestration-api.sh b/scripts/download-orchestration-api.sh new file mode 100755 index 00000000..d232f989 --- /dev/null +++ b/scripts/download-orchestration-api.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash + +if [ -z "${GITHUB_PAT}" ]; then + echo "Could not run the script. The GITHUB_PAT environment variable must be set to a valid Personal Access Token." + exit 1 +fi + +ORCHESTRATION_API_VERSION="2024-02-16" +ORCHESTRATION_COMMIT_SHA="c6a338190fa7260f8154d386589c5e42ea9c7479" + +mkdir -p ./internal/orchestration/${ORCHESTRATION_API_VERSION} + +# Download the Common spec +set -e +curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml +set +e +yq -i e '{"components": .}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml +sed -i '' "s@#/schemas/@#/components/schemas/@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml +sed -i '' "s@#/headers/@#/components/headers/@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml + +## Download the Links model spec for the orchestration API +#set -e +#curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/api/hidden/models/links.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/links/links.yaml +#set +e +#yq -i e '{"components": .}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/links/links.yaml +#sed -i '' "s@#/schemas@#/components/schemas@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/links/links.yaml + +# Download the Org parameter spec for the orchestration API +set -e +curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/orgs.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/orgs.yaml +set +e +yq -i e '{"components": {"parameters": .}}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/orgs.yaml + +# Download the Scan parameter spec for the orchestration API +set -e +curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/scans.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/scans.yaml +set +e +yq -i e '{"components": {"parameters": .}}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/scans.yaml + +## Download the Content Type parameter spec for the orchestration API +#set -e +#curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/content-type.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/content-type.yaml +#set +e +#yq -i e '{"components": {"parameters": .}}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/content-type.yaml +# +# Download the scans model spec for the orchestration API +set -e +curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/models/scans.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml +set +e +yq -i e '{"components": .}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml +sed -i '' "s@https://raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml#@../common/common.yaml#/components@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml +sed -i '' "s@'#/schemas/@'#/components/schemas/@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml +#sed -i '' "s@../../../../models/links.yaml#@../links/links.yaml#/components@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/orchestrations/orchestrations.yaml + +# Download the orchestration API spec +set -e +curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/resources/scans/${ORCHESTRATION_API_VERSION}/spec.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml +set +e +sed -i '' "s@../../../models/scans.yaml#/schemas@./scans/scans.yaml#/components/schemas@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml +sed -i '' "s@#/components/x-snyk-common@./common/common.yaml#/components@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml +sed -i '' "s@../../../parameters/orgs.yaml#@./parameters/orgs.yaml#/components/parameters@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml +sed -i '' "s@../../../parameters/scans.yaml#@./parameters/scans.yaml#/components/parameters@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml +#sed -i '' "s@../../../parameters/content-type.yaml#@./parameters/content-type.yaml#/components/parameters@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml \ No newline at end of file From c572f7117592b37ab257274a219c3166270b954a Mon Sep 17 00:00:00 2001 From: Teodora Sandu Date: Wed, 3 Apr 2024 11:11:58 +0100 Subject: [PATCH 2/3] refactor: use python script --- .gitignore | 1 + Makefile | 9 ++-- scripts/download-orchestration-api.py | 39 +++++++++++++++++ scripts/download-orchestration-api.sh | 63 --------------------------- scripts/download-workspace-api.py | 54 +++++++++++++++++++++++ scripts/utils.py | 43 ++++++++++++++++++ 6 files changed, 143 insertions(+), 66 deletions(-) create mode 100644 scripts/download-orchestration-api.py delete mode 100755 scripts/download-orchestration-api.sh create mode 100644 scripts/download-workspace-api.py create mode 100644 scripts/utils.py diff --git a/.gitignore b/.gitignore index 58513598..108c4303 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,7 @@ webidentity.json ################################# # Development files # ################################# +scripts/__pycache__/ internal/workspace/**/**/*.yaml !internal/workspace/**/**/*.config.yaml internal/orchestration/**/**/*.yaml diff --git a/Makefile b/Makefile index 72acd895..9597b80b 100644 --- a/Makefile +++ b/Makefile @@ -61,12 +61,15 @@ generate: $(TOOLS_BIN)/go/mockgen $(TOOLS_BIN)/go/oapi-codegen @go generate ./... .PHONY: download-apis -download-apis: download-workspace-api +download-apis: download-workspace-api download-orchestration-api .PHONY: download-workspace-api download-workspace-api: - ./scripts/download-workspace-api.sh - ./scripts/download-orchestration-api.sh + python3 ./scripts/download-workspace-api.py + +.PHONY: download-orchestration-api +download-orchestration-api: + python3 ./scripts/download-orchestration-api.py .PHONY: help help: diff --git a/scripts/download-orchestration-api.py b/scripts/download-orchestration-api.py new file mode 100644 index 00000000..6831418e --- /dev/null +++ b/scripts/download-orchestration-api.py @@ -0,0 +1,39 @@ +from utils import mkDir +from utils import saveGitHubFile +from utils import formatSpecWithComponents +from utils import formatSpecWithParameters +from utils import replaceInFile + +ORCHESTRATION_API_VERSION = "2024-02-16" +ORCHESTRATION_COMMIT_SHA = "c6a338190fa7260f8154d386589c5e42ea9c7479" + +mkDir(f"./internal/orchestration/{ORCHESTRATION_API_VERSION}") + +# Download the Common spec +saveGitHubFile("sweater-comb/common-model-v1/components/common.yaml", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/common/common.yaml") +formatSpecWithComponents(f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/common/common.yaml") +replaceInFile("#/schemas/", "#/components/schemas/", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/common/common.yaml") +replaceInFile("#/headers/", "#/components/headers/", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/common/common.yaml") + +# Download the Org parameter spec for the orchestration API +saveGitHubFile(f"orchestration-service/{ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/orgs.yaml", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/parameters/orgs.yaml") +formatSpecWithParameters(f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/parameters/orgs.yaml") +formatSpecWithComponents(f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/parameters/orgs.yaml") + +# Download the Scan parameter spec for the orchestration API +saveGitHubFile(f"orchestration-service/{ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/scans.yaml", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/parameters/scans.yaml") +formatSpecWithParameters(f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/parameters/scans.yaml") +formatSpecWithComponents(f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/parameters/scans.yaml") + +# Download the scans model spec for the orchestration API +saveGitHubFile(f"orchestration-service/{ORCHESTRATION_COMMIT_SHA}/src/rest/models/scans.yaml", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/scans/scans.yaml") +formatSpecWithComponents(f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/scans/scans.yaml") +replaceInFile("https://raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml#", "../common/common.yaml#/components", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/scans/scans.yaml") +replaceInFile("'#/schemas/", "'#/components/schemas/", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/scans/scans.yaml") + +# Download the orchestration API spec +saveGitHubFile(f"orchestration-service/{ORCHESTRATION_COMMIT_SHA}/src/rest/resources/scans/{ORCHESTRATION_API_VERSION}/spec.yaml", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/spec.yaml") +replaceInFile("../../../models/scans.yaml#/schemas", "./scans/scans.yaml#/components/schemas", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/spec.yaml") +replaceInFile("#/components/x-snyk-common", "./common/common.yaml#/components", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/spec.yaml") +replaceInFile("../../../parameters/orgs.yaml#", "./parameters/orgs.yaml#/components/parameters", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/spec.yaml") +replaceInFile("../../../parameters/scans.yaml#", "./parameters/scans.yaml#/components/parameters", f"./internal/orchestration/{ORCHESTRATION_API_VERSION}/spec.yaml") diff --git a/scripts/download-orchestration-api.sh b/scripts/download-orchestration-api.sh deleted file mode 100755 index d232f989..00000000 --- a/scripts/download-orchestration-api.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash - -if [ -z "${GITHUB_PAT}" ]; then - echo "Could not run the script. The GITHUB_PAT environment variable must be set to a valid Personal Access Token." - exit 1 -fi - -ORCHESTRATION_API_VERSION="2024-02-16" -ORCHESTRATION_COMMIT_SHA="c6a338190fa7260f8154d386589c5e42ea9c7479" - -mkdir -p ./internal/orchestration/${ORCHESTRATION_API_VERSION} - -# Download the Common spec -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml -set +e -yq -i e '{"components": .}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml -sed -i '' "s@#/schemas/@#/components/schemas/@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml -sed -i '' "s@#/headers/@#/components/headers/@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/common/common.yaml - -## Download the Links model spec for the orchestration API -#set -e -#curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/api/hidden/models/links.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/links/links.yaml -#set +e -#yq -i e '{"components": .}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/links/links.yaml -#sed -i '' "s@#/schemas@#/components/schemas@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/links/links.yaml - -# Download the Org parameter spec for the orchestration API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/orgs.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/orgs.yaml -set +e -yq -i e '{"components": {"parameters": .}}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/orgs.yaml - -# Download the Scan parameter spec for the orchestration API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/scans.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/scans.yaml -set +e -yq -i e '{"components": {"parameters": .}}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/scans.yaml - -## Download the Content Type parameter spec for the orchestration API -#set -e -#curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/parameters/content-type.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/content-type.yaml -#set +e -#yq -i e '{"components": {"parameters": .}}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/parameters/content-type.yaml -# -# Download the scans model spec for the orchestration API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/models/scans.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml -set +e -yq -i e '{"components": .}' ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml -sed -i '' "s@https://raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml#@../common/common.yaml#/components@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml -sed -i '' "s@'#/schemas/@'#/components/schemas/@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/scans/scans.yaml -#sed -i '' "s@../../../../models/links.yaml#@../links/links.yaml#/components@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/orchestrations/orchestrations.yaml - -# Download the orchestration API spec -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/orchestration-service/${ORCHESTRATION_COMMIT_SHA}/src/rest/resources/scans/${ORCHESTRATION_API_VERSION}/spec.yaml > ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml -set +e -sed -i '' "s@../../../models/scans.yaml#/schemas@./scans/scans.yaml#/components/schemas@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml -sed -i '' "s@#/components/x-snyk-common@./common/common.yaml#/components@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml -sed -i '' "s@../../../parameters/orgs.yaml#@./parameters/orgs.yaml#/components/parameters@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml -sed -i '' "s@../../../parameters/scans.yaml#@./parameters/scans.yaml#/components/parameters@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml -#sed -i '' "s@../../../parameters/content-type.yaml#@./parameters/content-type.yaml#/components/parameters@g" ./internal/orchestration/${ORCHESTRATION_API_VERSION}/spec.yaml \ No newline at end of file diff --git a/scripts/download-workspace-api.py b/scripts/download-workspace-api.py new file mode 100644 index 00000000..85021dbf --- /dev/null +++ b/scripts/download-workspace-api.py @@ -0,0 +1,54 @@ +from utils import mkDir +from utils import saveGitHubFile +from utils import formatSpecWithComponents +from utils import formatSpecWithParameters +from utils import replaceInFile + +WORKSPACE_API_VERSION = "2024-03-12" +WORKSPACE_COMMIT_SHA = "cfd737cd917ab2c63840bd112d9eb2c9a9c101f6" + +mkDir(f"./internal/workspace/{WORKSPACE_API_VERSION}") + +# Download the Common spec +saveGitHubFile("sweater-comb/common-model-v1/components/common.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/common/common.yaml") +formatSpecWithComponents(f"./internal/workspace/{WORKSPACE_API_VERSION}/common/common.yaml") +replaceInFile("#/schemas/", "#/components/schemas/", f"./internal/workspace/{WORKSPACE_API_VERSION}/common/common.yaml") +replaceInFile("#/headers/", "#/components/headers/", f"./internal/workspace/{WORKSPACE_API_VERSION}/common/common.yaml") + +# Download the Links model spec for the Workspace API +saveGitHubFile(f"workspace-service/{WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/models/links.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/links/links.yaml") +formatSpecWithComponents(f"./internal/workspace/{WORKSPACE_API_VERSION}/links/links.yaml") +replaceInFile("#/schemas", "#/components/schemas", f"./internal/workspace/{WORKSPACE_API_VERSION}/links/links.yaml") + +# Download the Org parameter spec for the orchestration API +saveGitHubFile(f"orchestration-service/{WORKSPACE_COMMIT_SHA}/src/rest/parameters/orgs.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/orgs.yaml") +formatSpecWithParameters(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/orgs.yaml") +formatSpecWithComponents(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/orgs.yaml") + +# Download the Request ID parameter spec for the Workspace API +saveGitHubFile(f"workspace-service/{WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/parameters/request-id.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/request-id.yaml") +formatSpecWithParameters(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/request-id.yaml") +formatSpecWithComponents(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/request-id.yaml") + +# Download the User Agent parameter spec for the Workspace API +saveGitHubFile(f"workspace-service/{WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/parameters/user-agent.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/user-agent.yaml") +formatSpecWithParameters(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/user-agent.yaml") +formatSpecWithComponents(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/user-agent.yaml") + +# Download the Content Type parameter spec for the Workspace API +saveGitHubFile(f"workspace-service/{WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/parameters/content-type.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/content-type.yaml") +formatSpecWithParameters(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/content-type.yaml") +formatSpecWithComponents(f"./internal/workspace/{WORKSPACE_API_VERSION}/parameters/content-type.yaml") + +# Download the Workspace model spec for the Workspace API +saveGitHubFile(f"workspace-service/{WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/resources/workspaces/{WORKSPACE_API_VERSION}/models/workspaces.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/workspaces/workspaces.yaml") +formatSpecWithComponents(f"./internal/workspace/{WORKSPACE_API_VERSION}/workspaces/workspaces.yaml") +replaceInFile("https://raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml#", "../common/common.yaml#/components@g", f"./internal/workspace/{WORKSPACE_API_VERSION}/workspaces/workspaces.yaml") +replaceInFile("../../../../models/links.yaml#", "../links/links.yaml#/components", f"./internal/workspace/{WORKSPACE_API_VERSION}/workspaces/workspaces.yaml") + +# Download the orchestration API spec +saveGitHubFile(f"workspace-service/{WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/resources/workspaces/{WORKSPACE_API_VERSION}/spec.yaml", f"./internal/workspace/{WORKSPACE_API_VERSION}/spec.yaml") +replaceInFile("../../../models/scans.yaml#/schemas", "./scans/scans.yaml#/components/schemas", f"./internal/workspace/{WORKSPACE_API_VERSION}/spec.yaml") +replaceInFile("#/components/x-snyk-common", "./common/common.yaml#/components", f"./internal/workspace/{WORKSPACE_API_VERSION}/spec.yaml") +replaceInFile("../../../parameters/orgs.yaml#", "./parameters/orgs.yaml#/components/parameters", f"./internal/workspace/{WORKSPACE_API_VERSION}/spec.yaml") +replaceInFile("../../../parameters/scans.yaml#", "./parameters/scans.yaml#/components/parameters", f"./internal/workspace/{WORKSPACE_API_VERSION}/spec.yaml") diff --git a/scripts/utils.py b/scripts/utils.py new file mode 100644 index 00000000..e6a76d5f --- /dev/null +++ b/scripts/utils.py @@ -0,0 +1,43 @@ +import requests +import os +import json +import yaml + +def mkDir(directory): + if not os.path.exists(directory): + os.makedirs(directory) + +def replaceInFile(search_text, replace_text, file): + with open(file, 'r') as f: + data = f.read() + data = data.replace(search_text, replace_text) + + with open(file, 'w') as f: + f.write(data) + +def saveGitHubFile(gitHubFile, localFile): + if "GITHUB_PAT" not in os.environ: + print >> sys.stderr, "Could not run the script. The GITHUB_PAT environment variable must be set to a valid Personal Access Token." + sys.exit(1) + + gitHubPat = os.environ["GITHUB_PAT"] + response = requests.get(f"https://{gitHubPat}@raw.githubusercontent.com/snyk/{gitHubFile}", headers={'Accept': 'application/json'}) + + with open(localFile, "w") as f: + f.write(response.text) + +def formatSpecWithComponents(file): + with open(file, 'r') as f: + obj = yaml.safe_load(f) + + with open(file, 'w') as f: + nestedObj = {'components': obj} + yaml.dump(nestedObj, f, sort_keys=False) + +def formatSpecWithParameters(file): + with open(file, 'r') as f: + obj = yaml.safe_load(f) + + with open(file, 'w') as f: + nestedObj = {'parameters': obj} + yaml.dump(nestedObj, f, sort_keys=False) From c59cc01286b4aa1d7b1cd1a70d86aacb955b115d Mon Sep 17 00:00:00 2001 From: Teodora Sandu Date: Wed, 3 Apr 2024 12:50:30 +0100 Subject: [PATCH 3/3] refactor: minor improvements --- CONTRIBUTING.md | 2 + Makefile | 4 +- scripts/download-orchestration-api.py | 2 + scripts/download-workspace-api.py | 2 + scripts/download-workspace-api.sh | 69 --------------------------- 5 files changed, 8 insertions(+), 71 deletions(-) mode change 100644 => 100755 scripts/download-orchestration-api.py mode change 100644 => 100755 scripts/download-workspace-api.py delete mode 100755 scripts/download-workspace-api.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7838accf..7270f1dd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,6 +43,8 @@ In order to update the clients you need access to some private Snyk repositories export GITHUB_PAT= ``` +Also make sure to have `python3` installed. + Then run `make download-apis` to download the latest code. If you want to download a new version, you can also do that. Then generate the client by running `make generate`. diff --git a/Makefile b/Makefile index 9597b80b..dac4c18c 100644 --- a/Makefile +++ b/Makefile @@ -65,11 +65,11 @@ download-apis: download-workspace-api download-orchestration-api .PHONY: download-workspace-api download-workspace-api: - python3 ./scripts/download-workspace-api.py + ./scripts/download-workspace-api.py .PHONY: download-orchestration-api download-orchestration-api: - python3 ./scripts/download-orchestration-api.py + ./scripts/download-orchestration-api.py .PHONY: help help: diff --git a/scripts/download-orchestration-api.py b/scripts/download-orchestration-api.py old mode 100644 new mode 100755 index 6831418e..94fec16d --- a/scripts/download-orchestration-api.py +++ b/scripts/download-orchestration-api.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + from utils import mkDir from utils import saveGitHubFile from utils import formatSpecWithComponents diff --git a/scripts/download-workspace-api.py b/scripts/download-workspace-api.py old mode 100644 new mode 100755 index 85021dbf..5b02a4fb --- a/scripts/download-workspace-api.py +++ b/scripts/download-workspace-api.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + from utils import mkDir from utils import saveGitHubFile from utils import formatSpecWithComponents diff --git a/scripts/download-workspace-api.sh b/scripts/download-workspace-api.sh deleted file mode 100755 index bb3af04f..00000000 --- a/scripts/download-workspace-api.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env bash - -if [ -z "${GITHUB_PAT}" ]; then - echo "Could not run the script. The GITHUB_PAT environment variable must be set to a valid Personal Access Token." - exit 1 -fi - -WORKSPACE_API_VERSION="2024-03-12" -WORKSPACE_COMMIT_SHA="cfd737cd917ab2c63840bd112d9eb2c9a9c101f6" - -mkdir -p ./internal/workspace/${WORKSPACE_API_VERSION} - -# Download the Common spec -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/common/common.yaml -set +e -yq -i e '{"components": .}' ./internal/workspace/${WORKSPACE_API_VERSION}/common/common.yaml -sed -i '' "s@#/schemas/@#/components/schemas/@g" ./internal/workspace/${WORKSPACE_API_VERSION}/common/common.yaml -sed -i '' "s@#/headers/@#/components/headers/@g" ./internal/workspace/${WORKSPACE_API_VERSION}/common/common.yaml - -# Download the Links model spec for the Workspace API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/workspace-service/${WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/models/links.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/links/links.yaml -set +e -yq -i e '{"components": .}' ./internal/workspace/${WORKSPACE_API_VERSION}/links/links.yaml -sed -i '' "s@#/schemas@#/components/schemas@g" ./internal/workspace/${WORKSPACE_API_VERSION}/links/links.yaml - -# Download the Org parameter spec for the Workspace API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/workspace-service/${WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/parameters/orgs.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/orgs.yaml -set +e -yq -i e '{"components": {"parameters": .}}' ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/orgs.yaml - -# Download the Request ID parameter spec for the Workspace API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/workspace-service/${WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/parameters/request-id.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/request-id.yaml -set +e -yq -i e '{"components": {"parameters": .}}' ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/request-id.yaml - -# Download the User Agent parameter spec for the Workspace API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/workspace-service/${WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/parameters/user-agent.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/user-agent.yaml -set +e -yq -i e '{"components": {"parameters": .}}' ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/user-agent.yaml - -# Download the Content Type parameter spec for the Workspace API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/workspace-service/${WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/parameters/content-type.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/content-type.yaml -set +e -yq -i e '{"components": {"parameters": .}}' ./internal/workspace/${WORKSPACE_API_VERSION}/parameters/content-type.yaml - -# Download the Workspace model spec for the Workspace API -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/workspace-service/${WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/resources/workspaces/${WORKSPACE_API_VERSION}/models/workspaces.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/workspaces/workspaces.yaml -set +e -yq -i e '{"components": .}' ./internal/workspace/${WORKSPACE_API_VERSION}/workspaces/workspaces.yaml -sed -i '' "s@https://raw.githubusercontent.com/snyk/sweater-comb/common-model-v1/components/common.yaml#@../common/common.yaml#/components@g" ./internal/workspace/${WORKSPACE_API_VERSION}/workspaces/workspaces.yaml -sed -i '' "s@../../../../models/links.yaml#@../links/links.yaml#/components@g" ./internal/workspace/${WORKSPACE_API_VERSION}/workspaces/workspaces.yaml - -# Download the Workspace API spec -set -e -curl -s https://${GITHUB_PAT}@raw.githubusercontent.com/snyk/workspace-service/${WORKSPACE_COMMIT_SHA}/src/rest/api/hidden/resources/workspaces/${WORKSPACE_API_VERSION}/spec.yaml > ./internal/workspace/${WORKSPACE_API_VERSION}/spec.yaml -set +e -sed -i '' "s@./models/workspaces.yaml#/schemas@./workspaces/workspaces.yaml#/components/schemas@g" ./internal/workspace/${WORKSPACE_API_VERSION}/spec.yaml -sed -i '' "s@#/components/x-snyk-common@./common/common.yaml#/components@g" ./internal/workspace/${WORKSPACE_API_VERSION}/spec.yaml -sed -i '' "s@../../../parameters/orgs.yaml#@./parameters/orgs.yaml#/components/parameters@g" ./internal/workspace/${WORKSPACE_API_VERSION}/spec.yaml -sed -i '' "s@../../../parameters/request-id.yaml#@./parameters/request-id.yaml#/components/parameters@g" ./internal/workspace/${WORKSPACE_API_VERSION}/spec.yaml -sed -i '' "s@../../../parameters/user-agent.yaml#@./parameters/user-agent.yaml#/components/parameters@g" ./internal/workspace/${WORKSPACE_API_VERSION}/spec.yaml -sed -i '' "s@../../../parameters/content-type.yaml#@./parameters/content-type.yaml#/components/parameters@g" ./internal/workspace/${WORKSPACE_API_VERSION}/spec.yaml \ No newline at end of file