diff --git a/apiserver/controllers/controllers.go b/apiserver/controllers/controllers.go index 70a56bd5..8e42f320 100644 --- a/apiserver/controllers/controllers.go +++ b/apiserver/controllers/controllers.go @@ -30,11 +30,16 @@ import ( "github.com/cloudbase/garm/runner" wsWriter "github.com/cloudbase/garm/websocket" + "github.com/gorilla/mux" "github.com/gorilla/websocket" "github.com/pkg/errors" ) func NewAPIController(r *runner.Runner, authenticator *auth.Authenticator, hub *wsWriter.Hub) (*APIController, error) { + controllerInfo, err := r.GetControllerInfo(auth.GetAdminContext()) + if err != nil { + return nil, errors.Wrap(err, "failed to get controller info") + } return &APIController{ r: r, auth: authenticator, @@ -43,18 +48,20 @@ func NewAPIController(r *runner.Runner, authenticator *auth.Authenticator, hub * ReadBufferSize: 1024, WriteBufferSize: 16384, }, + controllerID: controllerInfo.ControllerID.String(), }, nil } type APIController struct { - r *runner.Runner - auth *auth.Authenticator - hub *wsWriter.Hub - upgrader websocket.Upgrader + r *runner.Runner + auth *auth.Authenticator + hub *wsWriter.Hub + upgrader websocket.Upgrader + controllerID string } func handleError(w http.ResponseWriter, err error) { - w.Header().Add("Content-Type", "application/json") + w.Header().Set("Content-Type", "application/json") origErr := errors.Cause(err) apiErr := params.APIErrorResponse{ Details: origErr.Error(), @@ -138,7 +145,19 @@ func (a *APIController) handleWorkflowJobEvent(w http.ResponseWriter, r *http.Re labelValues = a.webhookMetricLabelValues("true", "") } -func (a *APIController) CatchAll(w http.ResponseWriter, r *http.Request) { +func (a *APIController) WebhookHandler(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + controllerID, ok := vars["controllerID"] + // If the webhook URL includes a controller ID, we validate that it's meant for us. We still + // support bare webhook URLs, which are tipically configured manually by the user. + // The controllerID suffixed webhook URL is useful when configuring the webhook for an entity + // via garm. We cannot tag a webhook URL on github, so there is no way to determine ownership. + // Using a controllerID suffix is a simple way to denote ownership. + if ok && controllerID != a.controllerID { + log.Printf("ignoring webhook meant for controller %s", util.SanitizeLogEntry(controllerID)) + return + } + headers := r.Header.Clone() event := runnerParams.Event(headers.Get("X-Github-Event")) @@ -195,8 +214,9 @@ func (a *APIController) NotFoundHandler(w http.ResponseWriter, r *http.Request) Details: "Resource not found", Error: "Not found", } - w.WriteHeader(http.StatusNotFound) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) if err := json.NewEncoder(w).Encode(apiErr); err != nil { log.Printf("failet to write response: %q", err) } diff --git a/apiserver/controllers/organizations.go b/apiserver/controllers/organizations.go index d03d1de4..02f93fc4 100644 --- a/apiserver/controllers/organizations.go +++ b/apiserver/controllers/organizations.go @@ -18,6 +18,7 @@ import ( "encoding/json" "log" "net/http" + "strconv" gErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/apiserver/params" @@ -43,21 +44,21 @@ import ( func (a *APIController) CreateOrgHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var repoData runnerParams.CreateOrgParams - if err := json.NewDecoder(r.Body).Decode(&repoData); err != nil { + var orgData runnerParams.CreateOrgParams + if err := json.NewDecoder(r.Body).Decode(&orgData); err != nil { handleError(w, gErrors.ErrBadRequest) return } - repo, err := a.r.CreateOrganization(ctx, repoData) + org, err := a.r.CreateOrganization(ctx, orgData) if err != nil { - log.Printf("error creating repository: %+v", err) + log.Printf("error creating organization: %+v", err) handleError(w, err) return } w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(repo); err != nil { + if err := json.NewEncoder(w).Encode(org); err != nil { log.Printf("failed to encode response: %q", err) } } @@ -139,6 +140,12 @@ func (a *APIController) GetOrgByIDHandler(w http.ResponseWriter, r *http.Request // in: path // required: true // +// + name: keepWebhook +// description: If true and a webhook is installed for this organization, it will not be removed. +// type: boolean +// in: query +// required: false +// // Responses: // default: APIErrorResponse func (a *APIController) DeleteOrgHandler(w http.ResponseWriter, r *http.Request) { @@ -157,7 +164,9 @@ func (a *APIController) DeleteOrgHandler(w http.ResponseWriter, r *http.Request) return } - if err := a.r.DeleteOrganization(ctx, orgID); err != nil { + keepWebhook, _ := strconv.ParseBool(r.URL.Query().Get("keepWebhook")) + + if err := a.r.DeleteOrganization(ctx, orgID, keepWebhook); err != nil { log.Printf("removing org: %+v", err) handleError(w, err) return @@ -344,9 +353,9 @@ func (a *APIController) ListOrgPoolsHandler(w http.ResponseWriter, r *http.Reque func (a *APIController) GetOrgPoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) - orgID, repoOk := vars["orgID"] + orgID, orgOk := vars["orgID"] poolID, poolOk := vars["poolID"] - if !repoOk || !poolOk { + if !orgOk || !poolOk { w.WriteHeader(http.StatusBadRequest) if err := json.NewEncoder(w).Encode(params.APIErrorResponse{ Error: "Bad Request", @@ -479,3 +488,142 @@ func (a *APIController) UpdateOrgPoolHandler(w http.ResponseWriter, r *http.Requ log.Printf("failed to encode response: %q", err) } } + +// swagger:route POST /organizations/{orgID}/webhook organizations hooks InstallOrgWebhook +// +// Install the GARM webhook for an organization. The secret configured on the organization will +// be used to validate the requests. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters used when creating the organization webhook. +// type: InstallWebhookParams +// in: body +// required: true +// +// Responses: +// 200: HookInfo +// default: APIErrorResponse +func (a *APIController) InstallOrgWebhookHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + orgID, orgOk := vars["orgID"] + if !orgOk { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(params.APIErrorResponse{ + Error: "Bad Request", + Details: "No org ID specified", + }); err != nil { + log.Printf("failed to encode response: %q", err) + } + return + } + + var hookParam runnerParams.InstallWebhookParams + if err := json.NewDecoder(r.Body).Decode(&hookParam); err != nil { + log.Printf("failed to decode: %s", err) + handleError(w, gErrors.ErrBadRequest) + return + } + + info, err := a.r.InstallOrgWebhook(ctx, orgID, hookParam) + if err != nil { + log.Printf("installing webhook: %s", err) + handleError(w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(info); err != nil { + log.Printf("failed to encode response: %q", err) + } +} + +// swagger:route DELETE /organizations/{orgID}/webhook organizations hooks UninstallOrgWebhook +// +// Uninstall organization webhook. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse +func (a *APIController) UninstallOrgWebhookHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + orgID, orgOk := vars["orgID"] + if !orgOk { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(params.APIErrorResponse{ + Error: "Bad Request", + Details: "No org ID specified", + }); err != nil { + log.Printf("failed to encode response: %q", err) + } + return + } + + if err := a.r.UninstallOrgWebhook(ctx, orgID); err != nil { + log.Printf("removing webhook: %s", err) + handleError(w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) +} + +// swagger:route GET /organizations/{orgID}/webhook organizations hooks GetOrgWebhookInfo +// +// Get information about the GARM installed webhook on an organization. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: HookInfo +// default: APIErrorResponse +func (a *APIController) GetOrgWebhookInfoHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + orgID, orgOk := vars["orgID"] + if !orgOk { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(params.APIErrorResponse{ + Error: "Bad Request", + Details: "No org ID specified", + }); err != nil { + log.Printf("failed to encode response: %q", err) + } + return + } + + info, err := a.r.GetOrgWebhookInfo(ctx, orgID) + if err != nil { + log.Printf("getting webhook info: %s", err) + handleError(w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(info); err != nil { + log.Printf("failed to encode response: %q", err) + } +} diff --git a/apiserver/controllers/repositories.go b/apiserver/controllers/repositories.go index 9aae826f..ae2a3040 100644 --- a/apiserver/controllers/repositories.go +++ b/apiserver/controllers/repositories.go @@ -18,6 +18,7 @@ import ( "encoding/json" "log" "net/http" + "strconv" gErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/apiserver/params" @@ -139,6 +140,12 @@ func (a *APIController) GetRepoByIDHandler(w http.ResponseWriter, r *http.Reques // in: path // required: true // +// + name: keepWebhook +// description: If true and a webhook is installed for this repo, it will not be removed. +// type: boolean +// in: query +// required: false +// // Responses: // default: APIErrorResponse func (a *APIController) DeleteRepoHandler(w http.ResponseWriter, r *http.Request) { @@ -157,7 +164,8 @@ func (a *APIController) DeleteRepoHandler(w http.ResponseWriter, r *http.Request return } - if err := a.r.DeleteRepository(ctx, repoID); err != nil { + keepWebhook, _ := strconv.ParseBool(r.URL.Query().Get("keepWebhook")) + if err := a.r.DeleteRepository(ctx, repoID, keepWebhook); err != nil { log.Printf("fetching repo: %s", err) handleError(w, err) return @@ -479,3 +487,142 @@ func (a *APIController) UpdateRepoPoolHandler(w http.ResponseWriter, r *http.Req log.Printf("failed to encode response: %q", err) } } + +// swagger:route POST /repositories/{repoID}/webhook repositories hooks InstallRepoWebhook +// +// Install the GARM webhook for an organization. The secret configured on the organization will +// be used to validate the requests. +// +// Parameters: +// + name: repoID +// description: Repository ID. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters used when creating the repository webhook. +// type: InstallWebhookParams +// in: body +// required: true +// +// Responses: +// 200: HookInfo +// default: APIErrorResponse +func (a *APIController) InstallRepoWebhookHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + repoID, orgOk := vars["repoID"] + if !orgOk { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(params.APIErrorResponse{ + Error: "Bad Request", + Details: "No repository ID specified", + }); err != nil { + log.Printf("failed to encode response: %q", err) + } + return + } + + var hookParam runnerParams.InstallWebhookParams + if err := json.NewDecoder(r.Body).Decode(&hookParam); err != nil { + log.Printf("failed to decode: %s", err) + handleError(w, gErrors.ErrBadRequest) + return + } + + info, err := a.r.InstallRepoWebhook(ctx, repoID, hookParam) + if err != nil { + log.Printf("installing webhook: %s", err) + handleError(w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(info); err != nil { + log.Printf("failed to encode response: %q", err) + } +} + +// swagger:route DELETE /repositories/{repoID}/webhook repositories hooks UninstallRepoWebhook +// +// Uninstall organization webhook. +// +// Parameters: +// + name: repoID +// description: Repository ID. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse +func (a *APIController) UninstallRepoWebhookHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + repoID, orgOk := vars["repoID"] + if !orgOk { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(params.APIErrorResponse{ + Error: "Bad Request", + Details: "No repository ID specified", + }); err != nil { + log.Printf("failed to encode response: %q", err) + } + return + } + + if err := a.r.UninstallRepoWebhook(ctx, repoID); err != nil { + log.Printf("removing webhook: %s", err) + handleError(w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) +} + +// swagger:route GET /repositories/{repoID}/webhook repositories hooks GetRepoWebhookInfo +// +// Get information about the GARM installed webhook on a repository. +// +// Parameters: +// + name: repoID +// description: Repository ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: HookInfo +// default: APIErrorResponse +func (a *APIController) GetRepoWebhookInfoHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + repoID, orgOk := vars["repoID"] + if !orgOk { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(params.APIErrorResponse{ + Error: "Bad Request", + Details: "No repository ID specified", + }); err != nil { + log.Printf("failed to encode response: %q", err) + } + return + } + + info, err := a.r.GetRepoWebhookInfo(ctx, repoID) + if err != nil { + log.Printf("getting webhook info: %s", err) + handleError(w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(info); err != nil { + log.Printf("failed to encode response: %q", err) + } +} diff --git a/apiserver/routers/routers.go b/apiserver/routers/routers.go index f14ffef4..161f9cee 100644 --- a/apiserver/routers/routers.go +++ b/apiserver/routers/routers.go @@ -82,15 +82,17 @@ func WithDebugServer(parentRouter *mux.Router) *mux.Router { return parentRouter } -func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddleware, initMiddleware, instanceMiddleware auth.Middleware) *mux.Router { +func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddleware, initMiddleware, instanceMiddleware auth.Middleware, manageWebhooks bool) *mux.Router { router := mux.NewRouter() logMiddleware := util.NewLoggingMiddleware(logWriter) router.Use(logMiddleware) // Handles github webhooks webhookRouter := router.PathPrefix("/webhooks").Subrouter() - webhookRouter.PathPrefix("/").Handler(http.HandlerFunc(han.CatchAll)) - webhookRouter.PathPrefix("").Handler(http.HandlerFunc(han.CatchAll)) + webhookRouter.Handle("/", http.HandlerFunc(han.WebhookHandler)) + webhookRouter.Handle("", http.HandlerFunc(han.WebhookHandler)) + webhookRouter.Handle("/{controllerID}/", http.HandlerFunc(han.WebhookHandler)) + webhookRouter.Handle("/{controllerID}", http.HandlerFunc(han.WebhookHandler)) // Handles API calls apiSubRouter := router.PathPrefix("/api/v1").Subrouter() @@ -118,6 +120,7 @@ func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddl apiRouter := apiSubRouter.PathPrefix("").Subrouter() apiRouter.Use(initMiddleware.Middleware) apiRouter.Use(authMiddleware.Middleware) + apiRouter.Use(auth.AdminRequiredMiddleware) // Metrics Token apiRouter.Handle("/metrics-token/", http.HandlerFunc(han.MetricsTokenHandler)).Methods("GET", "OPTIONS") @@ -201,6 +204,17 @@ func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddl apiRouter.Handle("/repositories/", http.HandlerFunc(han.CreateRepoHandler)).Methods("POST", "OPTIONS") apiRouter.Handle("/repositories", http.HandlerFunc(han.CreateRepoHandler)).Methods("POST", "OPTIONS") + if manageWebhooks { + // Install Webhook + apiRouter.Handle("/repositories/{repoID}/webhook/", http.HandlerFunc(han.InstallRepoWebhookHandler)).Methods("POST", "OPTIONS") + apiRouter.Handle("/repositories/{repoID}/webhook", http.HandlerFunc(han.InstallRepoWebhookHandler)).Methods("POST", "OPTIONS") + // Uninstall Webhook + apiRouter.Handle("/repositories/{repoID}/webhook/", http.HandlerFunc(han.UninstallRepoWebhookHandler)).Methods("DELETE", "OPTIONS") + apiRouter.Handle("/repositories/{repoID}/webhook", http.HandlerFunc(han.UninstallRepoWebhookHandler)).Methods("DELETE", "OPTIONS") + // Get webhook info + apiRouter.Handle("/repositories/{repoID}/webhook/", http.HandlerFunc(han.GetRepoWebhookInfoHandler)).Methods("GET", "OPTIONS") + apiRouter.Handle("/repositories/{repoID}/webhook", http.HandlerFunc(han.GetRepoWebhookInfoHandler)).Methods("GET", "OPTIONS") + } ///////////////////////////// // Organizations and pools // ///////////////////////////// @@ -240,6 +254,17 @@ func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddl apiRouter.Handle("/organizations/", http.HandlerFunc(han.CreateOrgHandler)).Methods("POST", "OPTIONS") apiRouter.Handle("/organizations", http.HandlerFunc(han.CreateOrgHandler)).Methods("POST", "OPTIONS") + if manageWebhooks { + // Install Webhook + apiRouter.Handle("/organizations/{orgID}/webhook/", http.HandlerFunc(han.InstallOrgWebhookHandler)).Methods("POST", "OPTIONS") + apiRouter.Handle("/organizations/{orgID}/webhook", http.HandlerFunc(han.InstallOrgWebhookHandler)).Methods("POST", "OPTIONS") + // Uninstall Webhook + apiRouter.Handle("/organizations/{orgID}/webhook/", http.HandlerFunc(han.UninstallOrgWebhookHandler)).Methods("DELETE", "OPTIONS") + apiRouter.Handle("/organizations/{orgID}/webhook", http.HandlerFunc(han.UninstallOrgWebhookHandler)).Methods("DELETE", "OPTIONS") + // Get webhook info + apiRouter.Handle("/organizations/{orgID}/webhook/", http.HandlerFunc(han.GetOrgWebhookInfoHandler)).Methods("GET", "OPTIONS") + apiRouter.Handle("/organizations/{orgID}/webhook", http.HandlerFunc(han.GetOrgWebhookInfoHandler)).Methods("GET", "OPTIONS") + } ///////////////////////////// // Enterprises and pools // ///////////////////////////// @@ -291,5 +316,8 @@ func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddl // Websocket log writer apiRouter.Handle("/{ws:ws\\/?}", http.HandlerFunc(han.WSHandler)).Methods("GET") + + // NotFound handler + apiRouter.PathPrefix("/").HandlerFunc(han.NotFoundHandler).Methods("GET", "POST", "PUT", "DELETE", "OPTIONS") return router } diff --git a/apiserver/swagger-models.yaml b/apiserver/swagger-models.yaml index a2ad3474..fa8181f7 100644 --- a/apiserver/swagger-models.yaml +++ b/apiserver/swagger-models.yaml @@ -8,6 +8,13 @@ definitions: import: package: github.com/cloudbase/garm/params alias: garm_params + HookInfo: + type: object + x-go-type: + type: HookInfo + import: + package: github.com/cloudbase/garm/params + alias: garm_params ControllerInfo: type: object x-go-type: @@ -15,6 +22,13 @@ definitions: import: package: github.com/cloudbase/garm/params alias: garm_params + InstallWebhookParams: + type: object + x-go-type: + type: InstallWebhookParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params NewUserParams: type: object x-go-type: diff --git a/apiserver/swagger.yaml b/apiserver/swagger.yaml index 5851740c..1d5f33b1 100644 --- a/apiserver/swagger.yaml +++ b/apiserver/swagger.yaml @@ -76,6 +76,20 @@ definitions: alias: garm_params package: github.com/cloudbase/garm/params type: GithubCredentials + HookInfo: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: HookInfo + InstallWebhookParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: InstallWebhookParams Instance: type: object x-go-type: @@ -688,6 +702,10 @@ paths: name: orgID required: true type: string + - description: If true and a webhook is installed for this organization, it will not be removed. + in: query + name: keepWebhook + type: boolean responses: default: description: APIErrorResponse @@ -900,6 +918,76 @@ paths: tags: - organizations - pools + /organizations/{orgID}/webhook: + delete: + operationId: UninstallOrgWebhook + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Uninstall organization webhook. + tags: + - organizations + - hooks + get: + operationId: GetOrgWebhookInfo + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + responses: + "200": + description: HookInfo + schema: + $ref: '#/definitions/HookInfo' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get information about the GARM installed webhook on an organization. + tags: + - organizations + - hooks + post: + description: |- + Install the GARM webhook for an organization. The secret configured on the organization will + be used to validate the requests. + operationId: InstallOrgWebhook + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + - description: Parameters used when creating the organization webhook. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/InstallWebhookParams' + description: Parameters used when creating the organization webhook. + type: object + responses: + "200": + description: HookInfo + schema: + $ref: '#/definitions/HookInfo' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + tags: + - organizations + - hooks /pools: get: operationId: ListPools @@ -1063,6 +1151,10 @@ paths: name: repoID required: true type: string + - description: If true and a webhook is installed for this repo, it will not be removed. + in: query + name: keepWebhook + type: boolean responses: default: description: APIErrorResponse @@ -1275,6 +1367,76 @@ paths: tags: - repositories - pools + /repositories/{repoID}/webhook: + delete: + operationId: UninstallRepoWebhook + parameters: + - description: Repository ID. + in: path + name: repoID + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Uninstall organization webhook. + tags: + - repositories + - hooks + get: + operationId: GetRepoWebhookInfo + parameters: + - description: Repository ID. + in: path + name: repoID + required: true + type: string + responses: + "200": + description: HookInfo + schema: + $ref: '#/definitions/HookInfo' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get information about the GARM installed webhook on a repository. + tags: + - repositories + - hooks + post: + description: |- + Install the GARM webhook for an organization. The secret configured on the organization will + be used to validate the requests. + operationId: InstallRepoWebhook + parameters: + - description: Repository ID. + in: path + name: repoID + required: true + type: string + - description: Parameters used when creating the repository webhook. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/InstallWebhookParams' + description: Parameters used when creating the repository webhook. + type: object + responses: + "200": + description: HookInfo + schema: + $ref: '#/definitions/HookInfo' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + tags: + - repositories + - hooks produces: - application/json security: diff --git a/auth/admin_required.go b/auth/admin_required.go new file mode 100644 index 00000000..8ab6cbac --- /dev/null +++ b/auth/admin_required.go @@ -0,0 +1,14 @@ +package auth + +import "net/http" + +func AdminRequiredMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + if !IsAdmin(ctx) { + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +} diff --git a/client/organizations/delete_org_parameters.go b/client/organizations/delete_org_parameters.go index 92e27495..daf36813 100644 --- a/client/organizations/delete_org_parameters.go +++ b/client/organizations/delete_org_parameters.go @@ -14,6 +14,7 @@ import ( "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" ) // NewDeleteOrgParams creates a new DeleteOrgParams object, @@ -61,6 +62,12 @@ DeleteOrgParams contains all the parameters to send to the API endpoint */ type DeleteOrgParams struct { + /* KeepWebhook. + + If true and a webhook is installed for this organization, it will not be removed. + */ + KeepWebhook *bool + /* OrgID. ID of the organization to delete. @@ -120,6 +127,17 @@ func (o *DeleteOrgParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } +// WithKeepWebhook adds the keepWebhook to the delete org params +func (o *DeleteOrgParams) WithKeepWebhook(keepWebhook *bool) *DeleteOrgParams { + o.SetKeepWebhook(keepWebhook) + return o +} + +// SetKeepWebhook adds the keepWebhook to the delete org params +func (o *DeleteOrgParams) SetKeepWebhook(keepWebhook *bool) { + o.KeepWebhook = keepWebhook +} + // WithOrgID adds the orgID to the delete org params func (o *DeleteOrgParams) WithOrgID(orgID string) *DeleteOrgParams { o.SetOrgID(orgID) @@ -139,6 +157,23 @@ func (o *DeleteOrgParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Reg } var res []error + if o.KeepWebhook != nil { + + // query param keepWebhook + var qrKeepWebhook bool + + if o.KeepWebhook != nil { + qrKeepWebhook = *o.KeepWebhook + } + qKeepWebhook := swag.FormatBool(qrKeepWebhook) + if qKeepWebhook != "" { + + if err := r.SetQueryParam("keepWebhook", qKeepWebhook); err != nil { + return err + } + } + } + // path param orgID if err := r.SetPathParam("orgID", o.OrgID); err != nil { return err diff --git a/client/organizations/get_org_webhook_info_parameters.go b/client/organizations/get_org_webhook_info_parameters.go new file mode 100644 index 00000000..fe67c584 --- /dev/null +++ b/client/organizations/get_org_webhook_info_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetOrgWebhookInfoParams creates a new GetOrgWebhookInfoParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetOrgWebhookInfoParams() *GetOrgWebhookInfoParams { + return &GetOrgWebhookInfoParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetOrgWebhookInfoParamsWithTimeout creates a new GetOrgWebhookInfoParams object +// with the ability to set a timeout on a request. +func NewGetOrgWebhookInfoParamsWithTimeout(timeout time.Duration) *GetOrgWebhookInfoParams { + return &GetOrgWebhookInfoParams{ + timeout: timeout, + } +} + +// NewGetOrgWebhookInfoParamsWithContext creates a new GetOrgWebhookInfoParams object +// with the ability to set a context for a request. +func NewGetOrgWebhookInfoParamsWithContext(ctx context.Context) *GetOrgWebhookInfoParams { + return &GetOrgWebhookInfoParams{ + Context: ctx, + } +} + +// NewGetOrgWebhookInfoParamsWithHTTPClient creates a new GetOrgWebhookInfoParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetOrgWebhookInfoParamsWithHTTPClient(client *http.Client) *GetOrgWebhookInfoParams { + return &GetOrgWebhookInfoParams{ + HTTPClient: client, + } +} + +/* +GetOrgWebhookInfoParams contains all the parameters to send to the API endpoint + + for the get org webhook info operation. + + Typically these are written to a http.Request. +*/ +type GetOrgWebhookInfoParams struct { + + /* OrgID. + + Organization ID. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get org webhook info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetOrgWebhookInfoParams) WithDefaults() *GetOrgWebhookInfoParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get org webhook info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetOrgWebhookInfoParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get org webhook info params +func (o *GetOrgWebhookInfoParams) WithTimeout(timeout time.Duration) *GetOrgWebhookInfoParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get org webhook info params +func (o *GetOrgWebhookInfoParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get org webhook info params +func (o *GetOrgWebhookInfoParams) WithContext(ctx context.Context) *GetOrgWebhookInfoParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get org webhook info params +func (o *GetOrgWebhookInfoParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get org webhook info params +func (o *GetOrgWebhookInfoParams) WithHTTPClient(client *http.Client) *GetOrgWebhookInfoParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get org webhook info params +func (o *GetOrgWebhookInfoParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the get org webhook info params +func (o *GetOrgWebhookInfoParams) WithOrgID(orgID string) *GetOrgWebhookInfoParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the get org webhook info params +func (o *GetOrgWebhookInfoParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetOrgWebhookInfoParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/get_org_webhook_info_responses.go b/client/organizations/get_org_webhook_info_responses.go new file mode 100644 index 00000000..7de76956 --- /dev/null +++ b/client/organizations/get_org_webhook_info_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// GetOrgWebhookInfoReader is a Reader for the GetOrgWebhookInfo structure. +type GetOrgWebhookInfoReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetOrgWebhookInfoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetOrgWebhookInfoOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetOrgWebhookInfoDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetOrgWebhookInfoOK creates a GetOrgWebhookInfoOK with default headers values +func NewGetOrgWebhookInfoOK() *GetOrgWebhookInfoOK { + return &GetOrgWebhookInfoOK{} +} + +/* +GetOrgWebhookInfoOK describes a response with status code 200, with default header values. + +HookInfo +*/ +type GetOrgWebhookInfoOK struct { + Payload garm_params.HookInfo +} + +// IsSuccess returns true when this get org webhook info o k response has a 2xx status code +func (o *GetOrgWebhookInfoOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get org webhook info o k response has a 3xx status code +func (o *GetOrgWebhookInfoOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get org webhook info o k response has a 4xx status code +func (o *GetOrgWebhookInfoOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get org webhook info o k response has a 5xx status code +func (o *GetOrgWebhookInfoOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get org webhook info o k response a status code equal to that given +func (o *GetOrgWebhookInfoOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get org webhook info o k response +func (o *GetOrgWebhookInfoOK) Code() int { + return 200 +} + +func (o *GetOrgWebhookInfoOK) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/webhook][%d] getOrgWebhookInfoOK %+v", 200, o.Payload) +} + +func (o *GetOrgWebhookInfoOK) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/webhook][%d] getOrgWebhookInfoOK %+v", 200, o.Payload) +} + +func (o *GetOrgWebhookInfoOK) GetPayload() garm_params.HookInfo { + return o.Payload +} + +func (o *GetOrgWebhookInfoOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetOrgWebhookInfoDefault creates a GetOrgWebhookInfoDefault with default headers values +func NewGetOrgWebhookInfoDefault(code int) *GetOrgWebhookInfoDefault { + return &GetOrgWebhookInfoDefault{ + _statusCode: code, + } +} + +/* +GetOrgWebhookInfoDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetOrgWebhookInfoDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get org webhook info default response has a 2xx status code +func (o *GetOrgWebhookInfoDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get org webhook info default response has a 3xx status code +func (o *GetOrgWebhookInfoDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get org webhook info default response has a 4xx status code +func (o *GetOrgWebhookInfoDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get org webhook info default response has a 5xx status code +func (o *GetOrgWebhookInfoDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get org webhook info default response a status code equal to that given +func (o *GetOrgWebhookInfoDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get org webhook info default response +func (o *GetOrgWebhookInfoDefault) Code() int { + return o._statusCode +} + +func (o *GetOrgWebhookInfoDefault) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/webhook][%d] GetOrgWebhookInfo default %+v", o._statusCode, o.Payload) +} + +func (o *GetOrgWebhookInfoDefault) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/webhook][%d] GetOrgWebhookInfo default %+v", o._statusCode, o.Payload) +} + +func (o *GetOrgWebhookInfoDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetOrgWebhookInfoDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/install_org_webhook_parameters.go b/client/organizations/install_org_webhook_parameters.go new file mode 100644 index 00000000..b28de742 --- /dev/null +++ b/client/organizations/install_org_webhook_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + garm_params "github.com/cloudbase/garm/params" +) + +// NewInstallOrgWebhookParams creates a new InstallOrgWebhookParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewInstallOrgWebhookParams() *InstallOrgWebhookParams { + return &InstallOrgWebhookParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewInstallOrgWebhookParamsWithTimeout creates a new InstallOrgWebhookParams object +// with the ability to set a timeout on a request. +func NewInstallOrgWebhookParamsWithTimeout(timeout time.Duration) *InstallOrgWebhookParams { + return &InstallOrgWebhookParams{ + timeout: timeout, + } +} + +// NewInstallOrgWebhookParamsWithContext creates a new InstallOrgWebhookParams object +// with the ability to set a context for a request. +func NewInstallOrgWebhookParamsWithContext(ctx context.Context) *InstallOrgWebhookParams { + return &InstallOrgWebhookParams{ + Context: ctx, + } +} + +// NewInstallOrgWebhookParamsWithHTTPClient creates a new InstallOrgWebhookParams object +// with the ability to set a custom HTTPClient for a request. +func NewInstallOrgWebhookParamsWithHTTPClient(client *http.Client) *InstallOrgWebhookParams { + return &InstallOrgWebhookParams{ + HTTPClient: client, + } +} + +/* +InstallOrgWebhookParams contains all the parameters to send to the API endpoint + + for the install org webhook operation. + + Typically these are written to a http.Request. +*/ +type InstallOrgWebhookParams struct { + + /* Body. + + Parameters used when creating the organization webhook. + */ + Body garm_params.InstallWebhookParams + + /* OrgID. + + Organization ID. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the install org webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *InstallOrgWebhookParams) WithDefaults() *InstallOrgWebhookParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the install org webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *InstallOrgWebhookParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the install org webhook params +func (o *InstallOrgWebhookParams) WithTimeout(timeout time.Duration) *InstallOrgWebhookParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the install org webhook params +func (o *InstallOrgWebhookParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the install org webhook params +func (o *InstallOrgWebhookParams) WithContext(ctx context.Context) *InstallOrgWebhookParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the install org webhook params +func (o *InstallOrgWebhookParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the install org webhook params +func (o *InstallOrgWebhookParams) WithHTTPClient(client *http.Client) *InstallOrgWebhookParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the install org webhook params +func (o *InstallOrgWebhookParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the install org webhook params +func (o *InstallOrgWebhookParams) WithBody(body garm_params.InstallWebhookParams) *InstallOrgWebhookParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the install org webhook params +func (o *InstallOrgWebhookParams) SetBody(body garm_params.InstallWebhookParams) { + o.Body = body +} + +// WithOrgID adds the orgID to the install org webhook params +func (o *InstallOrgWebhookParams) WithOrgID(orgID string) *InstallOrgWebhookParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the install org webhook params +func (o *InstallOrgWebhookParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *InstallOrgWebhookParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/install_org_webhook_responses.go b/client/organizations/install_org_webhook_responses.go new file mode 100644 index 00000000..6721ec2f --- /dev/null +++ b/client/organizations/install_org_webhook_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// InstallOrgWebhookReader is a Reader for the InstallOrgWebhook structure. +type InstallOrgWebhookReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *InstallOrgWebhookReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewInstallOrgWebhookOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewInstallOrgWebhookDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewInstallOrgWebhookOK creates a InstallOrgWebhookOK with default headers values +func NewInstallOrgWebhookOK() *InstallOrgWebhookOK { + return &InstallOrgWebhookOK{} +} + +/* +InstallOrgWebhookOK describes a response with status code 200, with default header values. + +HookInfo +*/ +type InstallOrgWebhookOK struct { + Payload garm_params.HookInfo +} + +// IsSuccess returns true when this install org webhook o k response has a 2xx status code +func (o *InstallOrgWebhookOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this install org webhook o k response has a 3xx status code +func (o *InstallOrgWebhookOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this install org webhook o k response has a 4xx status code +func (o *InstallOrgWebhookOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this install org webhook o k response has a 5xx status code +func (o *InstallOrgWebhookOK) IsServerError() bool { + return false +} + +// IsCode returns true when this install org webhook o k response a status code equal to that given +func (o *InstallOrgWebhookOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the install org webhook o k response +func (o *InstallOrgWebhookOK) Code() int { + return 200 +} + +func (o *InstallOrgWebhookOK) Error() string { + return fmt.Sprintf("[POST /organizations/{orgID}/webhook][%d] installOrgWebhookOK %+v", 200, o.Payload) +} + +func (o *InstallOrgWebhookOK) String() string { + return fmt.Sprintf("[POST /organizations/{orgID}/webhook][%d] installOrgWebhookOK %+v", 200, o.Payload) +} + +func (o *InstallOrgWebhookOK) GetPayload() garm_params.HookInfo { + return o.Payload +} + +func (o *InstallOrgWebhookOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewInstallOrgWebhookDefault creates a InstallOrgWebhookDefault with default headers values +func NewInstallOrgWebhookDefault(code int) *InstallOrgWebhookDefault { + return &InstallOrgWebhookDefault{ + _statusCode: code, + } +} + +/* +InstallOrgWebhookDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type InstallOrgWebhookDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this install org webhook default response has a 2xx status code +func (o *InstallOrgWebhookDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this install org webhook default response has a 3xx status code +func (o *InstallOrgWebhookDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this install org webhook default response has a 4xx status code +func (o *InstallOrgWebhookDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this install org webhook default response has a 5xx status code +func (o *InstallOrgWebhookDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this install org webhook default response a status code equal to that given +func (o *InstallOrgWebhookDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the install org webhook default response +func (o *InstallOrgWebhookDefault) Code() int { + return o._statusCode +} + +func (o *InstallOrgWebhookDefault) Error() string { + return fmt.Sprintf("[POST /organizations/{orgID}/webhook][%d] InstallOrgWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *InstallOrgWebhookDefault) String() string { + return fmt.Sprintf("[POST /organizations/{orgID}/webhook][%d] InstallOrgWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *InstallOrgWebhookDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *InstallOrgWebhookDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/organizations_client.go b/client/organizations/organizations_client.go index 3d75cd86..ee00493f 100644 --- a/client/organizations/organizations_client.go +++ b/client/organizations/organizations_client.go @@ -40,12 +40,18 @@ type ClientService interface { GetOrgPool(params *GetOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetOrgPoolOK, error) + GetOrgWebhookInfo(params *GetOrgWebhookInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetOrgWebhookInfoOK, error) + + InstallOrgWebhook(params *InstallOrgWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InstallOrgWebhookOK, error) + ListOrgInstances(params *ListOrgInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgInstancesOK, error) ListOrgPools(params *ListOrgPoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgPoolsOK, error) ListOrgs(params *ListOrgsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgsOK, error) + UninstallOrgWebhook(params *UninstallOrgWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + UpdateOrg(params *UpdateOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateOrgOK, error) UpdateOrgPool(params *UpdateOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateOrgPoolOK, error) @@ -269,6 +275,84 @@ func (a *Client) GetOrgPool(params *GetOrgPoolParams, authInfo runtime.ClientAut return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +GetOrgWebhookInfo gets information about the g a r m installed webhook on an organization +*/ +func (a *Client) GetOrgWebhookInfo(params *GetOrgWebhookInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetOrgWebhookInfoOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetOrgWebhookInfoParams() + } + op := &runtime.ClientOperation{ + ID: "GetOrgWebhookInfo", + Method: "GET", + PathPattern: "/organizations/{orgID}/webhook", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetOrgWebhookInfoReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetOrgWebhookInfoOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetOrgWebhookInfoDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + InstallOrgWebhook Install the GARM webhook for an organization. The secret configured on the organization will + +be used to validate the requests. +*/ +func (a *Client) InstallOrgWebhook(params *InstallOrgWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InstallOrgWebhookOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewInstallOrgWebhookParams() + } + op := &runtime.ClientOperation{ + ID: "InstallOrgWebhook", + Method: "POST", + PathPattern: "/organizations/{orgID}/webhook", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &InstallOrgWebhookReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*InstallOrgWebhookOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*InstallOrgWebhookDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* ListOrgInstances lists organization instances */ @@ -383,6 +467,38 @@ func (a *Client) ListOrgs(params *ListOrgsParams, authInfo runtime.ClientAuthInf return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +UninstallOrgWebhook uninstalls organization webhook +*/ +func (a *Client) UninstallOrgWebhook(params *UninstallOrgWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewUninstallOrgWebhookParams() + } + op := &runtime.ClientOperation{ + ID: "UninstallOrgWebhook", + Method: "DELETE", + PathPattern: "/organizations/{orgID}/webhook", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UninstallOrgWebhookReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + _, err := a.transport.Submit(op) + if err != nil { + return err + } + return nil +} + /* UpdateOrg updates organization with the parameters given */ diff --git a/client/organizations/uninstall_org_webhook_parameters.go b/client/organizations/uninstall_org_webhook_parameters.go new file mode 100644 index 00000000..3914d9c7 --- /dev/null +++ b/client/organizations/uninstall_org_webhook_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewUninstallOrgWebhookParams creates a new UninstallOrgWebhookParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUninstallOrgWebhookParams() *UninstallOrgWebhookParams { + return &UninstallOrgWebhookParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUninstallOrgWebhookParamsWithTimeout creates a new UninstallOrgWebhookParams object +// with the ability to set a timeout on a request. +func NewUninstallOrgWebhookParamsWithTimeout(timeout time.Duration) *UninstallOrgWebhookParams { + return &UninstallOrgWebhookParams{ + timeout: timeout, + } +} + +// NewUninstallOrgWebhookParamsWithContext creates a new UninstallOrgWebhookParams object +// with the ability to set a context for a request. +func NewUninstallOrgWebhookParamsWithContext(ctx context.Context) *UninstallOrgWebhookParams { + return &UninstallOrgWebhookParams{ + Context: ctx, + } +} + +// NewUninstallOrgWebhookParamsWithHTTPClient creates a new UninstallOrgWebhookParams object +// with the ability to set a custom HTTPClient for a request. +func NewUninstallOrgWebhookParamsWithHTTPClient(client *http.Client) *UninstallOrgWebhookParams { + return &UninstallOrgWebhookParams{ + HTTPClient: client, + } +} + +/* +UninstallOrgWebhookParams contains all the parameters to send to the API endpoint + + for the uninstall org webhook operation. + + Typically these are written to a http.Request. +*/ +type UninstallOrgWebhookParams struct { + + /* OrgID. + + Organization ID. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the uninstall org webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UninstallOrgWebhookParams) WithDefaults() *UninstallOrgWebhookParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the uninstall org webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UninstallOrgWebhookParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) WithTimeout(timeout time.Duration) *UninstallOrgWebhookParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) WithContext(ctx context.Context) *UninstallOrgWebhookParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) WithHTTPClient(client *http.Client) *UninstallOrgWebhookParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) WithOrgID(orgID string) *UninstallOrgWebhookParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the uninstall org webhook params +func (o *UninstallOrgWebhookParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *UninstallOrgWebhookParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/uninstall_org_webhook_responses.go b/client/organizations/uninstall_org_webhook_responses.go new file mode 100644 index 00000000..33b1ff97 --- /dev/null +++ b/client/organizations/uninstall_org_webhook_responses.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" +) + +// UninstallOrgWebhookReader is a Reader for the UninstallOrgWebhook structure. +type UninstallOrgWebhookReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UninstallOrgWebhookReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewUninstallOrgWebhookDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result +} + +// NewUninstallOrgWebhookDefault creates a UninstallOrgWebhookDefault with default headers values +func NewUninstallOrgWebhookDefault(code int) *UninstallOrgWebhookDefault { + return &UninstallOrgWebhookDefault{ + _statusCode: code, + } +} + +/* +UninstallOrgWebhookDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UninstallOrgWebhookDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this uninstall org webhook default response has a 2xx status code +func (o *UninstallOrgWebhookDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this uninstall org webhook default response has a 3xx status code +func (o *UninstallOrgWebhookDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this uninstall org webhook default response has a 4xx status code +func (o *UninstallOrgWebhookDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this uninstall org webhook default response has a 5xx status code +func (o *UninstallOrgWebhookDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this uninstall org webhook default response a status code equal to that given +func (o *UninstallOrgWebhookDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the uninstall org webhook default response +func (o *UninstallOrgWebhookDefault) Code() int { + return o._statusCode +} + +func (o *UninstallOrgWebhookDefault) Error() string { + return fmt.Sprintf("[DELETE /organizations/{orgID}/webhook][%d] UninstallOrgWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *UninstallOrgWebhookDefault) String() string { + return fmt.Sprintf("[DELETE /organizations/{orgID}/webhook][%d] UninstallOrgWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *UninstallOrgWebhookDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UninstallOrgWebhookDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/repositories/delete_repo_parameters.go b/client/repositories/delete_repo_parameters.go index 08ea11d9..8bfd54eb 100644 --- a/client/repositories/delete_repo_parameters.go +++ b/client/repositories/delete_repo_parameters.go @@ -14,6 +14,7 @@ import ( "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" ) // NewDeleteRepoParams creates a new DeleteRepoParams object, @@ -61,6 +62,12 @@ DeleteRepoParams contains all the parameters to send to the API endpoint */ type DeleteRepoParams struct { + /* KeepWebhook. + + If true and a webhook is installed for this repo, it will not be removed. + */ + KeepWebhook *bool + /* RepoID. ID of the repository to delete. @@ -120,6 +127,17 @@ func (o *DeleteRepoParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } +// WithKeepWebhook adds the keepWebhook to the delete repo params +func (o *DeleteRepoParams) WithKeepWebhook(keepWebhook *bool) *DeleteRepoParams { + o.SetKeepWebhook(keepWebhook) + return o +} + +// SetKeepWebhook adds the keepWebhook to the delete repo params +func (o *DeleteRepoParams) SetKeepWebhook(keepWebhook *bool) { + o.KeepWebhook = keepWebhook +} + // WithRepoID adds the repoID to the delete repo params func (o *DeleteRepoParams) WithRepoID(repoID string) *DeleteRepoParams { o.SetRepoID(repoID) @@ -139,6 +157,23 @@ func (o *DeleteRepoParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Re } var res []error + if o.KeepWebhook != nil { + + // query param keepWebhook + var qrKeepWebhook bool + + if o.KeepWebhook != nil { + qrKeepWebhook = *o.KeepWebhook + } + qKeepWebhook := swag.FormatBool(qrKeepWebhook) + if qKeepWebhook != "" { + + if err := r.SetQueryParam("keepWebhook", qKeepWebhook); err != nil { + return err + } + } + } + // path param repoID if err := r.SetPathParam("repoID", o.RepoID); err != nil { return err diff --git a/client/repositories/get_repo_webhook_info_parameters.go b/client/repositories/get_repo_webhook_info_parameters.go new file mode 100644 index 00000000..b4c9e515 --- /dev/null +++ b/client/repositories/get_repo_webhook_info_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package repositories + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetRepoWebhookInfoParams creates a new GetRepoWebhookInfoParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetRepoWebhookInfoParams() *GetRepoWebhookInfoParams { + return &GetRepoWebhookInfoParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetRepoWebhookInfoParamsWithTimeout creates a new GetRepoWebhookInfoParams object +// with the ability to set a timeout on a request. +func NewGetRepoWebhookInfoParamsWithTimeout(timeout time.Duration) *GetRepoWebhookInfoParams { + return &GetRepoWebhookInfoParams{ + timeout: timeout, + } +} + +// NewGetRepoWebhookInfoParamsWithContext creates a new GetRepoWebhookInfoParams object +// with the ability to set a context for a request. +func NewGetRepoWebhookInfoParamsWithContext(ctx context.Context) *GetRepoWebhookInfoParams { + return &GetRepoWebhookInfoParams{ + Context: ctx, + } +} + +// NewGetRepoWebhookInfoParamsWithHTTPClient creates a new GetRepoWebhookInfoParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetRepoWebhookInfoParamsWithHTTPClient(client *http.Client) *GetRepoWebhookInfoParams { + return &GetRepoWebhookInfoParams{ + HTTPClient: client, + } +} + +/* +GetRepoWebhookInfoParams contains all the parameters to send to the API endpoint + + for the get repo webhook info operation. + + Typically these are written to a http.Request. +*/ +type GetRepoWebhookInfoParams struct { + + /* RepoID. + + Repository ID. + */ + RepoID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get repo webhook info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetRepoWebhookInfoParams) WithDefaults() *GetRepoWebhookInfoParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get repo webhook info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetRepoWebhookInfoParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) WithTimeout(timeout time.Duration) *GetRepoWebhookInfoParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) WithContext(ctx context.Context) *GetRepoWebhookInfoParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) WithHTTPClient(client *http.Client) *GetRepoWebhookInfoParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithRepoID adds the repoID to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) WithRepoID(repoID string) *GetRepoWebhookInfoParams { + o.SetRepoID(repoID) + return o +} + +// SetRepoID adds the repoId to the get repo webhook info params +func (o *GetRepoWebhookInfoParams) SetRepoID(repoID string) { + o.RepoID = repoID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetRepoWebhookInfoParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param repoID + if err := r.SetPathParam("repoID", o.RepoID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/repositories/get_repo_webhook_info_responses.go b/client/repositories/get_repo_webhook_info_responses.go new file mode 100644 index 00000000..75f61a2b --- /dev/null +++ b/client/repositories/get_repo_webhook_info_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package repositories + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// GetRepoWebhookInfoReader is a Reader for the GetRepoWebhookInfo structure. +type GetRepoWebhookInfoReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetRepoWebhookInfoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetRepoWebhookInfoOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetRepoWebhookInfoDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetRepoWebhookInfoOK creates a GetRepoWebhookInfoOK with default headers values +func NewGetRepoWebhookInfoOK() *GetRepoWebhookInfoOK { + return &GetRepoWebhookInfoOK{} +} + +/* +GetRepoWebhookInfoOK describes a response with status code 200, with default header values. + +HookInfo +*/ +type GetRepoWebhookInfoOK struct { + Payload garm_params.HookInfo +} + +// IsSuccess returns true when this get repo webhook info o k response has a 2xx status code +func (o *GetRepoWebhookInfoOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get repo webhook info o k response has a 3xx status code +func (o *GetRepoWebhookInfoOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get repo webhook info o k response has a 4xx status code +func (o *GetRepoWebhookInfoOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get repo webhook info o k response has a 5xx status code +func (o *GetRepoWebhookInfoOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get repo webhook info o k response a status code equal to that given +func (o *GetRepoWebhookInfoOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get repo webhook info o k response +func (o *GetRepoWebhookInfoOK) Code() int { + return 200 +} + +func (o *GetRepoWebhookInfoOK) Error() string { + return fmt.Sprintf("[GET /repositories/{repoID}/webhook][%d] getRepoWebhookInfoOK %+v", 200, o.Payload) +} + +func (o *GetRepoWebhookInfoOK) String() string { + return fmt.Sprintf("[GET /repositories/{repoID}/webhook][%d] getRepoWebhookInfoOK %+v", 200, o.Payload) +} + +func (o *GetRepoWebhookInfoOK) GetPayload() garm_params.HookInfo { + return o.Payload +} + +func (o *GetRepoWebhookInfoOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetRepoWebhookInfoDefault creates a GetRepoWebhookInfoDefault with default headers values +func NewGetRepoWebhookInfoDefault(code int) *GetRepoWebhookInfoDefault { + return &GetRepoWebhookInfoDefault{ + _statusCode: code, + } +} + +/* +GetRepoWebhookInfoDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetRepoWebhookInfoDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get repo webhook info default response has a 2xx status code +func (o *GetRepoWebhookInfoDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get repo webhook info default response has a 3xx status code +func (o *GetRepoWebhookInfoDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get repo webhook info default response has a 4xx status code +func (o *GetRepoWebhookInfoDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get repo webhook info default response has a 5xx status code +func (o *GetRepoWebhookInfoDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get repo webhook info default response a status code equal to that given +func (o *GetRepoWebhookInfoDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get repo webhook info default response +func (o *GetRepoWebhookInfoDefault) Code() int { + return o._statusCode +} + +func (o *GetRepoWebhookInfoDefault) Error() string { + return fmt.Sprintf("[GET /repositories/{repoID}/webhook][%d] GetRepoWebhookInfo default %+v", o._statusCode, o.Payload) +} + +func (o *GetRepoWebhookInfoDefault) String() string { + return fmt.Sprintf("[GET /repositories/{repoID}/webhook][%d] GetRepoWebhookInfo default %+v", o._statusCode, o.Payload) +} + +func (o *GetRepoWebhookInfoDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetRepoWebhookInfoDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/repositories/install_repo_webhook_parameters.go b/client/repositories/install_repo_webhook_parameters.go new file mode 100644 index 00000000..933ff1b6 --- /dev/null +++ b/client/repositories/install_repo_webhook_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package repositories + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + garm_params "github.com/cloudbase/garm/params" +) + +// NewInstallRepoWebhookParams creates a new InstallRepoWebhookParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewInstallRepoWebhookParams() *InstallRepoWebhookParams { + return &InstallRepoWebhookParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewInstallRepoWebhookParamsWithTimeout creates a new InstallRepoWebhookParams object +// with the ability to set a timeout on a request. +func NewInstallRepoWebhookParamsWithTimeout(timeout time.Duration) *InstallRepoWebhookParams { + return &InstallRepoWebhookParams{ + timeout: timeout, + } +} + +// NewInstallRepoWebhookParamsWithContext creates a new InstallRepoWebhookParams object +// with the ability to set a context for a request. +func NewInstallRepoWebhookParamsWithContext(ctx context.Context) *InstallRepoWebhookParams { + return &InstallRepoWebhookParams{ + Context: ctx, + } +} + +// NewInstallRepoWebhookParamsWithHTTPClient creates a new InstallRepoWebhookParams object +// with the ability to set a custom HTTPClient for a request. +func NewInstallRepoWebhookParamsWithHTTPClient(client *http.Client) *InstallRepoWebhookParams { + return &InstallRepoWebhookParams{ + HTTPClient: client, + } +} + +/* +InstallRepoWebhookParams contains all the parameters to send to the API endpoint + + for the install repo webhook operation. + + Typically these are written to a http.Request. +*/ +type InstallRepoWebhookParams struct { + + /* Body. + + Parameters used when creating the repository webhook. + */ + Body garm_params.InstallWebhookParams + + /* RepoID. + + Repository ID. + */ + RepoID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the install repo webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *InstallRepoWebhookParams) WithDefaults() *InstallRepoWebhookParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the install repo webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *InstallRepoWebhookParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the install repo webhook params +func (o *InstallRepoWebhookParams) WithTimeout(timeout time.Duration) *InstallRepoWebhookParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the install repo webhook params +func (o *InstallRepoWebhookParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the install repo webhook params +func (o *InstallRepoWebhookParams) WithContext(ctx context.Context) *InstallRepoWebhookParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the install repo webhook params +func (o *InstallRepoWebhookParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the install repo webhook params +func (o *InstallRepoWebhookParams) WithHTTPClient(client *http.Client) *InstallRepoWebhookParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the install repo webhook params +func (o *InstallRepoWebhookParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the install repo webhook params +func (o *InstallRepoWebhookParams) WithBody(body garm_params.InstallWebhookParams) *InstallRepoWebhookParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the install repo webhook params +func (o *InstallRepoWebhookParams) SetBody(body garm_params.InstallWebhookParams) { + o.Body = body +} + +// WithRepoID adds the repoID to the install repo webhook params +func (o *InstallRepoWebhookParams) WithRepoID(repoID string) *InstallRepoWebhookParams { + o.SetRepoID(repoID) + return o +} + +// SetRepoID adds the repoId to the install repo webhook params +func (o *InstallRepoWebhookParams) SetRepoID(repoID string) { + o.RepoID = repoID +} + +// WriteToRequest writes these params to a swagger request +func (o *InstallRepoWebhookParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + // path param repoID + if err := r.SetPathParam("repoID", o.RepoID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/repositories/install_repo_webhook_responses.go b/client/repositories/install_repo_webhook_responses.go new file mode 100644 index 00000000..9296fbef --- /dev/null +++ b/client/repositories/install_repo_webhook_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package repositories + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// InstallRepoWebhookReader is a Reader for the InstallRepoWebhook structure. +type InstallRepoWebhookReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *InstallRepoWebhookReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewInstallRepoWebhookOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewInstallRepoWebhookDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewInstallRepoWebhookOK creates a InstallRepoWebhookOK with default headers values +func NewInstallRepoWebhookOK() *InstallRepoWebhookOK { + return &InstallRepoWebhookOK{} +} + +/* +InstallRepoWebhookOK describes a response with status code 200, with default header values. + +HookInfo +*/ +type InstallRepoWebhookOK struct { + Payload garm_params.HookInfo +} + +// IsSuccess returns true when this install repo webhook o k response has a 2xx status code +func (o *InstallRepoWebhookOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this install repo webhook o k response has a 3xx status code +func (o *InstallRepoWebhookOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this install repo webhook o k response has a 4xx status code +func (o *InstallRepoWebhookOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this install repo webhook o k response has a 5xx status code +func (o *InstallRepoWebhookOK) IsServerError() bool { + return false +} + +// IsCode returns true when this install repo webhook o k response a status code equal to that given +func (o *InstallRepoWebhookOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the install repo webhook o k response +func (o *InstallRepoWebhookOK) Code() int { + return 200 +} + +func (o *InstallRepoWebhookOK) Error() string { + return fmt.Sprintf("[POST /repositories/{repoID}/webhook][%d] installRepoWebhookOK %+v", 200, o.Payload) +} + +func (o *InstallRepoWebhookOK) String() string { + return fmt.Sprintf("[POST /repositories/{repoID}/webhook][%d] installRepoWebhookOK %+v", 200, o.Payload) +} + +func (o *InstallRepoWebhookOK) GetPayload() garm_params.HookInfo { + return o.Payload +} + +func (o *InstallRepoWebhookOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewInstallRepoWebhookDefault creates a InstallRepoWebhookDefault with default headers values +func NewInstallRepoWebhookDefault(code int) *InstallRepoWebhookDefault { + return &InstallRepoWebhookDefault{ + _statusCode: code, + } +} + +/* +InstallRepoWebhookDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type InstallRepoWebhookDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this install repo webhook default response has a 2xx status code +func (o *InstallRepoWebhookDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this install repo webhook default response has a 3xx status code +func (o *InstallRepoWebhookDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this install repo webhook default response has a 4xx status code +func (o *InstallRepoWebhookDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this install repo webhook default response has a 5xx status code +func (o *InstallRepoWebhookDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this install repo webhook default response a status code equal to that given +func (o *InstallRepoWebhookDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the install repo webhook default response +func (o *InstallRepoWebhookDefault) Code() int { + return o._statusCode +} + +func (o *InstallRepoWebhookDefault) Error() string { + return fmt.Sprintf("[POST /repositories/{repoID}/webhook][%d] InstallRepoWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *InstallRepoWebhookDefault) String() string { + return fmt.Sprintf("[POST /repositories/{repoID}/webhook][%d] InstallRepoWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *InstallRepoWebhookDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *InstallRepoWebhookDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/repositories/repositories_client.go b/client/repositories/repositories_client.go index e9d2619d..c9903aa3 100644 --- a/client/repositories/repositories_client.go +++ b/client/repositories/repositories_client.go @@ -40,12 +40,18 @@ type ClientService interface { GetRepoPool(params *GetRepoPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetRepoPoolOK, error) + GetRepoWebhookInfo(params *GetRepoWebhookInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetRepoWebhookInfoOK, error) + + InstallRepoWebhook(params *InstallRepoWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InstallRepoWebhookOK, error) + ListRepoInstances(params *ListRepoInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListRepoInstancesOK, error) ListRepoPools(params *ListRepoPoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListRepoPoolsOK, error) ListRepos(params *ListReposParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListReposOK, error) + UninstallRepoWebhook(params *UninstallRepoWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + UpdateRepo(params *UpdateRepoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateRepoOK, error) UpdateRepoPool(params *UpdateRepoPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateRepoPoolOK, error) @@ -269,6 +275,84 @@ func (a *Client) GetRepoPool(params *GetRepoPoolParams, authInfo runtime.ClientA return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +GetRepoWebhookInfo gets information about the g a r m installed webhook on a repository +*/ +func (a *Client) GetRepoWebhookInfo(params *GetRepoWebhookInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetRepoWebhookInfoOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetRepoWebhookInfoParams() + } + op := &runtime.ClientOperation{ + ID: "GetRepoWebhookInfo", + Method: "GET", + PathPattern: "/repositories/{repoID}/webhook", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetRepoWebhookInfoReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetRepoWebhookInfoOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetRepoWebhookInfoDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + InstallRepoWebhook Install the GARM webhook for an organization. The secret configured on the organization will + +be used to validate the requests. +*/ +func (a *Client) InstallRepoWebhook(params *InstallRepoWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InstallRepoWebhookOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewInstallRepoWebhookParams() + } + op := &runtime.ClientOperation{ + ID: "InstallRepoWebhook", + Method: "POST", + PathPattern: "/repositories/{repoID}/webhook", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &InstallRepoWebhookReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*InstallRepoWebhookOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*InstallRepoWebhookDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* ListRepoInstances lists repository instances */ @@ -383,6 +467,38 @@ func (a *Client) ListRepos(params *ListReposParams, authInfo runtime.ClientAuthI return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +UninstallRepoWebhook uninstalls organization webhook +*/ +func (a *Client) UninstallRepoWebhook(params *UninstallRepoWebhookParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewUninstallRepoWebhookParams() + } + op := &runtime.ClientOperation{ + ID: "UninstallRepoWebhook", + Method: "DELETE", + PathPattern: "/repositories/{repoID}/webhook", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UninstallRepoWebhookReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + _, err := a.transport.Submit(op) + if err != nil { + return err + } + return nil +} + /* UpdateRepo updates repository with the parameters given */ diff --git a/client/repositories/uninstall_repo_webhook_parameters.go b/client/repositories/uninstall_repo_webhook_parameters.go new file mode 100644 index 00000000..acefd615 --- /dev/null +++ b/client/repositories/uninstall_repo_webhook_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package repositories + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewUninstallRepoWebhookParams creates a new UninstallRepoWebhookParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUninstallRepoWebhookParams() *UninstallRepoWebhookParams { + return &UninstallRepoWebhookParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUninstallRepoWebhookParamsWithTimeout creates a new UninstallRepoWebhookParams object +// with the ability to set a timeout on a request. +func NewUninstallRepoWebhookParamsWithTimeout(timeout time.Duration) *UninstallRepoWebhookParams { + return &UninstallRepoWebhookParams{ + timeout: timeout, + } +} + +// NewUninstallRepoWebhookParamsWithContext creates a new UninstallRepoWebhookParams object +// with the ability to set a context for a request. +func NewUninstallRepoWebhookParamsWithContext(ctx context.Context) *UninstallRepoWebhookParams { + return &UninstallRepoWebhookParams{ + Context: ctx, + } +} + +// NewUninstallRepoWebhookParamsWithHTTPClient creates a new UninstallRepoWebhookParams object +// with the ability to set a custom HTTPClient for a request. +func NewUninstallRepoWebhookParamsWithHTTPClient(client *http.Client) *UninstallRepoWebhookParams { + return &UninstallRepoWebhookParams{ + HTTPClient: client, + } +} + +/* +UninstallRepoWebhookParams contains all the parameters to send to the API endpoint + + for the uninstall repo webhook operation. + + Typically these are written to a http.Request. +*/ +type UninstallRepoWebhookParams struct { + + /* RepoID. + + Repository ID. + */ + RepoID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the uninstall repo webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UninstallRepoWebhookParams) WithDefaults() *UninstallRepoWebhookParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the uninstall repo webhook params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UninstallRepoWebhookParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) WithTimeout(timeout time.Duration) *UninstallRepoWebhookParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) WithContext(ctx context.Context) *UninstallRepoWebhookParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) WithHTTPClient(client *http.Client) *UninstallRepoWebhookParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithRepoID adds the repoID to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) WithRepoID(repoID string) *UninstallRepoWebhookParams { + o.SetRepoID(repoID) + return o +} + +// SetRepoID adds the repoId to the uninstall repo webhook params +func (o *UninstallRepoWebhookParams) SetRepoID(repoID string) { + o.RepoID = repoID +} + +// WriteToRequest writes these params to a swagger request +func (o *UninstallRepoWebhookParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param repoID + if err := r.SetPathParam("repoID", o.RepoID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/repositories/uninstall_repo_webhook_responses.go b/client/repositories/uninstall_repo_webhook_responses.go new file mode 100644 index 00000000..a74292c6 --- /dev/null +++ b/client/repositories/uninstall_repo_webhook_responses.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package repositories + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" +) + +// UninstallRepoWebhookReader is a Reader for the UninstallRepoWebhook structure. +type UninstallRepoWebhookReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UninstallRepoWebhookReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewUninstallRepoWebhookDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result +} + +// NewUninstallRepoWebhookDefault creates a UninstallRepoWebhookDefault with default headers values +func NewUninstallRepoWebhookDefault(code int) *UninstallRepoWebhookDefault { + return &UninstallRepoWebhookDefault{ + _statusCode: code, + } +} + +/* +UninstallRepoWebhookDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UninstallRepoWebhookDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this uninstall repo webhook default response has a 2xx status code +func (o *UninstallRepoWebhookDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this uninstall repo webhook default response has a 3xx status code +func (o *UninstallRepoWebhookDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this uninstall repo webhook default response has a 4xx status code +func (o *UninstallRepoWebhookDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this uninstall repo webhook default response has a 5xx status code +func (o *UninstallRepoWebhookDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this uninstall repo webhook default response a status code equal to that given +func (o *UninstallRepoWebhookDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the uninstall repo webhook default response +func (o *UninstallRepoWebhookDefault) Code() int { + return o._statusCode +} + +func (o *UninstallRepoWebhookDefault) Error() string { + return fmt.Sprintf("[DELETE /repositories/{repoID}/webhook][%d] UninstallRepoWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *UninstallRepoWebhookDefault) String() string { + return fmt.Sprintf("[DELETE /repositories/{repoID}/webhook][%d] UninstallRepoWebhook default %+v", o._statusCode, o.Payload) +} + +func (o *UninstallRepoWebhookDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UninstallRepoWebhookDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/cmd/garm-cli/cmd/controller_info.go b/cmd/garm-cli/cmd/controller_info.go index 038fe8fe..0a42ae1e 100644 --- a/cmd/garm-cli/cmd/controller_info.go +++ b/cmd/garm-cli/cmd/controller_info.go @@ -46,22 +46,32 @@ var infoShowCmd = &cobra.Command{ if err != nil { return err } - formatInfo(response.Payload) - return nil + return formatInfo(response.Payload) }, } -func formatInfo(info params.ControllerInfo) { +func formatInfo(info params.ControllerInfo) error { t := table.NewWriter() - header := table.Row{"Field", "Value"} + if info.WebhookURL == "" { + info.WebhookURL = "N/A" + } + + if info.ControllerWebhookURL == "" { + info.ControllerWebhookURL = "N/A" + } + t.AppendHeader(header) t.AppendRow(table.Row{"Controller ID", info.ControllerID}) t.AppendRow(table.Row{"Hostname", info.Hostname}) t.AppendRow(table.Row{"Metadata URL", info.MetadataURL}) t.AppendRow(table.Row{"Callback URL", info.CallbackURL}) + t.AppendRow(table.Row{"Webhook Base URL", info.WebhookURL}) + t.AppendRow(table.Row{"Controller Webhook URL", info.ControllerWebhookURL}) fmt.Println(t.Render()) + + return nil } func init() { diff --git a/cmd/garm-cli/cmd/enterprise.go b/cmd/garm-cli/cmd/enterprise.go index c63e0c44..b9ec7fe2 100644 --- a/cmd/garm-cli/cmd/enterprise.go +++ b/cmd/garm-cli/cmd/enterprise.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + "github.com/cloudbase/garm-provider-common/util" apiClientEnterprises "github.com/cloudbase/garm/client/enterprises" "github.com/cloudbase/garm/params" @@ -25,9 +26,10 @@ import ( ) var ( - enterpriseName string - enterpriseWebhookSecret string - enterpriseCreds string + enterpriseName string + enterpriseWebhookSecret string + enterpriseCreds string + enterpriseRandomWebhookSecret bool ) // enterpriseCmd represents the enterprise command @@ -55,6 +57,14 @@ var enterpriseAddCmd = &cobra.Command{ return errNeedsInitError } + if enterpriseRandomWebhookSecret { + secret, err := util.GetRandomString(32) + if err != nil { + return err + } + enterpriseWebhookSecret = secret + } + newEnterpriseReq := apiClientEnterprises.NewCreateEnterpriseParams() newEnterpriseReq.Body = params.CreateEnterpriseParams{ Name: enterpriseName, @@ -179,6 +189,9 @@ func init() { enterpriseAddCmd.Flags().StringVar(&enterpriseName, "name", "", "The name of the enterprise") enterpriseAddCmd.Flags().StringVar(&enterpriseWebhookSecret, "webhook-secret", "", "The webhook secret for this enterprise") enterpriseAddCmd.Flags().StringVar(&enterpriseCreds, "credentials", "", "Credentials name. See credentials list.") + enterpriseAddCmd.Flags().BoolVar(&enterpriseRandomWebhookSecret, "random-webhook-secret", false, "Generate a random webhook secret for this organization.") + enterpriseAddCmd.MarkFlagsMutuallyExclusive("webhook-secret", "random-webhook-secret") + enterpriseAddCmd.MarkFlagRequired("credentials") //nolint enterpriseAddCmd.MarkFlagRequired("name") //nolint enterpriseUpdateCmd.Flags().StringVar(&enterpriseWebhookSecret, "webhook-secret", "", "The webhook secret for this enterprise") diff --git a/cmd/garm-cli/cmd/organization.go b/cmd/garm-cli/cmd/organization.go index 56de989b..d833e2dd 100644 --- a/cmd/garm-cli/cmd/organization.go +++ b/cmd/garm-cli/cmd/organization.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + "github.com/cloudbase/garm-provider-common/util" apiClientOrgs "github.com/cloudbase/garm/client/organizations" "github.com/cloudbase/garm/params" @@ -25,9 +26,13 @@ import ( ) var ( - orgName string - orgWebhookSecret string - orgCreds string + orgName string + orgWebhookSecret string + orgCreds string + orgRandomWebhookSecret bool + insecureOrgWebhook bool + keepOrgWebhook bool + installOrgWebhook bool ) // organizationCmd represents the organization command @@ -44,6 +49,99 @@ organization for which garm maintains pools of self hosted runners.`, Run: nil, } +var orgWebhookCmd = &cobra.Command{ + Use: "webhook", + Short: "Manage organization webhooks", + Long: `Manage organization webhooks.`, + SilenceUsage: true, + Run: nil, +} + +var orgWebhookInstallCmd = &cobra.Command{ + Use: "install", + Short: "Install webhook", + Long: `Install webhook for an organization.`, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires an organization ID") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + installWebhookReq := apiClientOrgs.NewInstallOrgWebhookParams() + installWebhookReq.OrgID = args[0] + installWebhookReq.Body.InsecureSSL = insecureOrgWebhook + installWebhookReq.Body.WebhookEndpointType = params.WebhookEndpointDirect + + response, err := apiCli.Organizations.InstallOrgWebhook(installWebhookReq, authToken) + if err != nil { + return err + } + formatOneHookInfo(response.Payload) + return nil + }, +} + +var orgHookInfoShowCmd = &cobra.Command{ + Use: "show", + Short: "Show webhook info", + Long: `Show webhook info for an organization.`, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires an organization ID") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + showWebhookInfoReq := apiClientOrgs.NewGetOrgWebhookInfoParams() + showWebhookInfoReq.OrgID = args[0] + + response, err := apiCli.Organizations.GetOrgWebhookInfo(showWebhookInfoReq, authToken) + if err != nil { + return err + } + formatOneHookInfo(response.Payload) + return nil + }, +} + +var orgWebhookUninstallCmd = &cobra.Command{ + Use: "uninstall", + Short: "Uninstall webhook", + Long: `Uninstall webhook for an organization.`, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires an organization ID") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + uninstallWebhookReq := apiClientOrgs.NewUninstallOrgWebhookParams() + uninstallWebhookReq.OrgID = args[0] + + err := apiCli.Organizations.UninstallOrgWebhook(uninstallWebhookReq, authToken) + if err != nil { + return err + } + return nil + }, +} + var orgAddCmd = &cobra.Command{ Use: "add", Aliases: []string{"create"}, @@ -55,6 +153,14 @@ var orgAddCmd = &cobra.Command{ return errNeedsInitError } + if orgRandomWebhookSecret { + secret, err := util.GetRandomString(32) + if err != nil { + return err + } + orgWebhookSecret = secret + } + newOrgReq := apiClientOrgs.NewCreateOrgParams() newOrgReq.Body = params.CreateOrgParams{ Name: orgName, @@ -65,7 +171,25 @@ var orgAddCmd = &cobra.Command{ if err != nil { return err } - formatOneOrganization(response.Payload) + + if installOrgWebhook { + installWebhookReq := apiClientOrgs.NewInstallOrgWebhookParams() + installWebhookReq.OrgID = response.Payload.ID + installWebhookReq.Body.WebhookEndpointType = params.WebhookEndpointDirect + + _, err = apiCli.Organizations.InstallOrgWebhook(installWebhookReq, authToken) + if err != nil { + return err + } + } + + getOrgRequest := apiClientOrgs.NewGetOrgParams() + getOrgRequest.OrgID = response.Payload.ID + org, err := apiCli.Organizations.GetOrg(getOrgRequest, authToken) + if err != nil { + return err + } + formatOneOrganization(org.Payload) return nil }, } @@ -89,7 +213,7 @@ var orgUpdateCmd = &cobra.Command{ } updateOrgReq := apiClientOrgs.NewUpdateOrgParams() updateOrgReq.Body = params.UpdateEntityParams{ - WebhookSecret: repoWebhookSecret, + WebhookSecret: orgWebhookSecret, CredentialsName: orgCreds, } updateOrgReq.OrgID = args[0] @@ -167,6 +291,7 @@ var orgDeleteCmd = &cobra.Command{ } deleteOrgReq := apiClientOrgs.NewDeleteOrgParams() deleteOrgReq.OrgID = args[0] + deleteOrgReq.KeepWebhook = &keepOrgWebhook if err := apiCli.Organizations.DeleteOrg(deleteOrgReq, authToken); err != nil { return err } @@ -179,17 +304,33 @@ func init() { orgAddCmd.Flags().StringVar(&orgName, "name", "", "The name of the organization") orgAddCmd.Flags().StringVar(&orgWebhookSecret, "webhook-secret", "", "The webhook secret for this organization") orgAddCmd.Flags().StringVar(&orgCreds, "credentials", "", "Credentials name. See credentials list.") + orgAddCmd.Flags().BoolVar(&orgRandomWebhookSecret, "random-webhook-secret", false, "Generate a random webhook secret for this organization.") + orgAddCmd.Flags().BoolVar(&installOrgWebhook, "install-webhook", false, "Install the webhook as part of the add operation.") + orgAddCmd.MarkFlagsMutuallyExclusive("webhook-secret", "random-webhook-secret") + orgAddCmd.MarkFlagsOneRequired("webhook-secret", "random-webhook-secret") + orgAddCmd.MarkFlagRequired("credentials") //nolint orgAddCmd.MarkFlagRequired("name") //nolint + + orgDeleteCmd.Flags().BoolVar(&keepOrgWebhook, "keep-webhook", false, "Do not delete any existing webhook when removing the organization from GARM.") + orgUpdateCmd.Flags().StringVar(&orgWebhookSecret, "webhook-secret", "", "The webhook secret for this organization") orgUpdateCmd.Flags().StringVar(&orgCreds, "credentials", "", "Credentials name. See credentials list.") + orgWebhookInstallCmd.Flags().BoolVar(&insecureOrgWebhook, "insecure", false, "Ignore self signed certificate errors.") + orgWebhookCmd.AddCommand( + orgWebhookInstallCmd, + orgWebhookUninstallCmd, + orgHookInfoShowCmd, + ) + organizationCmd.AddCommand( orgListCmd, orgAddCmd, orgShowCmd, orgDeleteCmd, orgUpdateCmd, + orgWebhookCmd, ) rootCmd.AddCommand(organizationCmd) diff --git a/cmd/garm-cli/cmd/repository.go b/cmd/garm-cli/cmd/repository.go index 8466b318..8482264b 100644 --- a/cmd/garm-cli/cmd/repository.go +++ b/cmd/garm-cli/cmd/repository.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + "github.com/cloudbase/garm-provider-common/util" apiClientRepos "github.com/cloudbase/garm/client/repositories" "github.com/cloudbase/garm/params" @@ -25,10 +26,14 @@ import ( ) var ( - repoOwner string - repoName string - repoWebhookSecret string - repoCreds string + repoOwner string + repoName string + repoWebhookSecret string + repoCreds string + randomWebhookSecret bool + insecureRepoWebhook bool + keepRepoWebhook bool + installRepoWebhook bool ) // repositoryCmd represents the repository command @@ -45,6 +50,99 @@ repository for which the garm maintains pools of self hosted runners.`, Run: nil, } +var repoWebhookCmd = &cobra.Command{ + Use: "webhook", + Short: "Manage repository webhooks", + Long: `Manage repository webhooks.`, + SilenceUsage: true, + Run: nil, +} + +var repoWebhookInstallCmd = &cobra.Command{ + Use: "install", + Short: "Install webhook", + Long: `Install webhook for a repository.`, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires a repository ID") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + installWebhookReq := apiClientRepos.NewInstallRepoWebhookParams() + installWebhookReq.RepoID = args[0] + installWebhookReq.Body.InsecureSSL = insecureRepoWebhook + installWebhookReq.Body.WebhookEndpointType = params.WebhookEndpointDirect + + response, err := apiCli.Repositories.InstallRepoWebhook(installWebhookReq, authToken) + if err != nil { + return err + } + formatOneHookInfo(response.Payload) + return nil + }, +} + +var repoHookInfoShowCmd = &cobra.Command{ + Use: "show", + Short: "Show webhook info", + Long: `Show webhook info for a repository.`, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires a repository ID") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + showWebhookInfoReq := apiClientRepos.NewGetRepoWebhookInfoParams() + showWebhookInfoReq.RepoID = args[0] + + response, err := apiCli.Repositories.GetRepoWebhookInfo(showWebhookInfoReq, authToken) + if err != nil { + return err + } + formatOneHookInfo(response.Payload) + return nil + }, +} + +var repoWebhookUninstallCmd = &cobra.Command{ + Use: "uninstall", + Short: "Uninstall webhook", + Long: `Uninstall webhook for a repository.`, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires a repository ID") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + uninstallWebhookReq := apiClientRepos.NewUninstallRepoWebhookParams() + uninstallWebhookReq.RepoID = args[0] + + err := apiCli.Repositories.UninstallRepoWebhook(uninstallWebhookReq, authToken) + if err != nil { + return err + } + return nil + }, +} + var repoAddCmd = &cobra.Command{ Use: "add", Aliases: []string{"create"}, @@ -56,6 +154,14 @@ var repoAddCmd = &cobra.Command{ return errNeedsInitError } + if randomWebhookSecret { + secret, err := util.GetRandomString(32) + if err != nil { + return err + } + repoWebhookSecret = secret + } + newRepoReq := apiClientRepos.NewCreateRepoParams() newRepoReq.Body = params.CreateRepoParams{ Owner: repoOwner, @@ -67,7 +173,25 @@ var repoAddCmd = &cobra.Command{ if err != nil { return err } - formatOneRepository(response.Payload) + + if installRepoWebhook { + installWebhookReq := apiClientRepos.NewInstallRepoWebhookParams() + installWebhookReq.RepoID = response.Payload.ID + installWebhookReq.Body.WebhookEndpointType = params.WebhookEndpointDirect + + _, err := apiCli.Repositories.InstallRepoWebhook(installWebhookReq, authToken) + if err != nil { + return err + } + } + + getRepoReq := apiClientRepos.NewGetRepoParams() + getRepoReq.RepoID = response.Payload.ID + repo, err := apiCli.Repositories.GetRepo(getRepoReq, authToken) + if err != nil { + return err + } + formatOneRepository(repo.Payload) return nil }, } @@ -170,6 +294,7 @@ var repoDeleteCmd = &cobra.Command{ } deleteRepoReq := apiClientRepos.NewDeleteRepoParams() deleteRepoReq.RepoID = args[0] + deleteRepoReq.KeepWebhook = &keepRepoWebhook if err := apiCli.Repositories.DeleteRepo(deleteRepoReq, authToken); err != nil { return err } @@ -183,18 +308,35 @@ func init() { repoAddCmd.Flags().StringVar(&repoName, "name", "", "The name of the repository") repoAddCmd.Flags().StringVar(&repoWebhookSecret, "webhook-secret", "", "The webhook secret for this repository") repoAddCmd.Flags().StringVar(&repoCreds, "credentials", "", "Credentials name. See credentials list.") + repoAddCmd.Flags().BoolVar(&randomWebhookSecret, "random-webhook-secret", false, "Generate a random webhook secret for this repository.") + repoAddCmd.Flags().BoolVar(&installRepoWebhook, "install-webhook", false, "Install the webhook as part of the add operation.") + repoAddCmd.MarkFlagsMutuallyExclusive("webhook-secret", "random-webhook-secret") + repoAddCmd.MarkFlagsOneRequired("webhook-secret", "random-webhook-secret") + repoAddCmd.MarkFlagRequired("credentials") //nolint repoAddCmd.MarkFlagRequired("owner") //nolint repoAddCmd.MarkFlagRequired("name") //nolint - repoUpdateCmd.Flags().StringVar(&repoWebhookSecret, "webhook-secret", "", "The webhook secret for this repository") + + repoDeleteCmd.Flags().BoolVar(&keepRepoWebhook, "keep-webhook", false, "Do not delete any existing webhook when removing the repo from GARM.") + + repoUpdateCmd.Flags().StringVar(&repoWebhookSecret, "webhook-secret", "", "The webhook secret for this repository. If you update this secret, you will have to manually update the secret in GitHub as well.") repoUpdateCmd.Flags().StringVar(&repoCreds, "credentials", "", "Credentials name. See credentials list.") + repoWebhookInstallCmd.Flags().BoolVar(&insecureRepoWebhook, "insecure", false, "Ignore self signed certificate errors.") + + repoWebhookCmd.AddCommand( + repoWebhookInstallCmd, + repoWebhookUninstallCmd, + repoHookInfoShowCmd, + ) + repositoryCmd.AddCommand( repoListCmd, repoAddCmd, repoShowCmd, repoDeleteCmd, repoUpdateCmd, + repoWebhookCmd, ) rootCmd.AddCommand(repositoryCmd) diff --git a/cmd/garm-cli/cmd/root.go b/cmd/garm-cli/cmd/root.go index c491e263..72ecddc4 100644 --- a/cmd/garm-cli/cmd/root.go +++ b/cmd/garm-cli/cmd/root.go @@ -21,7 +21,9 @@ import ( apiClient "github.com/cloudbase/garm/client" "github.com/cloudbase/garm/cmd/garm-cli/config" + "github.com/cloudbase/garm/params" "github.com/go-openapi/runtime" + "github.com/jedib0t/go-pretty/v6/table" openapiRuntimeClient "github.com/go-openapi/runtime/client" "github.com/spf13/cobra" @@ -98,3 +100,17 @@ func initConfig() { } initApiClient(mgr.BaseURL, mgr.Token) } + +func formatOneHookInfo(hook params.HookInfo) { + t := table.NewWriter() + header := table.Row{"Field", "Value"} + t.AppendHeader(header) + t.AppendRows([]table.Row{ + {"ID", hook.ID}, + {"URL", hook.URL}, + {"Events", hook.Events}, + {"Active", hook.Active}, + {"Insecure SSL", hook.InsecureSSL}, + }) + fmt.Println(t.Render()) +} diff --git a/cmd/garm/main.go b/cmd/garm/main.go index 04a45f0b..5399fee0 100644 --- a/cmd/garm/main.go +++ b/cmd/garm/main.go @@ -170,7 +170,7 @@ func main() { log.Fatal(err) } - router := routers.NewAPIRouter(controller, multiWriter, jwtMiddleware, initMiddleware, instanceMiddleware) + router := routers.NewAPIRouter(controller, multiWriter, jwtMiddleware, initMiddleware, instanceMiddleware, cfg.Default.EnableWebhookManagement) if cfg.Metrics.Enable { log.Printf("registering prometheus metrics collectors") diff --git a/config/config.go b/config/config.go index a65c4668..c2a12017 100644 --- a/config/config.go +++ b/config/config.go @@ -110,6 +110,11 @@ type Default struct { // MetadataURL is the URL where instances can fetch information they may need // to set themselves up. MetadataURL string `toml:"metadata_url" json:"metadata-url"` + // WebhookURL is the URL that will be installed as a webhook target in github. + WebhookURL string `toml:"webhook_url" json:"webhook-url"` + // EnableWebhookManagement enables the webhook management API. + EnableWebhookManagement bool `toml:"enable_webhook_management" json:"enable-webhook-management"` + // LogFile is the location of the log file. LogFile string `toml:"log_file,omitempty" json:"log-file"` EnableLogStreamer bool `toml:"enable_log_streamer"` @@ -128,6 +133,7 @@ func (d *Default) Validate() error { if d.MetadataURL == "" { return fmt.Errorf("missing metadata-url") } + if _, err := url.Parse(d.MetadataURL); err != nil { return errors.Wrap(err, "validating metadata_url") } diff --git a/go.mod b/go.mod index 5ca40389..adb8e1a1 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/go-openapi/errors v0.20.4 github.com/go-openapi/runtime v0.26.0 github.com/go-openapi/strfmt v0.21.7 + github.com/go-openapi/swag v0.22.4 github.com/golang-jwt/jwt v3.2.2+incompatible github.com/google/go-github/v53 v53.2.0 github.com/google/uuid v1.3.0 @@ -22,7 +23,7 @@ require ( github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.14.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.1-0.20230723113155-fd865a44e3c4 github.com/stretchr/testify v1.8.2 golang.org/x/crypto v0.7.0 golang.org/x/oauth2 v0.8.0 @@ -55,7 +56,6 @@ require ( github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/go-openapi/loads v0.21.2 // indirect github.com/go-openapi/spec v0.20.8 // indirect - github.com/go-openapi/swag v0.22.4 // indirect github.com/go-openapi/validate v0.22.1 // indirect github.com/go-sql-driver/mysql v1.7.0 // indirect github.com/golang/protobuf v1.5.3 // indirect diff --git a/go.sum b/go.sum index fd9e987a..1e8205d2 100644 --- a/go.sum +++ b/go.sum @@ -165,7 +165,6 @@ github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB7 github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= @@ -299,8 +298,8 @@ github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6Mwd github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.1-0.20230723113155-fd865a44e3c4 h1:6be13R0JVLZN659yPzYYO0O1nYeSByDy5eqi85JKG/Y= +github.com/spf13/cobra v1.7.1-0.20230723113155-fd865a44e3c4/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= diff --git a/params/params.go b/params/params.go index 2f0f7371..26764e1d 100644 --- a/params/params.go +++ b/params/params.go @@ -27,12 +27,13 @@ import ( ) type ( - PoolType string - EventType string - EventLevel string - ProviderType string - JobStatus string - RunnerStatus string + PoolType string + EventType string + EventLevel string + ProviderType string + JobStatus string + RunnerStatus string + WebhookEndpointType string ) const ( @@ -42,6 +43,16 @@ const ( ExternalProvider ProviderType = "external" ) +const ( + // WebhookEndpointDirect instructs garm that it should attempt to create a webhook + // in the target entity, using the callback URL defined in the config as a target. + WebhookEndpointDirect WebhookEndpointType = "direct" + // WebhookEndpointTunnel instructs garm that it should attempt to create a webhook + // in the target entity, using the tunnel URL as a base for the webhook URL. + // This is defined for future use. + WebhookEndpointTunnel WebhookEndpointType = "tunnel" +) + const ( JobStatusQueued JobStatus = "queued" JobStatusInProgress JobStatus = "in_progress" @@ -285,11 +296,14 @@ func (p *Pool) PoolType() PoolType { type Pools []Pool type Internal struct { - OAuth2Token string `json:"oauth2"` - ControllerID string `json:"controller_id"` - InstanceCallbackURL string `json:"instance_callback_url"` - InstanceMetadataURL string `json:"instance_metadata_url"` - JWTSecret string `json:"jwt_secret"` + OAuth2Token string `json:"oauth2"` + ControllerID string `json:"controller_id"` + InstanceCallbackURL string `json:"instance_callback_url"` + InstanceMetadataURL string `json:"instance_metadata_url"` + BaseWebhookURL string `json:"base_webhook_url"` + ControllerWebhookURL string `json:"controller_webhook_url"` + + JWTSecret string `json:"jwt_secret"` // GithubCredentialsDetails contains all info about the credentials, except the // token, which is added above. GithubCredentialsDetails GithubCredentials `json:"gh_creds_details"` @@ -379,10 +393,12 @@ type JWTResponse struct { } type ControllerInfo struct { - ControllerID uuid.UUID `json:"controller_id"` - Hostname string `json:"hostname"` - MetadataURL string `json:"metadata_url"` - CallbackURL string `json:"callback_url"` + ControllerID uuid.UUID `json:"controller_id"` + Hostname string `json:"hostname"` + MetadataURL string `json:"metadata_url"` + CallbackURL string `json:"callback_url"` + WebhookURL string `json:"webhook_url"` + ControllerWebhookURL string `json:"controller_webhook_url"` } type GithubCredentials struct { @@ -484,3 +500,16 @@ type Job struct { // used by swagger client generated code type Jobs []Job + +type InstallWebhookParams struct { + WebhookEndpointType WebhookEndpointType `json:"webhook_endpoint_type"` + InsecureSSL bool `json:"insecure_ssl"` +} + +type HookInfo struct { + ID int64 `json:"id"` + URL string `json:"url"` + Events []string `json:"events"` + Active bool `json:"active"` + InsecureSSL bool `json:"insecure_ssl"` +} diff --git a/runner/common/mocks/GithubClient.go b/runner/common/mocks/GithubClient.go index fa65dcef..ebd442ba 100644 --- a/runner/common/mocks/GithubClient.go +++ b/runner/common/mocks/GithubClient.go @@ -14,6 +14,41 @@ type GithubClient struct { mock.Mock } +// CreateOrgHook provides a mock function with given fields: ctx, org, hook +func (_m *GithubClient) CreateOrgHook(ctx context.Context, org string, hook *github.Hook) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, org, hook) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, *github.Hook) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, org, hook) + } + if rf, ok := ret.Get(0).(func(context.Context, string, *github.Hook) *github.Hook); ok { + r0 = rf(ctx, org, hook) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, *github.Hook) *github.Response); ok { + r1 = rf(ctx, org, hook) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, *github.Hook) error); ok { + r2 = rf(ctx, org, hook) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + // CreateOrganizationRegistrationToken provides a mock function with given fields: ctx, owner func (_m *GithubClient) CreateOrganizationRegistrationToken(ctx context.Context, owner string) (*github.RegistrationToken, *github.Response, error) { ret := _m.Called(ctx, owner) @@ -84,6 +119,163 @@ func (_m *GithubClient) CreateRegistrationToken(ctx context.Context, owner strin return r0, r1, r2 } +// CreateRepoHook provides a mock function with given fields: ctx, owner, repo, hook +func (_m *GithubClient) CreateRepoHook(ctx context.Context, owner string, repo string, hook *github.Hook) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, owner, repo, hook) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.Hook) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, owner, repo, hook) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.Hook) *github.Hook); ok { + r0 = rf(ctx, owner, repo, hook) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, *github.Hook) *github.Response); ok { + r1 = rf(ctx, owner, repo, hook) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, string, *github.Hook) error); ok { + r2 = rf(ctx, owner, repo, hook) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// DeleteOrgHook provides a mock function with given fields: ctx, org, id +func (_m *GithubClient) DeleteOrgHook(ctx context.Context, org string, id int64) (*github.Response, error) { + ret := _m.Called(ctx, org, id) + + var r0 *github.Response + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, int64) (*github.Response, error)); ok { + return rf(ctx, org, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, int64) *github.Response); ok { + r0 = rf(ctx, org, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Response) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, int64) error); ok { + r1 = rf(ctx, org, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// DeleteRepoHook provides a mock function with given fields: ctx, owner, repo, id +func (_m *GithubClient) DeleteRepoHook(ctx context.Context, owner string, repo string, id int64) (*github.Response, error) { + ret := _m.Called(ctx, owner, repo, id) + + var r0 *github.Response + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) (*github.Response, error)); ok { + return rf(ctx, owner, repo, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) *github.Response); ok { + r0 = rf(ctx, owner, repo, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Response) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, int64) error); ok { + r1 = rf(ctx, owner, repo, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetOrgHook provides a mock function with given fields: ctx, org, id +func (_m *GithubClient) GetOrgHook(ctx context.Context, org string, id int64) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, org, id) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, int64) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, org, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, int64) *github.Hook); ok { + r0 = rf(ctx, org, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, int64) *github.Response); ok { + r1 = rf(ctx, org, id) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, int64) error); ok { + r2 = rf(ctx, org, id) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// GetRepoHook provides a mock function with given fields: ctx, owner, repo, id +func (_m *GithubClient) GetRepoHook(ctx context.Context, owner string, repo string, id int64) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, owner, repo, id) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, owner, repo, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) *github.Hook); ok { + r0 = rf(ctx, owner, repo, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, int64) *github.Response); ok { + r1 = rf(ctx, owner, repo, id) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, string, int64) error); ok { + r2 = rf(ctx, owner, repo, id) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + // GetWorkflowJobByID provides a mock function with given fields: ctx, owner, repo, jobID func (_m *GithubClient) GetWorkflowJobByID(ctx context.Context, owner string, repo string, jobID int64) (*github.WorkflowJob, *github.Response, error) { ret := _m.Called(ctx, owner, repo, jobID) @@ -119,6 +311,41 @@ func (_m *GithubClient) GetWorkflowJobByID(ctx context.Context, owner string, re return r0, r1, r2 } +// ListOrgHooks provides a mock function with given fields: ctx, org, opts +func (_m *GithubClient) ListOrgHooks(ctx context.Context, org string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, org, opts) + + var r0 []*github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, *github.ListOptions) ([]*github.Hook, *github.Response, error)); ok { + return rf(ctx, org, opts) + } + if rf, ok := ret.Get(0).(func(context.Context, string, *github.ListOptions) []*github.Hook); ok { + r0 = rf(ctx, org, opts) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, *github.ListOptions) *github.Response); ok { + r1 = rf(ctx, org, opts) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, *github.ListOptions) error); ok { + r2 = rf(ctx, org, opts) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + // ListOrganizationRunnerApplicationDownloads provides a mock function with given fields: ctx, owner func (_m *GithubClient) ListOrganizationRunnerApplicationDownloads(ctx context.Context, owner string) ([]*github.RunnerApplicationDownload, *github.Response, error) { ret := _m.Called(ctx, owner) @@ -189,6 +416,41 @@ func (_m *GithubClient) ListOrganizationRunners(ctx context.Context, owner strin return r0, r1, r2 } +// ListRepoHooks provides a mock function with given fields: ctx, owner, repo, opts +func (_m *GithubClient) ListRepoHooks(ctx context.Context, owner string, repo string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, owner, repo, opts) + + var r0 []*github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.ListOptions) ([]*github.Hook, *github.Response, error)); ok { + return rf(ctx, owner, repo, opts) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.ListOptions) []*github.Hook); ok { + r0 = rf(ctx, owner, repo, opts) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, *github.ListOptions) *github.Response); ok { + r1 = rf(ctx, owner, repo, opts) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, string, *github.ListOptions) error); ok { + r2 = rf(ctx, owner, repo, opts) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + // ListRunnerApplicationDownloads provides a mock function with given fields: ctx, owner, repo func (_m *GithubClient) ListRunnerApplicationDownloads(ctx context.Context, owner string, repo string) ([]*github.RunnerApplicationDownload, *github.Response, error) { ret := _m.Called(ctx, owner, repo) diff --git a/runner/common/mocks/OrganizationHooks.go b/runner/common/mocks/OrganizationHooks.go new file mode 100644 index 00000000..4d891f0b --- /dev/null +++ b/runner/common/mocks/OrganizationHooks.go @@ -0,0 +1,160 @@ +// Code generated by mockery v0.0.0-dev. DO NOT EDIT. + +package mocks + +import ( + context "context" + + github "github.com/google/go-github/v53/github" + mock "github.com/stretchr/testify/mock" +) + +// OrganizationHooks is an autogenerated mock type for the OrganizationHooks type +type OrganizationHooks struct { + mock.Mock +} + +// CreateOrgHook provides a mock function with given fields: ctx, org, hook +func (_m *OrganizationHooks) CreateOrgHook(ctx context.Context, org string, hook *github.Hook) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, org, hook) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, *github.Hook) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, org, hook) + } + if rf, ok := ret.Get(0).(func(context.Context, string, *github.Hook) *github.Hook); ok { + r0 = rf(ctx, org, hook) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, *github.Hook) *github.Response); ok { + r1 = rf(ctx, org, hook) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, *github.Hook) error); ok { + r2 = rf(ctx, org, hook) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// DeleteOrgHook provides a mock function with given fields: ctx, org, id +func (_m *OrganizationHooks) DeleteOrgHook(ctx context.Context, org string, id int64) (*github.Response, error) { + ret := _m.Called(ctx, org, id) + + var r0 *github.Response + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, int64) (*github.Response, error)); ok { + return rf(ctx, org, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, int64) *github.Response); ok { + r0 = rf(ctx, org, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Response) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, int64) error); ok { + r1 = rf(ctx, org, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetOrgHook provides a mock function with given fields: ctx, org, id +func (_m *OrganizationHooks) GetOrgHook(ctx context.Context, org string, id int64) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, org, id) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, int64) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, org, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, int64) *github.Hook); ok { + r0 = rf(ctx, org, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, int64) *github.Response); ok { + r1 = rf(ctx, org, id) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, int64) error); ok { + r2 = rf(ctx, org, id) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// ListOrgHooks provides a mock function with given fields: ctx, org, opts +func (_m *OrganizationHooks) ListOrgHooks(ctx context.Context, org string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, org, opts) + + var r0 []*github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, *github.ListOptions) ([]*github.Hook, *github.Response, error)); ok { + return rf(ctx, org, opts) + } + if rf, ok := ret.Get(0).(func(context.Context, string, *github.ListOptions) []*github.Hook); ok { + r0 = rf(ctx, org, opts) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, *github.ListOptions) *github.Response); ok { + r1 = rf(ctx, org, opts) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, *github.ListOptions) error); ok { + r2 = rf(ctx, org, opts) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// NewOrganizationHooks creates a new instance of OrganizationHooks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewOrganizationHooks(t interface { + mock.TestingT + Cleanup(func()) +}) *OrganizationHooks { + mock := &OrganizationHooks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/runner/common/mocks/PoolManager.go b/runner/common/mocks/PoolManager.go index e817407c..46444e28 100644 --- a/runner/common/mocks/PoolManager.go +++ b/runner/common/mocks/PoolManager.go @@ -3,6 +3,8 @@ package mocks import ( + context "context" + params "github.com/cloudbase/garm/params" mock "github.com/stretchr/testify/mock" ) @@ -26,6 +28,30 @@ func (_m *PoolManager) ForceDeleteRunner(runner params.Instance) error { return r0 } +// GetWebhookInfo provides a mock function with given fields: ctx +func (_m *PoolManager) GetWebhookInfo(ctx context.Context) (params.HookInfo, error) { + ret := _m.Called(ctx) + + var r0 params.HookInfo + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (params.HookInfo, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) params.HookInfo); ok { + r0 = rf(ctx) + } else { + r0 = ret.Get(0).(params.HookInfo) + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GithubRunnerRegistrationToken provides a mock function with given fields: func (_m *PoolManager) GithubRunnerRegistrationToken() (string, error) { ret := _m.Called() @@ -78,6 +104,30 @@ func (_m *PoolManager) ID() string { return r0 } +// InstallWebhook provides a mock function with given fields: ctx, param +func (_m *PoolManager) InstallWebhook(ctx context.Context, param params.InstallWebhookParams) (params.HookInfo, error) { + ret := _m.Called(ctx, param) + + var r0 params.HookInfo + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, params.InstallWebhookParams) (params.HookInfo, error)); ok { + return rf(ctx, param) + } + if rf, ok := ret.Get(0).(func(context.Context, params.InstallWebhookParams) params.HookInfo); ok { + r0 = rf(ctx, param) + } else { + r0 = ret.Get(0).(params.HookInfo) + } + + if rf, ok := ret.Get(1).(func(context.Context, params.InstallWebhookParams) error); ok { + r1 = rf(ctx, param) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // RefreshState provides a mock function with given fields: param func (_m *PoolManager) RefreshState(param params.UpdatePoolStateParams) error { ret := _m.Called(param) @@ -134,6 +184,20 @@ func (_m *PoolManager) Stop() error { return r0 } +// UninstallWebhook provides a mock function with given fields: ctx +func (_m *PoolManager) UninstallWebhook(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // Wait provides a mock function with given fields: func (_m *PoolManager) Wait() error { ret := _m.Called() diff --git a/runner/common/mocks/RepositoryHooks.go b/runner/common/mocks/RepositoryHooks.go new file mode 100644 index 00000000..ab9f1496 --- /dev/null +++ b/runner/common/mocks/RepositoryHooks.go @@ -0,0 +1,160 @@ +// Code generated by mockery v0.0.0-dev. DO NOT EDIT. + +package mocks + +import ( + context "context" + + github "github.com/google/go-github/v53/github" + mock "github.com/stretchr/testify/mock" +) + +// RepositoryHooks is an autogenerated mock type for the RepositoryHooks type +type RepositoryHooks struct { + mock.Mock +} + +// CreateRepoHook provides a mock function with given fields: ctx, owner, repo, hook +func (_m *RepositoryHooks) CreateRepoHook(ctx context.Context, owner string, repo string, hook *github.Hook) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, owner, repo, hook) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.Hook) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, owner, repo, hook) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.Hook) *github.Hook); ok { + r0 = rf(ctx, owner, repo, hook) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, *github.Hook) *github.Response); ok { + r1 = rf(ctx, owner, repo, hook) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, string, *github.Hook) error); ok { + r2 = rf(ctx, owner, repo, hook) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// DeleteRepoHook provides a mock function with given fields: ctx, owner, repo, id +func (_m *RepositoryHooks) DeleteRepoHook(ctx context.Context, owner string, repo string, id int64) (*github.Response, error) { + ret := _m.Called(ctx, owner, repo, id) + + var r0 *github.Response + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) (*github.Response, error)); ok { + return rf(ctx, owner, repo, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) *github.Response); ok { + r0 = rf(ctx, owner, repo, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Response) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, int64) error); ok { + r1 = rf(ctx, owner, repo, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetRepoHook provides a mock function with given fields: ctx, owner, repo, id +func (_m *RepositoryHooks) GetRepoHook(ctx context.Context, owner string, repo string, id int64) (*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, owner, repo, id) + + var r0 *github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) (*github.Hook, *github.Response, error)); ok { + return rf(ctx, owner, repo, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, int64) *github.Hook); ok { + r0 = rf(ctx, owner, repo, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, int64) *github.Response); ok { + r1 = rf(ctx, owner, repo, id) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, string, int64) error); ok { + r2 = rf(ctx, owner, repo, id) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// ListRepoHooks provides a mock function with given fields: ctx, owner, repo, opts +func (_m *RepositoryHooks) ListRepoHooks(ctx context.Context, owner string, repo string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) { + ret := _m.Called(ctx, owner, repo, opts) + + var r0 []*github.Hook + var r1 *github.Response + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.ListOptions) ([]*github.Hook, *github.Response, error)); ok { + return rf(ctx, owner, repo, opts) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, *github.ListOptions) []*github.Hook); ok { + r0 = rf(ctx, owner, repo, opts) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*github.Hook) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, *github.ListOptions) *github.Response); ok { + r1 = rf(ctx, owner, repo, opts) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*github.Response) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string, string, *github.ListOptions) error); ok { + r2 = rf(ctx, owner, repo, opts) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// NewRepositoryHooks creates a new instance of RepositoryHooks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRepositoryHooks(t interface { + mock.TestingT + Cleanup(func()) +}) *RepositoryHooks { + mock := &RepositoryHooks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/runner/common/pool.go b/runner/common/pool.go index 39d8d3fa..9024a930 100644 --- a/runner/common/pool.go +++ b/runner/common/pool.go @@ -15,6 +15,7 @@ package common import ( + "context" "time" "github.com/cloudbase/garm/params" @@ -43,7 +44,10 @@ type PoolManager interface { HandleWorkflowJob(job params.WorkflowJob) error RefreshState(param params.UpdatePoolStateParams) error ForceDeleteRunner(runner params.Instance) error - // AddPool(ctx context.Context, pool params.Pool) error + + InstallWebhook(ctx context.Context, param params.InstallWebhookParams) (params.HookInfo, error) + GetWebhookInfo(ctx context.Context) (params.HookInfo, error) + UninstallWebhook(ctx context.Context) error // PoolManager lifecycle functions. Start/stop pool. Start() error diff --git a/runner/common/util.go b/runner/common/util.go index b23295e3..e9ce9ae7 100644 --- a/runner/common/util.go +++ b/runner/common/util.go @@ -6,11 +6,30 @@ import ( "github.com/google/go-github/v53/github" ) +type OrganizationHooks interface { + ListOrgHooks(ctx context.Context, org string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) + GetOrgHook(ctx context.Context, org string, id int64) (*github.Hook, *github.Response, error) + CreateOrgHook(ctx context.Context, org string, hook *github.Hook) (*github.Hook, *github.Response, error) + DeleteOrgHook(ctx context.Context, org string, id int64) (*github.Response, error) + PingOrgHook(ctx context.Context, org string, id int64) (*github.Response, error) +} + +type RepositoryHooks interface { + ListRepoHooks(ctx context.Context, owner, repo string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) + GetRepoHook(ctx context.Context, owner, repo string, id int64) (*github.Hook, *github.Response, error) + CreateRepoHook(ctx context.Context, owner, repo string, hook *github.Hook) (*github.Hook, *github.Response, error) + DeleteRepoHook(ctx context.Context, owner, repo string, id int64) (*github.Response, error) + PingRepoHook(ctx context.Context, owner, repo string, id int64) (*github.Response, error) +} + // GithubClient that describes the minimum list of functions we need to interact with github. // Allows for easier testing. // //go:generate mockery --all type GithubClient interface { + OrganizationHooks + RepositoryHooks + // GetWorkflowJobByID gets details about a single workflow job. GetWorkflowJobByID(ctx context.Context, owner, repo string, jobID int64) (*github.WorkflowJob, *github.Response, error) // ListRunners lists all runners within a repository. diff --git a/runner/organizations.go b/runner/organizations.go index 61ebcc6a..8e8c2a70 100644 --- a/runner/organizations.go +++ b/runner/organizations.go @@ -124,7 +124,7 @@ func (r *Runner) GetOrganizationByID(ctx context.Context, orgID string) (params. return org, nil } -func (r *Runner) DeleteOrganization(ctx context.Context, orgID string) error { +func (r *Runner) DeleteOrganization(ctx context.Context, orgID string, keepWebhook bool) error { if !auth.IsAdmin(ctx) { return runnerErrors.ErrUnauthorized } @@ -148,6 +148,18 @@ func (r *Runner) DeleteOrganization(ctx context.Context, orgID string) error { return runnerErrors.NewBadRequestError("org has pools defined (%s)", strings.Join(poolIds, ", ")) } + if !keepWebhook && r.config.Default.EnableWebhookManagement { + poolMgr, err := r.poolManagerCtrl.GetOrgPoolManager(org) + if err != nil { + return errors.Wrap(err, "fetching pool manager") + } + + if err := poolMgr.UninstallWebhook(ctx); err != nil { + // TODO(gabriel-samfira): Should we error out here? + log.Printf("failed to uninstall webhook: %s", err) + } + } + if err := r.poolManagerCtrl.DeleteOrgPoolManager(org); err != nil { return errors.Wrap(err, "deleting org pool manager") } @@ -339,3 +351,68 @@ func (r *Runner) findOrgPoolManager(name string) (common.PoolManager, error) { } return poolManager, nil } + +func (r *Runner) InstallOrgWebhook(ctx context.Context, orgID string, param params.InstallWebhookParams) (params.HookInfo, error) { + if !auth.IsAdmin(ctx) { + return params.HookInfo{}, runnerErrors.ErrUnauthorized + } + + org, err := r.store.GetOrganizationByID(ctx, orgID) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching org") + } + + poolMgr, err := r.poolManagerCtrl.GetOrgPoolManager(org) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching pool manager for org") + } + + info, err := poolMgr.InstallWebhook(ctx, param) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "installing webhook") + } + return info, nil +} + +func (r *Runner) UninstallOrgWebhook(ctx context.Context, orgID string) error { + if !auth.IsAdmin(ctx) { + return runnerErrors.ErrUnauthorized + } + + org, err := r.store.GetOrganizationByID(ctx, orgID) + if err != nil { + return errors.Wrap(err, "fetching org") + } + + poolMgr, err := r.poolManagerCtrl.GetOrgPoolManager(org) + if err != nil { + return errors.Wrap(err, "fetching pool manager for org") + } + + if err := poolMgr.UninstallWebhook(ctx); err != nil { + return errors.Wrap(err, "uninstalling webhook") + } + return nil +} + +func (r *Runner) GetOrgWebhookInfo(ctx context.Context, orgID string) (params.HookInfo, error) { + if !auth.IsAdmin(ctx) { + return params.HookInfo{}, runnerErrors.ErrUnauthorized + } + + org, err := r.store.GetOrganizationByID(ctx, orgID) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching org") + } + + poolMgr, err := r.poolManagerCtrl.GetOrgPoolManager(org) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching pool manager for org") + } + + info, err := poolMgr.GetWebhookInfo(ctx) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching webhook info") + } + return info, nil +} diff --git a/runner/organizations_test.go b/runner/organizations_test.go index f6c1e170..3aa3e427 100644 --- a/runner/organizations_test.go +++ b/runner/organizations_test.go @@ -254,7 +254,7 @@ func (s *OrgTestSuite) TestGetOrganizationByIDErrUnauthorized() { func (s *OrgTestSuite) TestDeleteOrganization() { s.Fixtures.PoolMgrCtrlMock.On("DeleteOrgPoolManager", mock.AnythingOfType("params.Organization")).Return(nil) - err := s.Runner.DeleteOrganization(s.Fixtures.AdminContext, s.Fixtures.StoreOrgs["test-org-3"].ID) + err := s.Runner.DeleteOrganization(s.Fixtures.AdminContext, s.Fixtures.StoreOrgs["test-org-3"].ID, true) s.Fixtures.PoolMgrCtrlMock.AssertExpectations(s.T()) s.Require().Nil(err) @@ -264,7 +264,7 @@ func (s *OrgTestSuite) TestDeleteOrganization() { } func (s *OrgTestSuite) TestDeleteOrganizationErrUnauthorized() { - err := s.Runner.DeleteOrganization(context.Background(), "dummy-org-id") + err := s.Runner.DeleteOrganization(context.Background(), "dummy-org-id", true) s.Require().Equal(runnerErrors.ErrUnauthorized, err) } @@ -275,7 +275,7 @@ func (s *OrgTestSuite) TestDeleteOrganizationPoolDefinedFailed() { s.FailNow(fmt.Sprintf("cannot create store organizations pool: %v", err)) } - err = s.Runner.DeleteOrganization(s.Fixtures.AdminContext, s.Fixtures.StoreOrgs["test-org-1"].ID) + err = s.Runner.DeleteOrganization(s.Fixtures.AdminContext, s.Fixtures.StoreOrgs["test-org-1"].ID, true) s.Require().Equal(runnerErrors.NewBadRequestError("org has pools defined (%s)", pool.ID), err) } @@ -283,7 +283,7 @@ func (s *OrgTestSuite) TestDeleteOrganizationPoolDefinedFailed() { func (s *OrgTestSuite) TestDeleteOrganizationPoolMgrFailed() { s.Fixtures.PoolMgrCtrlMock.On("DeleteOrgPoolManager", mock.AnythingOfType("params.Organization")).Return(s.Fixtures.ErrMock) - err := s.Runner.DeleteOrganization(s.Fixtures.AdminContext, s.Fixtures.StoreOrgs["test-org-1"].ID) + err := s.Runner.DeleteOrganization(s.Fixtures.AdminContext, s.Fixtures.StoreOrgs["test-org-1"].ID, true) s.Fixtures.PoolMgrCtrlMock.AssertExpectations(s.T()) s.Require().Equal(fmt.Sprintf("deleting org pool manager: %s", s.Fixtures.ErrMock.Error()), err.Error()) diff --git a/runner/pool/common.go b/runner/pool/common.go new file mode 100644 index 00000000..a89a5ac6 --- /dev/null +++ b/runner/pool/common.go @@ -0,0 +1,63 @@ +package pool + +import ( + "net/url" + "strings" + + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm/params" + "github.com/google/go-github/v53/github" + "github.com/pkg/errors" +) + +func validateHookRequest(controllerID, baseURL string, allHooks []*github.Hook, req *github.Hook) error { + parsed, err := url.Parse(baseURL) + if err != nil { + return errors.Wrap(err, "parsing webhook url") + } + + partialMatches := []string{} + for _, hook := range allHooks { + hookURL, ok := hook.Config["url"].(string) + if !ok { + continue + } + hookURL = strings.ToLower(hookURL) + + if hook.Config["url"] == req.Config["url"] { + return runnerErrors.NewConflictError("hook already installed") + } else if strings.Contains(hookURL, controllerID) || strings.Contains(hookURL, parsed.Hostname()) { + partialMatches = append(partialMatches, hook.Config["url"].(string)) + } + } + + if len(partialMatches) > 0 { + return runnerErrors.NewConflictError("a webhook containing the controller ID or hostname of this contreoller is already installed on this repository") + } + + return nil +} + +func hookToParamsHookInfo(hook *github.Hook) params.HookInfo { + var hookURL string + url, ok := hook.Config["url"] + if ok { + hookURL = url.(string) + } + + var insecureSSL bool + insecureSSLConfig, ok := hook.Config["insecure_ssl"] + if ok { + if insecureSSLConfig.(string) == "1" { + insecureSSL = true + } + } + + return params.HookInfo{ + ID: *hook.ID, + URL: hookURL, + Events: hook.Events, + Active: *hook.Active, + InsecureSSL: insecureSSL, + } +} diff --git a/runner/pool/enterprise.go b/runner/pool/enterprise.go index 025c3415..b61fb2ba 100644 --- a/runner/pool/enterprise.go +++ b/runner/pool/enterprise.go @@ -197,14 +197,6 @@ func (r *enterprise) WebhookSecret() string { return r.cfg.WebhookSecret } -func (r *enterprise) GetCallbackURL() string { - return r.cfgInternal.InstanceCallbackURL -} - -func (r *enterprise) GetMetadataURL() string { - return r.cfgInternal.InstanceMetadataURL -} - func (r *enterprise) FindPoolByTags(labels []string) (params.Pool, error) { pool, err := r.store.FindEnterprisePoolByTags(r.ctx, r.id, labels) if err != nil { @@ -231,3 +223,15 @@ func (r *enterprise) ValidateOwner(job params.WorkflowJob) error { func (r *enterprise) ID() string { return r.id } + +func (r *enterprise) InstallHook(ctx context.Context, req *github.Hook) (params.HookInfo, error) { + return params.HookInfo{}, fmt.Errorf("not implemented") +} + +func (r *enterprise) UninstallHook(ctx context.Context, url string) error { + return fmt.Errorf("not implemented") +} + +func (r *enterprise) GetHookInfo(ctx context.Context) (params.HookInfo, error) { + return params.HookInfo{}, fmt.Errorf("not implemented") +} diff --git a/runner/pool/interfaces.go b/runner/pool/interfaces.go index e707cdae..c1882523 100644 --- a/runner/pool/interfaces.go +++ b/runner/pool/interfaces.go @@ -15,6 +15,8 @@ package pool import ( + "context" + "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" @@ -29,6 +31,10 @@ type poolHelper interface { RemoveGithubRunner(runnerID int64) (*github.Response, error) FetchTools() ([]*github.RunnerApplicationDownload, error) + InstallHook(ctx context.Context, req *github.Hook) (params.HookInfo, error) + UninstallHook(ctx context.Context, url string) error + GetHookInfo(ctx context.Context) (params.HookInfo, error) + GithubCLI() common.GithubClient FetchDbInstances() ([]params.Instance, error) @@ -36,8 +42,6 @@ type poolHelper interface { GithubURL() string JwtToken() string String() string - GetCallbackURL() string - GetMetadataURL() string FindPoolByTags(labels []string) (params.Pool, error) GetPoolByID(poolID string) (params.Pool, error) ValidateOwner(job params.WorkflowJob) error diff --git a/runner/pool/organization.go b/runner/pool/organization.go index a8a6ed9d..db2e2938 100644 --- a/runner/pool/organization.go +++ b/runner/pool/organization.go @@ -17,6 +17,7 @@ package pool import ( "context" "fmt" + "log" "net/http" "strings" "sync" @@ -57,6 +58,12 @@ func NewOrganizationPoolManager(ctx context.Context, cfg params.Organization, cf store: store, providers: providers, controllerID: cfgInternal.ControllerID, + urls: urls{ + webhookURL: cfgInternal.BaseWebhookURL, + callbackURL: cfgInternal.InstanceCallbackURL, + metadataURL: cfgInternal.InstanceMetadataURL, + controllerWebhookURL: cfgInternal.ControllerWebhookURL, + }, quit: make(chan struct{}), helper: helper, credsDetails: cfgInternal.GithubCredentialsDetails, @@ -210,14 +217,6 @@ func (r *organization) WebhookSecret() string { return r.cfg.WebhookSecret } -func (r *organization) GetCallbackURL() string { - return r.cfgInternal.InstanceCallbackURL -} - -func (r *organization) GetMetadataURL() string { - return r.cfgInternal.InstanceMetadataURL -} - func (r *organization) FindPoolByTags(labels []string) (params.Pool, error) { pool, err := r.store.FindOrganizationPoolByTags(r.ctx, r.id, labels) if err != nil { @@ -244,3 +243,81 @@ func (r *organization) ValidateOwner(job params.WorkflowJob) error { func (r *organization) ID() string { return r.id } + +func (r *organization) listHooks(ctx context.Context) ([]*github.Hook, error) { + opts := github.ListOptions{ + PerPage: 100, + } + var allHooks []*github.Hook + for { + hooks, ghResp, err := r.ghcli.ListOrgHooks(ctx, r.cfg.Name, &opts) + if err != nil { + if ghResp != nil && ghResp.StatusCode == http.StatusNotFound { + return nil, runnerErrors.NewBadRequestError("organization not found or your PAT does not have access to manage webhooks") + } + return nil, errors.Wrap(err, "fetching hooks") + } + allHooks = append(allHooks, hooks...) + if ghResp.NextPage == 0 { + break + } + opts.Page = ghResp.NextPage + } + return allHooks, nil +} + +func (r *organization) InstallHook(ctx context.Context, req *github.Hook) (params.HookInfo, error) { + allHooks, err := r.listHooks(ctx) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "listing hooks") + } + + if err := validateHookRequest(r.cfgInternal.ControllerID, r.cfgInternal.BaseWebhookURL, allHooks, req); err != nil { + return params.HookInfo{}, errors.Wrap(err, "validating hook request") + } + + hook, _, err := r.ghcli.CreateOrgHook(ctx, r.cfg.Name, req) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "creating organization hook") + } + + if _, err := r.ghcli.PingOrgHook(ctx, r.cfg.Name, hook.GetID()); err != nil { + log.Printf("failed to ping hook %d: %v", *hook.ID, err) + } + + return hookToParamsHookInfo(hook), nil +} + +func (r *organization) UninstallHook(ctx context.Context, url string) error { + allHooks, err := r.listHooks(ctx) + if err != nil { + return errors.Wrap(err, "listing hooks") + } + + for _, hook := range allHooks { + if hook.Config["url"] == url { + _, err = r.ghcli.DeleteOrgHook(ctx, r.cfg.Name, hook.GetID()) + if err != nil { + return errors.Wrap(err, "deleting hook") + } + return nil + } + } + return nil +} + +func (r *organization) GetHookInfo(ctx context.Context) (params.HookInfo, error) { + allHooks, err := r.listHooks(ctx) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "listing hooks") + } + + for _, hook := range allHooks { + hookInfo := hookToParamsHookInfo(hook) + if strings.EqualFold(hookInfo.URL, r.cfgInternal.ControllerWebhookURL) { + return hookInfo, nil + } + } + + return params.HookInfo{}, runnerErrors.NewNotFoundError("hook not found") +} diff --git a/runner/pool/pool.go b/runner/pool/pool.go index a2516605..55b63692 100644 --- a/runner/pool/pool.go +++ b/runner/pool/pool.go @@ -85,6 +85,12 @@ func (k *keyMutex) Delete(key string) { k.muxes.Delete(key) } +type urls struct { + callbackURL string + metadataURL string + webhookURL string + controllerWebhookURL string +} type basePoolManager struct { ctx context.Context controllerID string @@ -101,6 +107,8 @@ type basePoolManager struct { managerIsRunning bool managerErrorReason string + urls urls + mux sync.Mutex wg *sync.WaitGroup keyMux *keyMutex @@ -686,8 +694,8 @@ func (r *basePoolManager) AddRunner(ctx context.Context, poolID string, aditiona RunnerStatus: params.RunnerPending, OSArch: pool.OSArch, OSType: pool.OSType, - CallbackURL: r.helper.GetCallbackURL(), - MetadataURL: r.helper.GetMetadataURL(), + CallbackURL: r.urls.callbackURL, + MetadataURL: r.urls.metadataURL, CreateAttempt: 1, GitHubRunnerGroup: pool.GitHubRunnerGroup, AditionalLabels: aditionalLabels, @@ -1598,3 +1606,40 @@ func (r *basePoolManager) consumeQueuedJobs() error { } return nil } + +func (r *basePoolManager) InstallWebhook(ctx context.Context, param params.InstallWebhookParams) (params.HookInfo, error) { + if r.urls.controllerWebhookURL == "" { + return params.HookInfo{}, errors.Wrap(runnerErrors.ErrBadRequest, "controller webhook url is empty") + } + + insecureSSL := "0" + if param.InsecureSSL { + insecureSSL = "1" + } + req := &github.Hook{ + Active: github.Bool(true), + Config: map[string]interface{}{ + "url": r.urls.controllerWebhookURL, + "content_type": "json", + "insecure_ssl": insecureSSL, + "secret": r.WebhookSecret(), + }, + Events: []string{ + "workflow_job", + }, + } + + return r.helper.InstallHook(ctx, req) +} + +func (r *basePoolManager) UninstallWebhook(ctx context.Context) error { + if r.urls.controllerWebhookURL == "" { + return errors.Wrap(runnerErrors.ErrBadRequest, "controller webhook url is empty") + } + + return r.helper.UninstallHook(ctx, r.urls.controllerWebhookURL) +} + +func (r *basePoolManager) GetWebhookInfo(ctx context.Context) (params.HookInfo, error) { + return r.helper.GetHookInfo(ctx) +} diff --git a/runner/pool/repository.go b/runner/pool/repository.go index 86dc5cec..4fb976d1 100644 --- a/runner/pool/repository.go +++ b/runner/pool/repository.go @@ -17,6 +17,7 @@ package pool import ( "context" "fmt" + "log" "net/http" "strings" "sync" @@ -57,6 +58,12 @@ func NewRepositoryPoolManager(ctx context.Context, cfg params.Repository, cfgInt store: store, providers: providers, controllerID: cfgInternal.ControllerID, + urls: urls{ + webhookURL: cfgInternal.BaseWebhookURL, + callbackURL: cfgInternal.InstanceCallbackURL, + metadataURL: cfgInternal.InstanceMetadataURL, + controllerWebhookURL: cfgInternal.ControllerWebhookURL, + }, quit: make(chan struct{}), helper: helper, credsDetails: cfgInternal.GithubCredentialsDetails, @@ -211,14 +218,6 @@ func (r *repository) WebhookSecret() string { return r.cfg.WebhookSecret } -func (r *repository) GetCallbackURL() string { - return r.cfgInternal.InstanceCallbackURL -} - -func (r *repository) GetMetadataURL() string { - return r.cfgInternal.InstanceMetadataURL -} - func (r *repository) FindPoolByTags(labels []string) (params.Pool, error) { pool, err := r.store.FindRepositoryPoolByTags(r.ctx, r.id, labels) if err != nil { @@ -245,3 +244,80 @@ func (r *repository) ValidateOwner(job params.WorkflowJob) error { func (r *repository) ID() string { return r.id } + +func (r *repository) listHooks(ctx context.Context) ([]*github.Hook, error) { + opts := github.ListOptions{ + PerPage: 100, + } + var allHooks []*github.Hook + for { + hooks, ghResp, err := r.ghcli.ListRepoHooks(ctx, r.cfg.Owner, r.cfg.Name, &opts) + if err != nil { + if ghResp != nil && ghResp.StatusCode == http.StatusNotFound { + return nil, runnerErrors.NewBadRequestError("repository not found or your PAT does not have access to manage webhooks") + } + return nil, errors.Wrap(err, "fetching hooks") + } + allHooks = append(allHooks, hooks...) + if ghResp.NextPage == 0 { + break + } + opts.Page = ghResp.NextPage + } + return allHooks, nil +} + +func (r *repository) InstallHook(ctx context.Context, req *github.Hook) (params.HookInfo, error) { + allHooks, err := r.listHooks(ctx) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "listing hooks") + } + + if err := validateHookRequest(r.cfgInternal.ControllerID, r.cfgInternal.BaseWebhookURL, allHooks, req); err != nil { + return params.HookInfo{}, errors.Wrap(err, "validating hook request") + } + + hook, _, err := r.ghcli.CreateRepoHook(ctx, r.cfg.Owner, r.cfg.Name, req) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "creating repository hook") + } + + if _, err := r.ghcli.PingRepoHook(ctx, r.cfg.Owner, r.cfg.Name, hook.GetID()); err != nil { + log.Printf("failed to ping hook %d: %v", hook.GetID(), err) + } + + return hookToParamsHookInfo(hook), nil +} + +func (r *repository) UninstallHook(ctx context.Context, url string) error { + allHooks, err := r.listHooks(ctx) + if err != nil { + return errors.Wrap(err, "listing hooks") + } + + for _, hook := range allHooks { + if hook.Config["url"] == url { + _, err = r.ghcli.DeleteRepoHook(ctx, r.cfg.Owner, r.cfg.Name, hook.GetID()) + if err != nil { + return errors.Wrap(err, "deleting hook") + } + return nil + } + } + return nil +} + +func (r *repository) GetHookInfo(ctx context.Context) (params.HookInfo, error) { + allHooks, err := r.listHooks(ctx) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "listing hooks") + } + + for _, hook := range allHooks { + hookInfo := hookToParamsHookInfo(hook) + if strings.EqualFold(hookInfo.URL, r.cfgInternal.ControllerWebhookURL) { + return hookInfo, nil + } + } + return params.HookInfo{}, runnerErrors.NewNotFoundError("hook not found") +} diff --git a/runner/repositories.go b/runner/repositories.go index cf5191dd..54859c4e 100644 --- a/runner/repositories.go +++ b/runner/repositories.go @@ -123,7 +123,7 @@ func (r *Runner) GetRepositoryByID(ctx context.Context, repoID string) (params.R return repo, nil } -func (r *Runner) DeleteRepository(ctx context.Context, repoID string) error { +func (r *Runner) DeleteRepository(ctx context.Context, repoID string, keepWebhook bool) error { if !auth.IsAdmin(ctx) { return runnerErrors.ErrUnauthorized } @@ -147,6 +147,18 @@ func (r *Runner) DeleteRepository(ctx context.Context, repoID string) error { return runnerErrors.NewBadRequestError("repo has pools defined (%s)", strings.Join(poolIds, ", ")) } + if !keepWebhook && r.config.Default.EnableWebhookManagement { + poolMgr, err := r.poolManagerCtrl.GetRepoPoolManager(repo) + if err != nil { + return errors.Wrap(err, "fetching pool manager") + } + + if err := poolMgr.UninstallWebhook(ctx); err != nil { + // TODO(gabriel-samfira): Should we error out here? + log.Printf("failed to uninstall webhook: %s", err) + } + } + if err := r.poolManagerCtrl.DeleteRepoPoolManager(repo); err != nil { return errors.Wrap(err, "deleting repo pool manager") } @@ -349,3 +361,68 @@ func (r *Runner) findRepoPoolManager(owner, name string) (common.PoolManager, er } return poolManager, nil } + +func (r *Runner) InstallRepoWebhook(ctx context.Context, repoID string, param params.InstallWebhookParams) (params.HookInfo, error) { + if !auth.IsAdmin(ctx) { + return params.HookInfo{}, runnerErrors.ErrUnauthorized + } + + repo, err := r.store.GetRepositoryByID(ctx, repoID) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching repo") + } + + poolManager, err := r.poolManagerCtrl.GetRepoPoolManager(repo) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching pool manager for repo") + } + + info, err := poolManager.InstallWebhook(ctx, param) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "installing webhook") + } + return info, nil +} + +func (r *Runner) UninstallRepoWebhook(ctx context.Context, repoID string) error { + if !auth.IsAdmin(ctx) { + return runnerErrors.ErrUnauthorized + } + + repo, err := r.store.GetRepositoryByID(ctx, repoID) + if err != nil { + return errors.Wrap(err, "fetching repo") + } + + poolManager, err := r.poolManagerCtrl.GetRepoPoolManager(repo) + if err != nil { + return errors.Wrap(err, "fetching pool manager for repo") + } + + if err := poolManager.UninstallWebhook(ctx); err != nil { + return errors.Wrap(err, "uninstalling webhook") + } + return nil +} + +func (r *Runner) GetRepoWebhookInfo(ctx context.Context, repoID string) (params.HookInfo, error) { + if !auth.IsAdmin(ctx) { + return params.HookInfo{}, runnerErrors.ErrUnauthorized + } + + repo, err := r.store.GetRepositoryByID(ctx, repoID) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching repo") + } + + poolManager, err := r.poolManagerCtrl.GetRepoPoolManager(repo) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "fetching pool manager for repo") + } + + info, err := poolManager.GetWebhookInfo(ctx) + if err != nil { + return params.HookInfo{}, errors.Wrap(err, "getting webhook info") + } + return info, nil +} diff --git a/runner/repositories_test.go b/runner/repositories_test.go index 0b2c527a..4c918124 100644 --- a/runner/repositories_test.go +++ b/runner/repositories_test.go @@ -257,7 +257,7 @@ func (s *RepoTestSuite) TestGetRepositoryByIDErrUnauthorized() { func (s *RepoTestSuite) TestDeleteRepository() { s.Fixtures.PoolMgrCtrlMock.On("DeleteRepoPoolManager", mock.AnythingOfType("params.Repository")).Return(nil) - err := s.Runner.DeleteRepository(s.Fixtures.AdminContext, s.Fixtures.StoreRepos["test-repo-1"].ID) + err := s.Runner.DeleteRepository(s.Fixtures.AdminContext, s.Fixtures.StoreRepos["test-repo-1"].ID, true) s.Fixtures.PoolMgrCtrlMock.AssertExpectations(s.T()) s.Require().Nil(err) @@ -267,7 +267,7 @@ func (s *RepoTestSuite) TestDeleteRepository() { } func (s *RepoTestSuite) TestDeleteRepositoryErrUnauthorized() { - err := s.Runner.DeleteRepository(context.Background(), "dummy-repo-id") + err := s.Runner.DeleteRepository(context.Background(), "dummy-repo-id", true) s.Require().Equal(runnerErrors.ErrUnauthorized, err) } @@ -278,7 +278,7 @@ func (s *RepoTestSuite) TestDeleteRepositoryPoolDefinedFailed() { s.FailNow(fmt.Sprintf("cannot create store repositories pool: %v", err)) } - err = s.Runner.DeleteRepository(s.Fixtures.AdminContext, s.Fixtures.StoreRepos["test-repo-1"].ID) + err = s.Runner.DeleteRepository(s.Fixtures.AdminContext, s.Fixtures.StoreRepos["test-repo-1"].ID, true) s.Require().Equal(runnerErrors.NewBadRequestError("repo has pools defined (%s)", pool.ID), err) } @@ -286,7 +286,7 @@ func (s *RepoTestSuite) TestDeleteRepositoryPoolDefinedFailed() { func (s *RepoTestSuite) TestDeleteRepositoryPoolMgrFailed() { s.Fixtures.PoolMgrCtrlMock.On("DeleteRepoPoolManager", mock.AnythingOfType("params.Repository")).Return(s.Fixtures.ErrMock) - err := s.Runner.DeleteRepository(s.Fixtures.AdminContext, s.Fixtures.StoreRepos["test-repo-1"].ID) + err := s.Runner.DeleteRepository(s.Fixtures.AdminContext, s.Fixtures.StoreRepos["test-repo-1"].ID, true) s.Fixtures.PoolMgrCtrlMock.AssertExpectations(s.T()) s.Require().Equal(fmt.Sprintf("deleting repo pool manager: %s", s.Fixtures.ErrMock.Error()), err.Error()) diff --git a/runner/runner.go b/runner/runner.go index 9909ad58..76563c6d 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -311,12 +311,18 @@ func (p *poolManagerCtrl) getInternalConfig(credsName string) (params.Internal, return params.Internal{}, fmt.Errorf("fetching CA bundle for creds: %w", err) } + var controllerWebhookURL string + if p.config.Default.WebhookURL != "" { + controllerWebhookURL = fmt.Sprintf("%s/%s", p.config.Default.WebhookURL, p.controllerID) + } return params.Internal{ - OAuth2Token: creds.OAuth2Token, - ControllerID: p.controllerID, - InstanceCallbackURL: p.config.Default.CallbackURL, - InstanceMetadataURL: p.config.Default.MetadataURL, - JWTSecret: p.config.JWTAuth.Secret, + OAuth2Token: creds.OAuth2Token, + ControllerID: p.controllerID, + InstanceCallbackURL: p.config.Default.CallbackURL, + InstanceMetadataURL: p.config.Default.MetadataURL, + BaseWebhookURL: p.config.Default.WebhookURL, + ControllerWebhookURL: controllerWebhookURL, + JWTSecret: p.config.JWTAuth.Secret, GithubCredentialsDetails: params.GithubCredentials{ Name: creds.Name, Description: creds.Description, @@ -376,11 +382,17 @@ func (r *Runner) GetControllerInfo(ctx context.Context) (params.ControllerInfo, return params.ControllerInfo{}, errors.Wrap(err, "fetching hostname") } r.controllerInfo.Hostname = hostname + var controllerWebhook string + if r.controllerID != uuid.Nil && r.config.Default.WebhookURL != "" { + controllerWebhook = fmt.Sprintf("%s/%s", r.config.Default.WebhookURL, r.controllerID.String()) + } return params.ControllerInfo{ - ControllerID: r.controllerID, - Hostname: hostname, - MetadataURL: r.config.Default.MetadataURL, - CallbackURL: r.config.Default.CallbackURL, + ControllerID: r.controllerID, + Hostname: hostname, + MetadataURL: r.config.Default.MetadataURL, + CallbackURL: r.config.Default.CallbackURL, + WebhookURL: r.config.Default.WebhookURL, + ControllerWebhookURL: controllerWebhook, }, nil } diff --git a/testdata/config.toml b/testdata/config.toml index 24efc5b9..55e69694 100644 --- a/testdata/config.toml +++ b/testdata/config.toml @@ -17,6 +17,24 @@ callback_url = "https://garm.example.com/api/v1/callbacks" # highly encouraged. metadata_url = "https://garm.example.com/api/v1/metadata" +# This is the base URL where GARM will listen for webhook events from github. This +# URL can be directly configured in github to send events to. +# If GARM is allowed to manage webhooks, this URL will be used as a base to optionally +# create webhooks for repositories and organizations. To avoid clashes, the unique +# controller ID that gets generated when GARM is first installed, will be added as a suffix +# to this URL. +# +# For example, assuming that your GARM controller ID is "18225ce4-e3bd-43f0-9c85-7d7858bcc5b2" +# the webhook URL will be "https://garm.example.com/webhooks/18225ce4-e3bd-43f0-9c85-7d7858bcc5b2" +webhook_url = "https://garm.example.com/webhooks" + +# This option enables GARM to manage webhooks for repositories and organizations. Set this +# to false to disable the API routes that manage webhooks. +# +# When managing webhooks, the PAT you're using must have the necessary access to create/list/delete +# webhooks for repositories or organizations. +enable_webhook_management = true + # Uncomment this line if you'd like to log to a file instead of standard output. # log_file = "/tmp/runner-manager.log" diff --git a/util/util.go b/util/util.go index db2b86f0..50d1142d 100644 --- a/util/util.go +++ b/util/util.go @@ -29,6 +29,52 @@ import ( "golang.org/x/oauth2" ) +type githubClient struct { + *github.ActionsService + org *github.OrganizationsService + repo *github.RepositoriesService +} + +func (g *githubClient) ListOrgHooks(ctx context.Context, org string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) { + return g.org.ListHooks(ctx, org, opts) +} + +func (g *githubClient) GetOrgHook(ctx context.Context, org string, id int64) (*github.Hook, *github.Response, error) { + return g.org.GetHook(ctx, org, id) +} + +func (g *githubClient) CreateOrgHook(ctx context.Context, org string, hook *github.Hook) (*github.Hook, *github.Response, error) { + return g.org.CreateHook(ctx, org, hook) +} + +func (g *githubClient) DeleteOrgHook(ctx context.Context, org string, id int64) (*github.Response, error) { + return g.org.DeleteHook(ctx, org, id) +} + +func (g *githubClient) PingOrgHook(ctx context.Context, org string, id int64) (*github.Response, error) { + return g.org.PingHook(ctx, org, id) +} + +func (g *githubClient) ListRepoHooks(ctx context.Context, owner, repo string, opts *github.ListOptions) ([]*github.Hook, *github.Response, error) { + return g.repo.ListHooks(ctx, owner, repo, opts) +} + +func (g *githubClient) GetRepoHook(ctx context.Context, owner, repo string, id int64) (*github.Hook, *github.Response, error) { + return g.repo.GetHook(ctx, owner, repo, id) +} + +func (g *githubClient) CreateRepoHook(ctx context.Context, owner, repo string, hook *github.Hook) (*github.Hook, *github.Response, error) { + return g.repo.CreateHook(ctx, owner, repo, hook) +} + +func (g *githubClient) DeleteRepoHook(ctx context.Context, owner, repo string, id int64) (*github.Response, error) { + return g.repo.DeleteHook(ctx, owner, repo, id) +} + +func (g *githubClient) PingRepoHook(ctx context.Context, owner, repo string, id int64) (*github.Response, error) { + return g.repo.PingHook(ctx, owner, repo, id) +} + func GithubClient(ctx context.Context, token string, credsDetails params.GithubCredentials) (common.GithubClient, common.GithubEnterpriseClient, error) { var roots *x509.CertPool if credsDetails.CABundle != nil && len(credsDetails.CABundle) > 0 { @@ -56,5 +102,10 @@ func GithubClient(ctx context.Context, token string, credsDetails params.GithubC return nil, nil, errors.Wrap(err, "fetching github client") } - return ghClient.Actions, ghClient.Enterprise, nil + cli := &githubClient{ + ActionsService: ghClient.Actions, + org: ghClient.Organizations, + repo: ghClient.Repositories, + } + return cli, ghClient.Enterprise, nil } diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml index 439d3e1d..a618ec24 100644 --- a/vendor/github.com/spf13/cobra/.golangci.yml +++ b/vendor/github.com/spf13/cobra/.golangci.yml @@ -1,4 +1,4 @@ -# Copyright 2013-2022 The Cobra Authors +# Copyright 2013-2023 The Cobra Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ linters: disable-all: true enable: #- bodyclose - - deadcode + # - deadcode ! deprecated since v1.49.0; replaced by 'unused' #- depguard #- dogsled #- dupl @@ -51,12 +51,12 @@ linters: #- rowserrcheck #- scopelint #- staticcheck - - structcheck + #- structcheck ! deprecated since v1.49.0; replaced by 'unused' #- stylecheck #- typecheck - unconvert #- unparam - #- unused - - varcheck + - unused + # - varcheck ! deprecated since v1.49.0; replaced by 'unused' #- whitespace fast: false diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile index c433a01b..0da8d7aa 100644 --- a/vendor/github.com/spf13/cobra/Makefile +++ b/vendor/github.com/spf13/cobra/Makefile @@ -5,10 +5,6 @@ ifeq (, $(shell which golangci-lint)) $(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh") endif -ifeq (, $(shell which richgo)) -$(warning "could not find richgo in $(PATH), run: go install github.com/kyoh86/richgo@latest") -endif - .PHONY: fmt lint test install_deps clean default: all @@ -25,6 +21,10 @@ lint: test: install_deps $(info ******************** running tests ********************) + go test -v ./... + +richtest: install_deps + $(info ******************** running tests with kyoh86/richgo ********************) richgo test -v ./... install_deps: diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index 7cc726be..6444f4b7 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -1,12 +1,12 @@ -![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) +![cobra logo](assets/CobraMain.png) Cobra is a library for creating powerful modern CLI applications. Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), [Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to -name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. +name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra. -[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) +[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) [![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) [![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) [![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) @@ -80,7 +80,7 @@ which maintains the same interface while adding POSIX compliance. # Installing Using Cobra is easy. First, use `go get` to install the latest version -of the library. +of the library. ``` go get -u github.com/spf13/cobra@latest @@ -105,8 +105,8 @@ go install github.com/spf13/cobra-cli@latest For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) -For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md). +For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md). # License -Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) +Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt) diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go index 95e03aec..2d023943 100644 --- a/vendor/github.com/spf13/cobra/active_help.go +++ b/vendor/github.com/spf13/cobra/active_help.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/vendor/github.com/spf13/cobra/active_help.md b/vendor/github.com/spf13/cobra/active_help.md deleted file mode 100644 index 5e7f59af..00000000 --- a/vendor/github.com/spf13/cobra/active_help.md +++ /dev/null @@ -1,157 +0,0 @@ -# Active Help - -Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion. - -For example, -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding. - -bash-5.1$ bin/helm package [tab] -Please specify the path to the chart to package - -bash-5.1$ bin/helm package [tab][tab] -bin/ internal/ scripts/ pkg/ testdata/ -``` - -**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program. -## Supported shells - -Active Help is currently only supported for the following shells: -- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed. -- Zsh - -## Adding Active Help messages - -As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md). - -Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details. - -### Active Help for nouns - -Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example: - -```go -cmd := &cobra.Command{ - Use: "add [NAME] [URL]", - Short: "add a chart repository", - Args: require.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - return addRepo(args) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - var comps []string - if len(args) == 0 { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } else if len(args) == 1 { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } else { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - return comps, cobra.ShellCompDirectiveNoFileComp - }, -} -``` -The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior: -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding - -bash-5.1$ helm repo add grafana [tab] -You must specify the URL for the repo you are adding - -bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab] -This command does not take any more arguments -``` -**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions. - -### Active Help for flags - -Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example: -```go -_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 2 { - return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp - } - return compVersionFlag(args[1], toComplete) - }) -``` -The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag. -``` -bash-5.1$ bin/helm install myrelease --version 2.0.[tab] -You must first specify the chart to install before the --version flag can be completed - -bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab] -2.0.1 2.0.2 2.0.3 -``` - -## User control of Active Help - -You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any. -Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration. - -The way to configure Active Help is to use the program's Active Help environment -variable. That variable is named `_ACTIVE_HELP` where `` is the name of your -program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever -Active Help configuration values are supported by the program. - -For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user -would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell. - -For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the -Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages -should or should not be added (instead of reading the environment variable directly). - -For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - activeHelpLevel := cobra.GetActiveHelpConfig(cmd) - - var comps []string - if len(args) == 0 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } - } else if len(args) == 1 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } - } else { - if activeHelpLevel == "local" { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - } - return comps, cobra.ShellCompDirectiveNoFileComp -}, -``` -**Note 1**: If the `_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly. - -**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `_ACTIVE_HELP` is set to. - -**Note 3**: If the user does not set `_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. -## Active Help with Cobra's default completion command - -Cobra provides a default `completion` command for programs that wish to use it. -When using the default `completion` command, Active Help is configurable in the same -fashion as described above using environment variables. You may wish to document this in more -details for your users. - -## Debugging Active Help - -Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details. - -When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below: -``` -$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -_activeHelp_ WARNING: cannot re-use a name that is still in use -:0 -Completion ended with directive: ShellCompDirectiveDefault - -$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -:0 -Completion ended with directive: ShellCompDirectiveDefault -``` diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go index 2c1f99e7..e79ec33a 100644 --- a/vendor/github.com/spf13/cobra/args.go +++ b/vendor/github.com/spf13/cobra/args.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ( type PositionalArgs func(cmd *Command, args []string) error -// Legacy arg validation has the following behaviour: +// legacyArgs validation has the following behaviour: // - root commands with no subcommands can take arbitrary arguments // - root commands with subcommands will do subcommand validity checking // - subcommands will always accept arbitrary arguments diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 3acdb279..8a531518 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -85,7 +85,7 @@ __%[1]s_handle_go_custom_completion() local out requestComp lastParam lastChar comp directive args # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + # Calling ${words[0]} instead of directly %[1]s allows handling aliases args=("${words[@]:1}") # Disable ActiveHelp which is not supported for bash completion v1 requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}" @@ -532,7 +532,7 @@ func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { } } -// Setup annotations for go completions for registered flags +// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags func prepareCustomAnnotationsForFlags(cmd *Command) { flagCompletionMutex.RLock() defer flagCompletionMutex.RUnlock() diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md deleted file mode 100644 index 52919b2f..00000000 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ /dev/null @@ -1,93 +0,0 @@ -# Generating Bash Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution. - -**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own. - -The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions. - -Some code that works in kubernetes: - -```bash -const ( - bash_completion_func = `__kubectl_parse_get() -{ - local kubectl_output out - if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then - out=($(echo "${kubectl_output}" | awk '{print $1}')) - COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) ) - fi -} - -__kubectl_get_resource() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - return 1 - fi - __kubectl_parse_get ${nouns[${#nouns[@]} -1]} - if [[ $? -eq 0 ]]; then - return 0 - fi -} - -__kubectl_custom_func() { - case ${last_command} in - kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop) - __kubectl_get_resource - return - ;; - *) - ;; - esac -} -`) -``` - -And then I set that in my command definition: - -```go -cmds := &cobra.Command{ - Use: "kubectl", - Short: "kubectl controls the Kubernetes cluster manager", - Long: `kubectl controls the Kubernetes cluster manager. - -Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, - Run: runHelp, - BashCompletionFunction: bash_completion_func, -} -``` - -The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods! - -Similarly, for flags: - -```go - annotation := make(map[string][]string) - annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"} - - flag := &pflag.Flag{ - Name: "namespace", - Usage: usage, - Annotations: annotation, - } - cmd.Flags().AddFlag(flag) -``` - -In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction` -value, e.g.: - -```bash -__kubectl_get_namespaces() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) - fi -} -``` diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go index bb4b7189..1cce5c32 100644 --- a/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ b/vendor/github.com/spf13/cobra/bash_completionsV2.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ func genBashComp(buf io.StringWriter, name string, includeDesc bool) { __%[1]s_debug() { - if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then + if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then echo "$*" >> "${BASH_COMP_DEBUG_FILE}" fi } @@ -57,7 +57,7 @@ __%[1]s_get_completion_results() { local requestComp lastParam lastChar args # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + # Calling ${words[0]} instead of directly %[1]s allows handling aliases args=("${words[@]:1}") requestComp="${words[0]} %[2]s ${args[*]}" @@ -65,7 +65,7 @@ __%[1]s_get_completion_results() { lastChar=${lastParam:$((${#lastParam}-1)):1} __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + if [[ -z ${cur} && ${lastChar} != = ]]; then # If the last parameter is complete (there is a space following it) # We add an extra empty parameter so we can indicate this to the go method. __%[1]s_debug "Adding extra empty parameter" @@ -75,7 +75,7 @@ __%[1]s_get_completion_results() { # When completing a flag with an = (e.g., %[1]s -n=) # bash focuses on the part after the =, so we need to remove # the flag part from $cur - if [[ "${cur}" == -*=* ]]; then + if [[ ${cur} == -*=* ]]; then cur="${cur#*=}" fi @@ -87,7 +87,7 @@ __%[1]s_get_completion_results() { directive=${out##*:} # Remove the directive out=${out%%:*} - if [ "${directive}" = "${out}" ]; then + if [[ ${directive} == "${out}" ]]; then # There is not directive specified directive=0 fi @@ -101,22 +101,36 @@ __%[1]s_process_completion_results() { local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + if (((directive & shellCompDirectiveError) != 0)); then # Error code. No completion. __%[1]s_debug "Received error from custom completion go code" return else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then + if (((directive & shellCompDirectiveNoSpace) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then __%[1]s_debug "Activating no space" compopt -o nospace else __%[1]s_debug "No space directive not supported in this version of bash" fi fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then + if (((directive & shellCompDirectiveKeepOrder) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + # no sort isn't supported for bash less than < 4.4 + if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then + __%[1]s_debug "No sort directive not supported in this version of bash" + else + __%[1]s_debug "Activating keep order" + compopt -o nosort + fi + else + __%[1]s_debug "No sort directive not supported in this version of bash" + fi + fi + if (((directive & shellCompDirectiveNoFileComp) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then __%[1]s_debug "Activating no file completion" compopt +o default else @@ -130,7 +144,7 @@ __%[1]s_process_completion_results() { local activeHelp=() __%[1]s_extract_activeHelp - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + if (((directive & shellCompDirectiveFilterFileExt) != 0)); then # File extension filtering local fullFilter filter filteringCmd @@ -143,13 +157,12 @@ __%[1]s_process_completion_results() { filteringCmd="_filedir $fullFilter" __%[1]s_debug "File filtering command: $filteringCmd" $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + elif (((directive & shellCompDirectiveFilterDirs) != 0)); then # File completion for directories only - # Use printf to strip any trailing newline local subdir - subdir=$(printf "%%s" "${completions[0]}") - if [ -n "$subdir" ]; then + subdir=${completions[0]} + if [[ -n $subdir ]]; then __%[1]s_debug "Listing directories in $subdir" pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return else @@ -164,7 +177,7 @@ __%[1]s_process_completion_results() { __%[1]s_handle_special_char "$cur" = # Print the activeHelp statements before we finish - if [ ${#activeHelp[*]} -ne 0 ]; then + if ((${#activeHelp[*]} != 0)); then printf "\n"; printf "%%s\n" "${activeHelp[@]}" printf "\n" @@ -184,21 +197,21 @@ __%[1]s_process_completion_results() { # Separate activeHelp lines from real completions. # Fills the $activeHelp and $completions arrays. __%[1]s_extract_activeHelp() { - local activeHelpMarker="%[8]s" + local activeHelpMarker="%[9]s" local endIndex=${#activeHelpMarker} while IFS='' read -r comp; do - if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then + if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then comp=${comp:endIndex} __%[1]s_debug "ActiveHelp found: $comp" - if [ -n "$comp" ]; then + if [[ -n $comp ]]; then activeHelp+=("$comp") fi else # Not an activeHelp line but a normal completion completions+=("$comp") fi - done < <(printf "%%s\n" "${out}") + done <<<"${out}" } __%[1]s_handle_completion_types() { @@ -254,7 +267,7 @@ __%[1]s_handle_standard_completion_case() { done < <(printf "%%s\n" "${completions[@]}") # If there is a single completion left, remove the description text - if [ ${#COMPREPLY[*]} -eq 1 ]; then + if ((${#COMPREPLY[*]} == 1)); then __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" comp="${COMPREPLY[0]%%%%$tab*}" __%[1]s_debug "Removed description from single completion, which is now: ${comp}" @@ -271,8 +284,8 @@ __%[1]s_handle_special_char() if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then local word=${comp%%"${comp##*${char}}"} local idx=${#COMPREPLY[*]} - while [[ $((--idx)) -ge 0 ]]; do - COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} + while ((--idx >= 0)); do + COMPREPLY[idx]=${COMPREPLY[idx]#"$word"} done fi } @@ -298,7 +311,7 @@ __%[1]s_format_comp_descriptions() # Make sure we can fit a description of at least 8 characters # if we are to align the descriptions. - if [[ $maxdesclength -gt 8 ]]; then + if ((maxdesclength > 8)); then # Add the proper number of spaces to align the descriptions for ((i = ${#comp} ; i < longest ; i++)); do comp+=" " @@ -310,8 +323,8 @@ __%[1]s_format_comp_descriptions() # If there is enough space for any description text, # truncate the descriptions that are too long for the shell width - if [ $maxdesclength -gt 0 ]; then - if [ ${#desc} -gt $maxdesclength ]; then + if ((maxdesclength > 0)); then + if ((${#desc} > maxdesclength)); then desc=${desc:0:$(( maxdesclength - 1 ))} desc+="…" fi @@ -332,9 +345,9 @@ __start_%[1]s() # Call _init_completion from the bash-completion package # to prepare the arguments properly if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -n "=:" || return + _init_completion -n =: || return else - __%[1]s_init_completion -n "=:" || return + __%[1]s_init_completion -n =: || return fi __%[1]s_debug @@ -361,7 +374,7 @@ fi # ex: ts=4 sw=4 et filetype=sh `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpMarker)) } diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index fe44bc8a..f23f5092 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ const ( defaultCaseInsensitive = false ) -// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing +// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing // to automatically enable in CLI tools. // Set this to true to enable it. var EnablePrefixMatching = defaultPrefixMatching @@ -167,8 +167,8 @@ func appendIfNotPresent(s, stringToAppend string) string { // rpad adds padding to the right of a string. func rpad(s string, padding int) string { - template := fmt.Sprintf("%%-%ds", padding) - return fmt.Sprintf(template, s) + formattedString := fmt.Sprintf("%%-%ds", padding) + return fmt.Sprintf(formattedString, s) } // tmpl executes the given template text on data, writing the result to w. diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index 6ff47dd5..01f7c6f1 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" // FParseErrWhitelist configures Flag parse errors to be ignored type FParseErrWhitelist flag.ParseErrorsWhitelist -// Structure to manage groups for commands +// Group Structure to manage groups for commands type Group struct { ID string Title string @@ -47,7 +47,7 @@ type Group struct { // definition to ensure usability. type Command struct { // Use is the one-line usage message. - // Recommended syntax is as follow: + // Recommended syntax is as follows: // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. // ... indicates that you can specify multiple values for the previous argument. // | indicates mutually exclusive information. You can use the argument to the left of the separator or the @@ -321,7 +321,7 @@ func (c *Command) SetHelpCommand(cmd *Command) { c.helpCommand = cmd } -// SetHelpCommandGroup sets the group id of the help command. +// SetHelpCommandGroupID sets the group id of the help command. func (c *Command) SetHelpCommandGroupID(groupID string) { if c.helpCommand != nil { c.helpCommand.GroupID = groupID @@ -330,7 +330,7 @@ func (c *Command) SetHelpCommandGroupID(groupID string) { c.helpCommandGroupID = groupID } -// SetCompletionCommandGroup sets the group id of the completion command. +// SetCompletionCommandGroupID sets the group id of the completion command. func (c *Command) SetCompletionCommandGroupID(groupID string) { // completionCommandGroupID is used if no completion command is defined by the user c.Root().completionCommandGroupID = groupID @@ -655,20 +655,44 @@ Loop: // argsMinusFirstX removes only the first x from args. Otherwise, commands that look like // openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). -func argsMinusFirstX(args []string, x string) []string { - for i, y := range args { - if x == y { - ret := []string{} - ret = append(ret, args[:i]...) - ret = append(ret, args[i+1:]...) - return ret +// Special care needs to be taken not to remove a flag value. +func (c *Command) argsMinusFirstX(args []string, x string) []string { + if len(args) == 0 { + return args + } + c.mergePersistentFlags() + flags := c.Flags() + +Loop: + for pos := 0; pos < len(args); pos++ { + s := args[pos] + switch { + case s == "--": + // -- means we have reached the end of the parseable args. Break out of the loop now. + break Loop + case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): + fallthrough + case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): + // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip + // over the next arg, because that is the value of this flag. + pos++ + continue + case !strings.HasPrefix(s, "-"): + // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so, + // return the args, excluding the one at this position. + if s == x { + ret := []string{} + ret = append(ret, args[:pos]...) + ret = append(ret, args[pos+1:]...) + return ret + } } } return args } func isFlagArg(arg string) bool { - return ((len(arg) >= 3 && arg[1] == '-') || + return ((len(arg) >= 3 && arg[0:2] == "--") || (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) } @@ -686,7 +710,7 @@ func (c *Command) Find(args []string) (*Command, []string, error) { cmd := c.findNext(nextSubCmd) if cmd != nil { - return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) + return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd)) } return c, innerArgs } @@ -1272,7 +1296,7 @@ func (c *Command) AllChildCommandsHaveGroup() bool { return true } -// ContainGroups return if groupID exists in the list of command groups. +// ContainsGroup return if groupID exists in the list of command groups. func (c *Command) ContainsGroup(groupID string) bool { for _, x := range c.commandgroups { if x.ID == groupID { diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go index 2b77f8f0..307f0c12 100644 --- a/vendor/github.com/spf13/cobra/command_notwin.go +++ b/vendor/github.com/spf13/cobra/command_notwin.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go index 520f23ab..adbef395 100644 --- a/vendor/github.com/spf13/cobra/command_win.go +++ b/vendor/github.com/spf13/cobra/command_win.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go index e8a0206d..ee38c4d0 100644 --- a/vendor/github.com/spf13/cobra/completions.go +++ b/vendor/github.com/spf13/cobra/completions.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -77,6 +77,10 @@ const ( // obtain the same behavior but only for flags. ShellCompDirectiveFilterDirs + // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order + // in which the completions are provided + ShellCompDirectiveKeepOrder + // =========================================================================== // All directives using iota should be above this one. @@ -159,6 +163,9 @@ func (d ShellCompDirective) string() string { if d&ShellCompDirectiveFilterDirs != 0 { directives = append(directives, "ShellCompDirectiveFilterDirs") } + if d&ShellCompDirectiveKeepOrder != 0 { + directives = append(directives, "ShellCompDirectiveKeepOrder") + } if len(directives) == 0 { directives = append(directives, "ShellCompDirectiveDefault") } @@ -169,7 +176,7 @@ func (d ShellCompDirective) string() string { return strings.Join(directives, ", ") } -// Adds a special hidden command that can be used to request custom completions. +// initCompleteCmd adds a special hidden command that can be used to request custom completions. func (c *Command) initCompleteCmd(args []string) { completeCmd := &Command{ Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), @@ -727,7 +734,7 @@ to enable it. You can execute the following once: To load completions in your current shell session: - source <(%[1]s completion zsh); compdef _%[1]s %[1]s + source <(%[1]s completion zsh) To load completions for every new session, execute once: diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go index 97112a17..12d61b69 100644 --- a/vendor/github.com/spf13/cobra/fish_completions.go +++ b/vendor/github.com/spf13/cobra/fish_completions.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ function __%[1]s_perform_completion __%[1]s_debug "last arg: $lastArg" # Disable ActiveHelp which is not supported for fish shell - set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg" + set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg" __%[1]s_debug "Calling $requestComp" set -l results (eval $requestComp 2> /dev/null) @@ -89,6 +89,60 @@ function __%[1]s_perform_completion printf "%%s\n" "$directiveLine" end +# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result +function __%[1]s_perform_completion_once + __%[1]s_debug "Starting __%[1]s_perform_completion_once" + + if test -n "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion" + return 0 + end + + set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion) + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "No completions, probably due to a failure" + return 1 + end + + __%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result" + return 0 +end + +# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run +function __%[1]s_clear_perform_completion_once_result + __%[1]s_debug "" + __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable ==========" + set --erase __%[1]s_perform_completion_once_result + __%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result" +end + +function __%[1]s_requires_order_preservation + __%[1]s_debug "" + __%[1]s_debug "========= checking if order preservation is required ==========" + + __%[1]s_perform_completion_once + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Error determining if order preservation is required" + return 1 + end + + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + __%[1]s_debug "Directive is: $directive" + + set -l shellCompDirectiveKeepOrder %[9]d + set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2) + __%[1]s_debug "Keeporder is: $keeporder" + + if test $keeporder -ne 0 + __%[1]s_debug "This does require order preservation" + return 0 + end + + __%[1]s_debug "This doesn't require order preservation" + return 1 +end + + # This function does two things: # - Obtain the completions and store them in the global __%[1]s_comp_results # - Return false if file completion should be performed @@ -99,17 +153,17 @@ function __%[1]s_prepare_completions # Start fresh set --erase __%[1]s_comp_results - set -l results (__%[1]s_perform_completion) - __%[1]s_debug "Completion results: $results" + __%[1]s_perform_completion_once + __%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result" - if test -z "$results" + if test -z "$__%[1]s_perform_completion_once_result" __%[1]s_debug "No completion, probably due to a failure" # Might as well do file completion, in case it helps return 1 end - set -l directive (string sub --start 2 $results[-1]) - set --global __%[1]s_comp_results $results[1..-2] + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2] __%[1]s_debug "Completions are: $__%[1]s_comp_results" __%[1]s_debug "Directive is: $directive" @@ -205,13 +259,17 @@ end # Remove any pre-existing completions for the program since we will be handling all of them. complete -c %[2]s -e +# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global +complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result' # The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results # which provides the program's completion choices. -complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' - +# If this doesn't require order preservation, we don't use the -k flag +complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' +# otherwise we use the -k flag +complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' `, nameForVar, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) } // GenFishCompletion generates fish completion file and writes to the passed writer. diff --git a/vendor/github.com/spf13/cobra/fish_completions.md b/vendor/github.com/spf13/cobra/fish_completions.md deleted file mode 100644 index 19b2ed12..00000000 --- a/vendor/github.com/spf13/cobra/fish_completions.md +++ /dev/null @@ -1,4 +0,0 @@ -## Generating Fish Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - diff --git a/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go index 9c377aaf..0671ec5f 100644 --- a/vendor/github.com/spf13/cobra/flag_groups.go +++ b/vendor/github.com/spf13/cobra/flag_groups.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import ( const ( requiredAsGroup = "cobra_annotation_required_if_others_set" + oneRequired = "cobra_annotation_one_required" mutuallyExclusive = "cobra_annotation_mutually_exclusive" ) @@ -43,6 +44,22 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) { } } +// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors +// if the command is invoked without at least one flag from the given set of flags. +func (c *Command) MarkFlagsOneRequired(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v)) + } + if err := c.Flags().SetAnnotation(v, oneRequired, append(f.Annotations[oneRequired], strings.Join(flagNames, " "))); err != nil { + // Only errs if the flag isn't found. + panic(err) + } + } +} + // MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors // if the command is invoked with more than one flag from the given set of flags. func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { @@ -59,7 +76,7 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { } } -// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the +// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the // first error encountered. func (c *Command) ValidateFlagGroups() error { if c.DisableFlagParsing { @@ -71,15 +88,20 @@ func (c *Command) ValidateFlagGroups() error { // groupStatus format is the list of flags as a unique ID, // then a map of each flag name and whether it is set or not. groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} flags.VisitAll(func(pflag *flag.Flag) { processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus) processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) }) if err := validateRequiredFlagGroups(groupStatus); err != nil { return err } + if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil { + return err + } if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { return err } @@ -142,6 +164,27 @@ func validateRequiredFlagGroups(data map[string]map[string]bool) error { return nil } +func validateOneRequiredFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + var set []string + for flagname, isSet := range flagnameAndStatus { + if isSet { + set = append(set, flagname) + } + } + if len(set) >= 1 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(set) + return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList) + } + return nil +} + func validateExclusiveFlagGroups(data map[string]map[string]bool) error { keys := sortedKeys(data) for _, flagList := range keys { @@ -176,6 +219,7 @@ func sortedKeys(m map[string]map[string]bool) []string { // enforceFlagGroupsForCompletion will do the following: // - when a flag in a group is present, other flags in the group will be marked required +// - when none of the flags in a one-required group are present, all flags in the group will be marked required // - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden // This allows the standard completion logic to behave appropriately for flag groups func (c *Command) enforceFlagGroupsForCompletion() { @@ -185,9 +229,11 @@ func (c *Command) enforceFlagGroupsForCompletion() { flags := c.Flags() groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} c.Flags().VisitAll(func(pflag *flag.Flag) { processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus) processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) }) @@ -204,6 +250,26 @@ func (c *Command) enforceFlagGroupsForCompletion() { } } + // If none of the flags of a one-required group are present, we make all the flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range oneRequiredGroupStatus { + set := 0 + + for _, isSet := range flagnameAndStatus { + if isSet { + set++ + } + } + + // None of the flags of the group are set, mark all flags in the group + // as required + if set == 0 { + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + // If a flag that is mutually exclusive to others is present, we hide the other // flags of that group so the shell completion does not suggest them for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go index 004de42e..55195193 100644 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ b/vendor/github.com/spf13/cobra/powershell_completions.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars { `+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` } -[scriptblock]$__%[2]sCompleterBlock = { +[scriptblock]${__%[2]sCompleterBlock} = { param( $WordToComplete, $CommandAst, @@ -77,6 +77,7 @@ filter __%[1]s_escapeStringWithSpecialChars { $ShellCompDirectiveNoFileComp=%[6]d $ShellCompDirectiveFilterFileExt=%[7]d $ShellCompDirectiveFilterDirs=%[8]d + $ShellCompDirectiveKeepOrder=%[9]d # Prepare the command to request completions for the program. # Split the command at the first space to separate the program and arguments. @@ -106,13 +107,22 @@ filter __%[1]s_escapeStringWithSpecialChars { # If the last parameter is complete (there is a space following it) # We add an extra empty parameter so we can indicate this to the go method. __%[1]s_debug "Adding extra empty parameter" -`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+` -`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` + # PowerShell 7.2+ changed the way how the arguments are passed to executables, + # so for pre-7.2 or when Legacy argument passing is enabled we need to use +`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+` + if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or + ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or + (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and + $PSNativeCommandArgumentPassing -eq 'Legacy')) { +`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` + } else { + $RequestComp="$RequestComp" + ' ""' + } } __%[1]s_debug "Calling $RequestComp" # First disable ActiveHelp which is not supported for Powershell - $env:%[9]s=0 + ${env:%[10]s}=0 #call the command store the output in $out and redirect stderr and stdout to null # $Out is an array contains each line per element @@ -137,7 +147,7 @@ filter __%[1]s_escapeStringWithSpecialChars { } $Longest = 0 - $Values = $Out | ForEach-Object { + [Array]$Values = $Out | ForEach-Object { #Split the output in name and description `+" $Name, $Description = $_.Split(\"`t\",2)"+` __%[1]s_debug "Name: $Name Description: $Description" @@ -182,6 +192,11 @@ filter __%[1]s_escapeStringWithSpecialChars { } } + # we sort the values in ascending order by name if keep order isn't passed + if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) { + $Values = $Values | Sort-Object -Property Name + } + if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { __%[1]s_debug "ShellCompDirectiveNoFileComp is called" @@ -264,10 +279,10 @@ filter __%[1]s_escapeStringWithSpecialChars { } } -Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock +Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock} `, name, nameForVar, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) } func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { diff --git a/vendor/github.com/spf13/cobra/powershell_completions.md b/vendor/github.com/spf13/cobra/powershell_completions.md deleted file mode 100644 index c449f1e5..00000000 --- a/vendor/github.com/spf13/cobra/powershell_completions.md +++ /dev/null @@ -1,3 +0,0 @@ -# Generating PowerShell Completions For Your Own cobra.Command - -Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details. diff --git a/vendor/github.com/spf13/cobra/projects_using_cobra.md b/vendor/github.com/spf13/cobra/projects_using_cobra.md deleted file mode 100644 index 6865f88e..00000000 --- a/vendor/github.com/spf13/cobra/projects_using_cobra.md +++ /dev/null @@ -1,60 +0,0 @@ -## Projects using Cobra - -- [Allero](https://github.com/allero-io/allero) -- [Arduino CLI](https://github.com/arduino/arduino-cli) -- [Bleve](https://blevesearch.com/) -- [Cilium](https://cilium.io/) -- [CloudQuery](https://github.com/cloudquery/cloudquery) -- [CockroachDB](https://www.cockroachlabs.com/) -- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) -- [Datree](https://github.com/datreeio/datree) -- [Delve](https://github.com/derekparker/delve) -- [Docker (distribution)](https://github.com/docker/distribution) -- [Etcd](https://etcd.io/) -- [Gardener](https://github.com/gardener/gardenctl) -- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) -- [Git Bump](https://github.com/erdaltsksn/git-bump) -- [GitHub CLI](https://github.com/cli/cli) -- [GitHub Labeler](https://github.com/erdaltsksn/gh-label) -- [Golangci-lint](https://golangci-lint.run) -- [GopherJS](https://github.com/gopherjs/gopherjs) -- [GoReleaser](https://goreleaser.com) -- [Helm](https://helm.sh) -- [Hugo](https://gohugo.io) -- [Infracost](https://github.com/infracost/infracost) -- [Istio](https://istio.io) -- [Kool](https://github.com/kool-dev/kool) -- [Kubernetes](https://kubernetes.io/) -- [Kubescape](https://github.com/armosec/kubescape) -- [KubeVirt](https://github.com/kubevirt/kubevirt) -- [Linkerd](https://linkerd.io/) -- [Mattermost-server](https://github.com/mattermost/mattermost-server) -- [Mercure](https://mercure.rocks/) -- [Meroxa CLI](https://github.com/meroxa/cli) -- [Metal Stack CLI](https://github.com/metal-stack/metalctl) -- [Moby (former Docker)](https://github.com/moby/moby) -- [Moldy](https://github.com/Moldy-Community/moldy) -- [Multi-gitter](https://github.com/lindell/multi-gitter) -- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) -- [nFPM](https://nfpm.goreleaser.com) -- [Okteto](https://github.com/okteto/okteto) -- [OpenShift](https://www.openshift.com/) -- [Ory Hydra](https://github.com/ory/hydra) -- [Ory Kratos](https://github.com/ory/kratos) -- [Pixie](https://github.com/pixie-io/pixie) -- [Polygon Edge](https://github.com/0xPolygon/polygon-edge) -- [Pouch](https://github.com/alibaba/pouch) -- [ProjectAtomic (enterprise)](https://www.projectatomic.io/) -- [Prototool](https://github.com/uber/prototool) -- [Pulumi](https://www.pulumi.com) -- [QRcp](https://github.com/claudiodangelis/qrcp) -- [Random](https://github.com/erdaltsksn/random) -- [Rclone](https://rclone.org/) -- [Scaleway CLI](https://github.com/scaleway/scaleway-cli) -- [Skaffold](https://skaffold.dev/) -- [Tendermint](https://github.com/tendermint/tendermint) -- [Twitch CLI](https://github.com/twitchdev/twitch-cli) -- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli) -- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework) -- [Werf](https://werf.io/) -- [ZITADEL](https://github.com/zitadel/zitadel) diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go index 126e83c3..b035742d 100644 --- a/vendor/github.com/spf13/cobra/shell_completions.go +++ b/vendor/github.com/spf13/cobra/shell_completions.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/vendor/github.com/spf13/cobra/shell_completions.md b/vendor/github.com/spf13/cobra/shell_completions.md deleted file mode 100644 index 553ee5df..00000000 --- a/vendor/github.com/spf13/cobra/shell_completions.md +++ /dev/null @@ -1,568 +0,0 @@ -# Generating shell completions - -Cobra can generate shell completions for multiple shells. -The currently supported shells are: -- Bash -- Zsh -- fish -- PowerShell - -Cobra will automatically provide your program with a fully functional `completion` command, -similarly to how it provides the `help` command. - -## Creating your own completion command - -If you do not wish to use the default `completion` command, you can choose to -provide your own, which will take precedence over the default one. (This also provides -backwards-compatibility with programs that already have their own `completion` command.) - -If you are using the `cobra-cli` generator, -which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli), -you can create a completion command by running - -```bash -cobra-cli add completion -``` -and then modifying the generated `cmd/completion.go` file to look something like this -(writing the shell script to stdout allows the most flexible use): - -```go -var completionCmd = &cobra.Command{ - Use: "completion [bash|zsh|fish|powershell]", - Short: "Generate completion script", - Long: fmt.Sprintf(`To load completions: - -Bash: - - $ source <(%[1]s completion bash) - - # To load completions for each session, execute once: - # Linux: - $ %[1]s completion bash > /etc/bash_completion.d/%[1]s - # macOS: - $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s - -Zsh: - - # If shell completion is not already enabled in your environment, - # you will need to enable it. You can execute the following once: - - $ echo "autoload -U compinit; compinit" >> ~/.zshrc - - # To load completions for each session, execute once: - $ %[1]s completion zsh > "${fpath[1]}/_%[1]s" - - # You will need to start a new shell for this setup to take effect. - -fish: - - $ %[1]s completion fish | source - - # To load completions for each session, execute once: - $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish - -PowerShell: - - PS> %[1]s completion powershell | Out-String | Invoke-Expression - - # To load completions for every new session, run: - PS> %[1]s completion powershell > %[1]s.ps1 - # and source this file from your PowerShell profile. -`,cmd.Root().Name()), - DisableFlagsInUseLine: true, - ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, - Args: cobra.ExactValidArgs(1), - Run: func(cmd *cobra.Command, args []string) { - switch args[0] { - case "bash": - cmd.Root().GenBashCompletion(os.Stdout) - case "zsh": - cmd.Root().GenZshCompletion(os.Stdout) - case "fish": - cmd.Root().GenFishCompletion(os.Stdout, true) - case "powershell": - cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) - } - }, -} -``` - -**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed. - -## Adapting the default completion command - -Cobra provides a few options for the default `completion` command. To configure such options you must set -the `CompletionOptions` field on the *root* command. - -To tell Cobra *not* to provide the default `completion` command: -``` -rootCmd.CompletionOptions.DisableDefaultCmd = true -``` - -To tell Cobra to mark the default `completion` command as *hidden*: -``` -rootCmd.CompletionOptions.HiddenDefaultCmd = true -``` - -To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: -``` -rootCmd.CompletionOptions.DisableNoDescFlag = true -``` - -To tell Cobra to completely disable descriptions for completions: -``` -rootCmd.CompletionOptions.DisableDescriptions = true -``` - -# Customizing completions - -The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values. - -## Completion of nouns - -### Static completion of nouns - -Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field. -For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. -Some simplified code from `kubectl get` looks like: - -```go -validArgs = []string{ "pod", "node", "service", "replicationcontroller" } - -cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - cobra.CheckErr(RunGet(f, out, cmd, args)) - }, - ValidArgs: validArgs, -} -``` - -Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like: - -```bash -$ kubectl get [tab][tab] -node pod replicationcontroller service -``` - -#### Aliases for nouns - -If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by -the completion algorithm if entered manually, e.g. in: - -```bash -$ kubectl get rc [tab][tab] -backend frontend database -``` - -Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of -replication controllers following `rc`. - -### Dynamic completion of nouns - -In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both. -Simplified code from `helm status` looks like: - -```go -cmd := &cobra.Command{ - Use: "status RELEASE_NAME", - Short: "Display the status of the named release", - Long: status_long, - RunE: func(cmd *cobra.Command, args []string) { - RunGet(args[0]) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 0 { - return nil, cobra.ShellCompDirectiveNoFileComp - } - return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp - }, -} -``` -Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster. -Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like: - -```bash -$ helm status [tab][tab] -harbor notary rook thanos -``` -You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp` -```go -// Indicates that the shell will perform its default behavior after completions -// have been provided (this implies none of the other directives). -ShellCompDirectiveDefault - -// Indicates an error occurred and completions should be ignored. -ShellCompDirectiveError - -// Indicates that the shell should not add a space after the completion, -// even if there is a single completion provided. -ShellCompDirectiveNoSpace - -// Indicates that the shell should not provide file completion even when -// no completion is provided. -ShellCompDirectiveNoFileComp - -// Indicates that the returned completions should be used as file extension filters. -// For example, to complete only files of the form *.json or *.yaml: -// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt -// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename() -// is a shortcut to using this directive explicitly. -// -ShellCompDirectiveFilterFileExt - -// Indicates that only directory names should be provided in file completion. -// For example: -// return nil, ShellCompDirectiveFilterDirs -// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly. -// -// To request directory names within another directory, the returned completions -// should specify a single directory name within which to search. For example, -// to complete directories within "themes/": -// return []string{"themes"}, ShellCompDirectiveFilterDirs -// -ShellCompDirectiveFilterDirs -``` - -***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. - -#### Debugging - -Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly: -```bash -$ helm __complete status har -harbor -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command: -```bash -$ helm __complete status "" -harbor -notary -rook -thanos -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code: -```go -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and optionally prints to stderr. -cobra.CompDebug(msg string, printToStdErr bool) { -cobra.CompDebugln(msg string, printToStdErr bool) - -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and to stderr. -cobra.CompError(msg string) -cobra.CompErrorln(msg string) -``` -***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above. - -## Completions for flags - -### Mark flags as required - -Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so: - -```go -cmd.MarkFlagRequired("pod") -cmd.MarkFlagRequired("container") -``` - -and you'll get something like - -```bash -$ kubectl exec [tab][tab] --c --container= -p --pod= -``` - -### Specify dynamic flag completion - -As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function. - -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault -}) -``` -Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: - -```bash -$ helm status --output [tab][tab] -json table yaml -``` - -#### Debugging - -You can also easily debug your Go completion code for flags: -```bash -$ helm __complete status --output "" -json -table -yaml -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above. - -### Specify valid filename extensions for flags that take a filename - -To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so: -```go -flagName := "output" -cmd.MarkFlagFilename(flagName, "yaml", "json") -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt}) -``` - -### Limit flag completions to directory names - -To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so: -```go -flagName := "output" -cmd.MarkFlagDirname(flagName) -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterDirs -}) -``` -To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so: -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs -}) -``` -### Descriptions for completions - -Cobra provides support for completion descriptions. Such descriptions are supported for each shell -(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)). -For commands and flags, Cobra will provide the descriptions automatically, based on usage information. -For example, using zsh: -``` -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release -``` -while using fish: -``` -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) -``` - -Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp -}} -``` -or -```go -ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"} -``` -## Bash completions - -### Dependencies - -The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)) - -### Aliases - -You can also configure `bash` aliases for your program and they will also support completions. - -```bash -alias aliasname=origcommand -complete -o default -F __start_origcommand aliasname - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -### Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. -Please refer to [Bash Completions](bash_completions.md) for details. - -### Bash completion V2 - -Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling -`GenBashCompletion()` or `GenBashCompletionFile()`. - -A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or -`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion -(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion -solution described in this document. -Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash -completion V2 solution which provides the following extra features: -- Supports completion descriptions (like the other shells) -- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines) -- Streamlined user experience thanks to a completion behavior aligned with the other shells - -`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()` -you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra -will provide the description automatically based on usage information. You can choose to make this option configurable by -your users. - -``` -# With descriptions -$ helm s[tab][tab] -search (search for a keyword in charts) status (display the status of the named release) -show (show information of a chart) - -# Without descriptions -$ helm s[tab][tab] -search show status -``` -**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. -## Zsh completions - -Cobra supports native zsh completion generated from the root `cobra.Command`. -The generated completion script should be put somewhere in your `$fpath` and be named -`_`. You will need to start a new shell for the completions to become available. - -Zsh supports descriptions for completions. Cobra will provide the description automatically, -based on usage information. Cobra provides a way to completely disable such descriptions by -using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make -this a configurable option to your users. -``` -# With descriptions -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`. - * You should instead use `RegisterFlagCompletionFunc()`. - -### Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced. -Please refer to [Zsh Completions](zsh_completions.md) for details. - -## fish completions - -Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. -``` -# With descriptions -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `fish`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `fish`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) - -## PowerShell completions - -Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. - -The script is designed to support all three PowerShell completion modes: - -* TabCompleteNext (default windows style - on each key press the next option is displayed) -* Complete (works like bash) -* MenuComplete (works like zsh) - -You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function `. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode. - -Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles. - -``` -# With descriptions and Mode 'Complete' -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions. -$ helm s[tab] -search show status - -search for a keyword in charts - -# Without descriptions -$ helm s[tab] -search show status -``` -### Aliases - -You can also configure `powershell` aliases for your program and they will also support completions. - -``` -$ sal aliasname origcommand -$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -The name of the completer block variable is of the form `$__CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `powershell`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `powershell`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) diff --git a/vendor/github.com/spf13/cobra/user_guide.md b/vendor/github.com/spf13/cobra/user_guide.md deleted file mode 100644 index e55367e8..00000000 --- a/vendor/github.com/spf13/cobra/user_guide.md +++ /dev/null @@ -1,695 +0,0 @@ -# User Guide - -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: - -``` - ▾ appName/ - ▾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra-CLI is its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd - -Cobra doesn't require any special constructors. Simply create your commands. - -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - Complete documentation is available at https://gohugo.io/documentation/`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile string - userLicense string - - rootCmd = &cobra.Command{ - Use: "cobra-cli", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - } -) - -// Execute executes the root command. -func Execute() error { - return rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -### Create additional commands - -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. - -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -### Returning and handling errors - -If you wish to return an error to the caller of a command, `RunE` can be used. - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(tryCmd) -} - -var tryCmd = &cobra.Command{ - Use: "try", - Short: "Try and possibly fail at something", - RunE: func(cmd *cobra.Command, args []string) error { - if err := someFunc(); err != nil { - return err - } - return nil - }, -} -``` - -The error can then be caught at the execute function call. - -## Working with Flags - -Flags provide modifiers to control how the action command operates. - -### Assign flags to a command - -Since the flags are defined and used in different locations, we need to -define a variable outside with the correct scope to assign the flag to -work with. - -```go -var Verbose bool -var Source string -``` - -There are two different approaches to assign a flag. - -### Persistent Flags - -A flag can be 'persistent', meaning that this flag will be available to the -command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. - -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` - -### Local Flags - -A flag can also be assigned locally, which will only apply to that specific command. - -```go -localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` - -### Local Flag on Parent Commands - -By default, Cobra only parses local flags on the target command, and any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will -parse local flags on each command before executing the target command. - -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` - -### Bind Flags with Config - -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string - -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` - -In this example, the persistent flag `author` is bound with `viper`. -**Note**: the variable `author` will not be set to the value from config, -when the `--author` flag is provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -Or, for persistent flags: -```go -rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkPersistentFlagRequired("region") -``` - -### Flag Groups - -If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then -Cobra can enforce that requirement: -```go -rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") -rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") -rootCmd.MarkFlagsRequiredTogether("username", "password") -``` - -You can also prevent different flags from being provided together if they represent mutually -exclusive options such as specifying an output format as either `--json` or `--yaml` but never both: -```go -rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON") -rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML") -rootCmd.MarkFlagsMutuallyExclusive("json", "yaml") -``` - -In both of these cases: - - both local and persistent flags can be used - - **NOTE:** the group is only enforced on commands where every flag is defined - - a flag may appear in multiple groups - - a group may contain any number of flags - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field of `Command`. -The following validators are built in: - -- Number of arguments: - - `NoArgs` - report an error if there are any positional args. - - `ArbitraryArgs` - accept any number of args. - - `MinimumNArgs(int)` - report an error if less than N positional args are provided. - - `MaximumNArgs(int)` - report an error if more than N positional args are provided. - - `ExactArgs(int)` - report an error if there are not exactly N positional args. - - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`. -- Content of the arguments: - - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args. - -If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`. - -Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks. -For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional -args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as -shown below: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: MatchAll(ExactArgs(2), OnlyValidArgs), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`. -For example: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - // Optionally run one of the validators provided by cobra - if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { - return err - } - // Run the custom validation logic - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -## Example - -In the example below, we have defined three commands. Two are at the top level -and one (cmdTimes) is a child of one of the top commands. In this case the root -is not executable, meaning that a subcommand is required. This is accomplished -by not providing a 'Run' for the 'rootCmd'. - -We have only defined one flag for a single command. - -More documentation about flags is available at https://github.com/spf13/pflag - -```go -package main - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -func main() { - var echoTimes int - - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } - - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Echo: " + strings.Join(args, " ")) - }, - } - - var cmdTimes = &cobra.Command{ - Use: "times [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } - - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` - -For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/). - -## Help Command - -Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help -create' is called. Every command will automatically have the '--help' flag added. - -### Example - -The following output is automatically generated by Cobra. Nothing beyond the -command and flag definitions are needed. - - $ cobra-cli help - - Cobra is a CLI library for Go that empowers applications. - This application is a tool to generate the needed files - to quickly create a Cobra application. - - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra-cli [command] --help" for more information about a command. - - -Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. - -### Grouping commands in help - -Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly -defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element -of that subcommand. The groups will appear in the help output in the same order as they are defined using different -calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using -`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively. - -### Defining your own help - -You can provide your own Help command or your own template for the default command to use -with the following functions: - -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` - -The latter two will also apply to any children commands. - -## Usage Message - -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. - -### Example -You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. - - $ cobra-cli --invalid - Error: unknown flag: --invalid - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra [command] --help" for more information about a command. - -### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: - -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` - -## Version Flag - -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. - -## PreRun and PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - -- `PersistentPreRun` -- `PreRun` -- `Run` -- `PostRun` -- `PersistentPostRun` - -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: - -```go -package main - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func main() { - - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } - - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } - - rootCmd.AddCommand(subCmd) - - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() -} -``` - -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] - -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` - -## Suggestions when "unknown command" happens - -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: - -``` -$ hugo srever -Error: unknown command "srever" for "hugo" - -Did you mean this? - server - -Run 'hugo --help' for usage. -``` - -Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. - -If you need to disable suggestions or tweak the string distance in your command, use: - -```go -command.DisableSuggestions = true -``` - -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which -you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). - -## Generating shell completions - -Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). - -## Providing Active Help - -Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md). diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go index 84cec76f..1856e4c7 100644 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ b/vendor/github.com/spf13/cobra/zsh_completions.go @@ -1,4 +1,4 @@ -// Copyright 2013-2022 The Cobra Authors +// Copyright 2013-2023 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -90,6 +90,7 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) { compCmd = ShellCompNoDescRequestCmd } WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s +compdef _%[1]s %[1]s # zsh completion for %-36[1]s -*- shell-script -*- @@ -108,8 +109,9 @@ _%[1]s() local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d - local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder local -a completions __%[1]s_debug "\n========= starting completion logic ==========" @@ -177,7 +179,7 @@ _%[1]s() return fi - local activeHelpMarker="%[8]s" + local activeHelpMarker="%[9]s" local endIndex=${#activeHelpMarker} local startIndex=$((${#activeHelpMarker}+1)) local hasActiveHelp=0 @@ -227,6 +229,11 @@ _%[1]s() noSpace="-S ''" fi + if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then + __%[1]s_debug "Activating keep order." + keepOrder="-V" + fi + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then # File extension filtering local filteringCmd @@ -262,7 +269,7 @@ _%[1]s() return $result else __%[1]s_debug "Calling _describe" - if eval _describe "completions" completions $flagPrefix $noSpace; then + if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then __%[1]s_debug "_describe found some completions" # Return the success of having called _describe @@ -296,6 +303,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then fi `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpMarker)) } diff --git a/vendor/github.com/spf13/cobra/zsh_completions.md b/vendor/github.com/spf13/cobra/zsh_completions.md deleted file mode 100644 index 7cff6178..00000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.md +++ /dev/null @@ -1,48 +0,0 @@ -## Generating Zsh Completion For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced. - -### Deprecation summary - -See further below for more details on these deprecations. - -* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored. -* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`. -* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction`. - -### Behavioral changes - -**Noun completion** -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis| -|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`| -`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored| -|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)| -|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior| - -**Flag-value completion** - -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion| -|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored| -|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)| -|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells| -|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`| -|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`| - -**Improvements** - -* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`) -* File completion by default if no other completions found -* Handling of required flags -* File extension filtering no longer mutually exclusive with bash usage -* Completion of directory names *within* another directory -* Support for `=` form of flags diff --git a/vendor/modules.txt b/vendor/modules.txt index 86575e2d..0ec40a5d 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -307,7 +307,7 @@ github.com/rogpeppe/fastuuid github.com/sirupsen/logrus github.com/sirupsen/logrus/hooks/syslog github.com/sirupsen/logrus/hooks/writer -# github.com/spf13/cobra v1.6.1 +# github.com/spf13/cobra v1.7.1-0.20230723113155-fd865a44e3c4 ## explicit; go 1.15 github.com/spf13/cobra # github.com/spf13/pflag v1.0.5