From d54dc3dc8b5cef1fd719e17d94b44e06d6ff41a1 Mon Sep 17 00:00:00 2001 From: Lennart Espe <3391295+lnsp@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:48:01 +0100 Subject: [PATCH] Add service delete and project delete --cascade valar service delete [--yes] [service] deletes a service with everything it holds, defaulting to the service in .valar.yml. valar project delete --cascade deletes a project's services and domain claims before the project itself. Both ask for the name to confirm unless --yes is given, and refuse with exit code 2 when standard input is not a terminal. Plain project delete still accepts the name from piped input. A 409 or 5xx answer is retried with a short backoff; a 404 on a retry counts as done, while a 404 on the first attempt exits with 3. With --json they print {"service": ..., "deleted": true} or {"project": ..., "deleted": true}. --- README.md | 12 ++- api/client.go | 6 ++ api/projects.go | 12 ++- api/projects_test.go | 32 ++++++-- cmd/delete.go | 87 +++++++++++++++++++++ cmd/delete_test.go | 175 +++++++++++++++++++++++++++++++++++++++++++ cmd/projects.go | 62 ++++++++------- cmd/projects_test.go | 75 ++++++++++++------- cmd/services.go | 40 +++++++++- 9 files changed, 437 insertions(+), 64 deletions(-) create mode 100644 cmd/delete.go create mode 100644 cmd/delete_test.go diff --git a/README.md b/README.md index 83aef57..36f573a 100644 --- a/README.md +++ b/README.md @@ -140,10 +140,10 @@ A project name is 3 to 20 lowercase letters or digits and starts with a letter. #### Delete a project ```bash -valar projects delete [--yes] [project-name] +valar projects delete [--yes] [--cascade] [project-name] ``` -Only empty projects can be deleted: a project with services, domains or key-value storage is refused. The command asks you to type the project name to confirm; `--yes` skips that. +Without `--cascade`, only empty projects can be deleted: a project with services, domains or key-value storage is refused. With `--cascade`, the project's services are deleted first, then its domain claims. The command asks you to type the project name to confirm; `--yes` skips that. With `--cascade` and no terminal to ask on, it refuses unless `--yes` is given. > [!CAUTION] > Deleting a project retires its name for good. No one can create a project with that name again, not even you. @@ -207,6 +207,14 @@ valar service enable [--service service] valar service disable [--service service] ``` +#### Delete a service + +```bash +valar service delete [--yes] [service] +``` + +Deletes the service with its builds, deployments, batch executions, environment, secrets, schedules and permission rules. Its linked domains are unlinked; the project keeps their claims. The service defaults to the one in `.valar.yml`. The command asks you to type the service name to confirm; `--yes` skips that, and without a terminal it refuses unless `--yes` is given. If a deletion fails, the service stays disabled and running the command again finishes it. + #### Listing all deployments of a service ```bash diff --git a/api/client.go b/api/client.go index 8302342..5ab6aab 100644 --- a/api/client.go +++ b/api/client.go @@ -196,6 +196,12 @@ func (client *Client) AbortBuild(project, service, id string) error { return nil } +// DeleteService deletes a service with everything it holds. A failed deletion +// leaves the service disabled; deleting again finishes it. +func (client *Client) DeleteService(project, service string) error { + return client.request(http.MethodDelete, fmt.Sprintf("/projects/%s/services/%s", project, service), nil, nil) +} + // Sets a service' status. A disabled service cannot receive any requests. func (client *Client) ChangeServiceStatus(project, service string, disabled bool) error { var ( diff --git a/api/projects.go b/api/projects.go index 3f2fddf..be96f33 100644 --- a/api/projects.go +++ b/api/projects.go @@ -26,7 +26,13 @@ func (client *Client) CreateProject(name string, public bool) (*Project, error) return &project, nil } -// DeleteProject deletes an empty project. The platform retires its name for good. -func (client *Client) DeleteProject(name string) error { - return client.request(http.MethodDelete, "/projects/"+name, nil, nil) +// DeleteProject deletes a project and retires its name for good. Without +// cascade the project must be empty; with it, its services and domain claims +// are deleted first. +func (client *Client) DeleteProject(name string, cascade bool) error { + path := "/projects/" + name + if cascade { + path += "?cascade=true" + } + return client.request(http.MethodDelete, path, nil, nil) } diff --git a/api/projects_test.go b/api/projects_test.go index d225294..6536bf6 100644 --- a/api/projects_test.go +++ b/api/projects_test.go @@ -41,24 +41,32 @@ func TestCreateProject_SurfacesServerError(t *testing.T) { func TestDeleteProject(t *testing.T) { for _, tc := range []struct { - Name string - Status int - Body string - WantErr string + Name string + Cascade bool + Status int + Body string + WantQuery string + WantErr string }{ - {"Deleted", http.StatusOK, `{"status":"ok"}`, ""}, - {"NotEmpty", http.StatusConflict, `{"error":"only empty projects can be deleted, and this one has services"}`, + {"Deleted", false, http.StatusOK, `{"status":"ok"}`, "", ""}, + {"NotEmpty", false, http.StatusConflict, `{"error":"only empty projects can be deleted, and this one has services"}`, "", "Conflict: only empty projects can be deleted, and this one has services"}, + {"Cascade", true, http.StatusOK, `{"status":"ok"}`, "cascade=true", ""}, } { t.Run(tc.Name, func(t *testing.T) { + var query string client, requests := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) { + query = r.URL.RawQuery w.WriteHeader(tc.Status) w.Write([]byte(tc.Body)) }) - err := client.DeleteProject("demo") + err := client.DeleteProject("demo", tc.Cascade) if want := (recordedRequest{http.MethodDelete, "/projects/demo", ""}); (*requests)[0] != want { t.Errorf("request %+v, want %+v", (*requests)[0], want) } + if query != tc.WantQuery { + t.Errorf("query = %q, want %q", query, tc.WantQuery) + } switch { case tc.WantErr == "" && err != nil: t.Errorf("unexpected error: %v", err) @@ -68,3 +76,13 @@ func TestDeleteProject(t *testing.T) { }) } } + +func TestDeleteService(t *testing.T) { + client, requests := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) {}) + if err := client.DeleteService("demo", "web"); err != nil { + t.Fatalf("DeleteService: %v", err) + } + if want := (recordedRequest{http.MethodDelete, "/projects/demo/services/web", ""}); (*requests)[0] != want { + t.Errorf("request %+v, want %+v", (*requests)[0], want) + } +} diff --git a/cmd/delete.go b/cmd/delete.go new file mode 100644 index 0000000..2d992ff --- /dev/null +++ b/cmd/delete.go @@ -0,0 +1,87 @@ +package cmd + +import ( + "bufio" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" + + "github.com/valar/cli/api" + "golang.org/x/term" +) + +// confirmation reads a name to confirm a deletion. A nil confirmation skips +// the question, as --yes does. +type confirmation struct { + in io.Reader + terminal bool +} + +func stdinConfirmation(yes bool) *confirmation { + if yes { + return nil + } + return &confirmation{in: os.Stdin, terminal: term.IsTerminal(int(os.Stdin.Fd()))} +} + +// ask prints warning and asks for the name of the subject being deleted. +// Without a terminal it refuses, so a script never blocks on the question. +func (c *confirmation) ask(w io.Writer, subject, name, warning string) error { + if c == nil { + return nil + } + if !c.terminal { + return newError(kindInvalid, "refusing to delete %s %s without confirmation: standard input is not a terminal, pass --yes", subject, name) + } + fmt.Fprintln(w, warning) + fmt.Fprintf(w, "Type the %s name to confirm: ", subject) + line, _ := bufio.NewReader(c.in).ReadString('\n') + if strings.TrimSpace(line) != name { + return newError(kindInvalid, "aborted: the input does not match %s, pass --yes to skip the confirmation", name) + } + return nil +} + +// deleteRetryDelays are the waits before each retry of a deletion. +var deleteRetryDelays = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second} + +// retryDeletion calls del until it succeeds, retrying a 409 or 5xx answer. +// A 404 on a retry means an earlier attempt finished the deletion. +func retryDeletion(w io.Writer, del func() error) error { + for attempt := 0; ; attempt++ { + err := del() + var apiErr api.Error + if err == nil || !errors.As(err, &apiErr) { + return err + } + if attempt > 0 && apiErr.StatusCode == http.StatusNotFound { + return nil + } + retryable := apiErr.StatusCode == http.StatusConflict || apiErr.StatusCode >= 500 + if !retryable || attempt == len(deleteRetryDelays) { + return err + } + delay := deleteRetryDelays[attempt] + fmt.Fprintf(w, "Deletion not finished (%v), retrying in %s ...\n", err, delay) + time.Sleep(delay) + } +} + +func deleteService(client *api.Client, project, service string, confirm *confirmation, w io.Writer) error { + if err := api.VerifyNames(project, service); err != nil { + return withKind(kindInvalid, err) + } + warning := fmt.Sprintf("Deleting service %s in project %s removes its builds, deployments, batch executions, environment, secrets and schedules.", service, project) + if err := confirm.ask(w, "service", service, warning); err != nil { + return err + } + if err := retryDeletion(w, func() error { return client.DeleteService(project, service) }); err != nil { + return fmt.Errorf("delete service %s: %w", service, err) + } + fmt.Fprintf(w, "Deleted service %s.\n", service) + return nil +} diff --git a/cmd/delete_test.go b/cmd/delete_test.go new file mode 100644 index 0000000..399a269 --- /dev/null +++ b/cmd/delete_test.go @@ -0,0 +1,175 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/valar/cli/api" +) + +// newScriptedAPI answers the nth request with the nth status, and with the +// last status once they run out. It records each request as "METHOD uri". +func newScriptedAPI(t *testing.T, statuses ...int) (*api.Client, *[]string) { + t.Helper() + var ( + mu sync.Mutex + requests []string + ) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/" { + w.Write([]byte(`{"version":"v2"}`)) + return + } + mu.Lock() + defer mu.Unlock() + status := statuses[min(len(requests), len(statuses)-1)] + requests = append(requests, r.Method+" "+r.URL.RequestURI()) + w.WriteHeader(status) + if status == http.StatusOK { + w.Write([]byte(`{"status":"ok"}`)) + } else { + fmt.Fprintf(w, `{"error":%q}`, http.StatusText(status)) + } + })) + t.Cleanup(srv.Close) + client, err := api.NewClient(srv.URL, "token") + if err != nil { + t.Fatalf("new client: %v", err) + } + return client, &requests +} + +func fastDeleteRetries(t *testing.T) { + t.Helper() + prev := deleteRetryDelays + deleteRetryDelays = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond} + t.Cleanup(func() { deleteRetryDelays = prev }) +} + +func terminalInput(s string) *confirmation { + return &confirmation{in: strings.NewReader(s), terminal: true} +} + +func TestDeleteService(t *testing.T) { + const route = "DELETE /projects/demo/services/web" + for _, tc := range []struct { + Name string + Confirm *confirmation + Statuses []int + WantRequests int + WantKind errorKind + WantErr string + }{ + {"Confirmed", terminalInput("web\n"), []int{200}, 1, 0, ""}, + {"Yes", nil, []int{200}, 1, 0, ""}, + {"Mismatch", terminalInput("api\n"), []int{200}, 0, kindInvalid, "aborted"}, + {"NotATerminal", &confirmation{in: strings.NewReader("web\n")}, []int{200}, 0, kindInvalid, "pass --yes"}, + {"NotFound", nil, []int{404}, 1, kindNotFound, "Not Found"}, + {"RetryThenNotFound", nil, []int{503, 404}, 2, 0, ""}, + {"ConflictRetried", nil, []int{409, 409, 200}, 3, 0, ""}, + {"ConflictPersists", nil, []int{409}, 4, kindConflict, "Conflict"}, + {"ServerErrorPersists", nil, []int{500}, 4, kindUnavailable, "Internal Server Error"}, + {"ForbiddenNotRetried", nil, []int{403}, 1, kindNotAllowed, "Forbidden"}, + } { + t.Run(tc.Name, func(t *testing.T) { + fastDeleteRetries(t) + client, requests := newScriptedAPI(t, tc.Statuses...) + var out bytes.Buffer + err := deleteService(client, "demo", "web", tc.Confirm, &out) + if len(*requests) != tc.WantRequests { + t.Errorf("requests %v, want %d", *requests, tc.WantRequests) + } + for _, r := range *requests { + if r != route { + t.Errorf("request %q, want %q", r, route) + } + } + if tc.WantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.WantErr) { + t.Fatalf("error = %v, want one containing %q", err, tc.WantErr) + } + if got := classify(err, kindFailed); got != tc.WantKind { + t.Errorf("kind = %v, want %v", got, tc.WantKind) + } + return + } + if err != nil { + t.Fatalf("deleteService: %v", err) + } + if !strings.Contains(out.String(), "Deleted service web.") { + t.Errorf("output %q does not report the deletion", out.String()) + } + }) + } +} + +func TestDeleteService_PromptNamesService(t *testing.T) { + client, _ := newScriptedAPI(t, 200) + var out bytes.Buffer + deleteService(client, "demo", "web", terminalInput("no\n"), &out) + if !strings.Contains(out.String(), "Deleting service web in project demo") || !strings.Contains(out.String(), "Type the service name") { + t.Errorf("prompt %q does not name the service", out.String()) + } +} + +// runCLI runs the root command against endpoint with JSON output and returns +// what it printed on stdout. +func runCLI(t *testing.T, endpoint string, args ...string) string { + t.Helper() + cfgPath := filepath.Join(t.TempDir(), "config") + if err := os.WriteFile(cfgPath, nil, 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("VALARCONFIG", cfgPath) + t.Setenv("VALAR_ENDPOINT", endpoint) + t.Setenv("VALAR_TOKEN", "token") + out := setJSON(t, false) + t.Cleanup(func() { + serviceDeleteYes, projectsDeleteYes, projectsDeleteCascade = false, false, false + rootCmd.SetArgs(nil) + }) + rootCmd.SetArgs(append(args, "--json")) + if err := rootCmd.Execute(); err != nil { + t.Fatalf("valar %s: %v", strings.Join(args, " "), err) + } + return out.String() +} + +func TestDeleteCommands_JSON(t *testing.T) { + for _, tc := range []struct { + Name string + Args []string + WantRequest string + Want string + }{ + {"ServiceFromConfig", []string{"service", "delete", "--yes"}, "DELETE /projects/p/services/s", `{"service":"s","deleted":true}`}, + {"NamedService", []string{"service", "delete", "--yes", "api"}, "DELETE /projects/p/services/api", `{"service":"api","deleted":true}`}, + {"Project", []string{"project", "delete", "--yes", "demo"}, "DELETE /projects/demo", `{"project":"demo","deleted":true}`}, + {"ProjectCascade", []string{"project", "delete", "--yes", "--cascade", "demo"}, "DELETE /projects/demo?cascade=true", `{"project":"demo","deleted":true}`}, + } { + t.Run(tc.Name, func(t *testing.T) { + writeServiceConfig(t, deployConfig) + client, requests := newScriptedAPI(t, 200) + out := runCLI(t, client.Endpoint, tc.Args...) + if len(*requests) != 1 || (*requests)[0] != tc.WantRequest { + t.Errorf("requests %v, want [%s]", *requests, tc.WantRequest) + } + if got := strings.Join(strings.Fields(out), ""); got != tc.Want { + t.Errorf("printed %s, want %s", got, tc.Want) + } + var doc map[string]any + if err := json.Unmarshal([]byte(out), &doc); err != nil { + t.Errorf("output is not JSON: %v", err) + } + }) + } +} diff --git a/cmd/projects.go b/cmd/projects.go index 6b4c215..bcd0aa7 100644 --- a/cmd/projects.go +++ b/cmd/projects.go @@ -1,7 +1,6 @@ package cmd import ( - "bufio" "fmt" "io" "os" @@ -15,8 +14,9 @@ import ( ) var ( - projectsCreatePublic bool - projectsDeleteYes bool + projectsCreatePublic bool + projectsDeleteYes bool + projectsDeleteCascade bool ) var ( @@ -45,28 +45,33 @@ project without a token.`, } projectsDeleteCmd = &cobra.Command{ - Use: "delete [--yes] name", - Short: "Delete an empty project and retire its name.", - Long: `Delete an empty project and retire its name. + Use: "delete [--yes] [--cascade] name", + Short: "Delete a project and retire its name.", + Long: `Delete a project and retire its name. -Only a project without services, domains and key-value storage can be deleted. -Its name is retired for good: no project can use it again. The command asks -for the project name to confirm, unless --yes is given.`, +Without --cascade, only a project without services, domains and key-value +storage can be deleted. With --cascade, its services are deleted first, then +its domain claims. Its name is retired for good: no project can use it again. + +The command asks for the project name to confirm, unless --yes is given. With +--cascade it refuses to run without a terminal to ask on, unless --yes is +given.`, Args: cobra.ExactArgs(1), Run: runAndHandle(func(cmd *cobra.Command, args []string) error { client, err := globalConfiguration.APIClient() if err != nil { return err } - var confirm io.Reader = os.Stdin - if projectsDeleteYes { - confirm = nil + confirm := stdinConfirmation(projectsDeleteYes) + if confirm != nil && !projectsDeleteCascade { + // Deleting an empty project accepts the name from piped input. + confirm.terminal = true } - if err := deleteProject(client, args[0], confirm, os.Stderr); err != nil { + if err := deleteProject(client, args[0], projectsDeleteCascade, confirm, os.Stderr); err != nil { return err } return result(struct { - Name string `json:"name"` + Project string `json:"project"` Deleted bool `json:"deleted"` }{args[0], true}, func(io.Writer) error { return nil }) }), @@ -93,21 +98,27 @@ func printProject(project *api.Project, w io.Writer) error { return tw.Flush() } -// deleteProject reads the project name from confirm before deleting, unless -// confirm is nil. -func deleteProject(client *api.Client, name string, confirm io.Reader, w io.Writer) error { +// deleteProject asks confirm for the project name, then deletes the project. +// A cascading deletion is retried, as repeating it finishes a failed one. +func deleteProject(client *api.Client, name string, cascade bool, confirm *confirmation, w io.Writer) error { if err := api.VerifyProjectName(name); err != nil { return withKind(kindInvalid, err) } - if confirm != nil { - fmt.Fprintf(w, "Deleting project %s retires its name for good: no project can use it again.\n", name) - fmt.Fprint(w, "Type the project name to confirm: ") - line, _ := bufio.NewReader(confirm).ReadString('\n') - if strings.TrimSpace(line) != name { - return newError(kindInvalid, "aborted: the input does not match %s, pass --yes to skip the confirmation", name) - } + warning := fmt.Sprintf("Deleting project %s retires its name for good: no project can use it again.", name) + if cascade { + warning = fmt.Sprintf("Deleting project %s deletes all its services and domain claims, and retires its name for good: no project can use it again.", name) + } + if err := confirm.ask(w, "project", name, warning); err != nil { + return err } - if err := client.DeleteProject(name); err != nil { + del := func() error { return client.DeleteProject(name, cascade) } + var err error + if cascade { + err = retryDeletion(w, del) + } else { + err = del() + } + if err != nil { return err } fmt.Fprintf(w, "Deleted project %s. Its name can't be used again.\n", name) @@ -285,6 +296,7 @@ func authModifyWithState(state string) func(cmd *cobra.Command, args []string) e func initProjectsCmd() { projectsCreateCmd.Flags().BoolVar(&projectsCreatePublic, "public", false, "Let anyone invoke the project's services without a token") projectsDeleteCmd.Flags().BoolVarP(&projectsDeleteYes, "yes", "y", false, "Delete without asking for the project name") + projectsDeleteCmd.Flags().BoolVar(&projectsDeleteCascade, "cascade", false, "Delete the project's services and domain claims first") projectsCmd.AddCommand(projectsCreateCmd, projectsDeleteCmd) rootCmd.AddCommand(projectsCmd) authCmd.AddCommand(authListCmd, authAllowCmd, authForbidCmd, authClearCmd, authCheckCmd) diff --git a/cmd/projects_test.go b/cmd/projects_test.go index bd9be18..aea8e99 100644 --- a/cmd/projects_test.go +++ b/cmd/projects_test.go @@ -6,7 +6,10 @@ import ( "testing" ) -const deleteRoute = "DELETE /projects/demo" +const ( + deleteRoute = "DELETE /projects/demo" + cascadeRoute = "DELETE /projects/demo?cascade=true" +) func TestCreateProject(t *testing.T) { for _, tc := range []struct { @@ -39,36 +42,45 @@ func TestCreateProject(t *testing.T) { func TestDeleteProject(t *testing.T) { for _, tc := range []struct { - Name string - Project string - Confirm *string - WantDelete bool - WantErr string + Name string + Project string + Cascade bool + Confirm *confirmation + Statuses []int + WantRequests []string + WantKind errorKind + WantErr string }{ - {"Confirmed", "demo", ptr("demo\n"), true, ""}, - {"ConfirmedWithoutNewline", "demo", ptr(" demo"), true, ""}, - {"Yes", "demo", nil, true, ""}, - {"Mismatch", "demo", ptr("dem\n"), false, "aborted"}, - {"NoInput", "demo", ptr(""), false, "--yes"}, + {"Confirmed", "demo", false, terminalInput("demo\n"), []int{200}, []string{deleteRoute}, 0, ""}, + {"ConfirmedWithoutNewline", "demo", false, terminalInput(" demo"), []int{200}, []string{deleteRoute}, 0, ""}, + {"Yes", "demo", false, nil, []int{200}, []string{deleteRoute}, 0, ""}, + {"Mismatch", "demo", false, terminalInput("dem\n"), []int{200}, nil, kindInvalid, "aborted"}, + {"NoInput", "demo", false, terminalInput(""), []int{200}, nil, kindInvalid, "--yes"}, // The name is part of the request path, so it must be one. - {"InvalidName", "demo/services/api", nil, false, "invalid project name"}, + {"InvalidName", "demo/services/api", false, nil, []int{200}, nil, kindInvalid, "invalid project name"}, + // Without cascade a conflict means the project isn't empty. + {"NotEmptyNotRetried", "demo", false, nil, []int{409}, []string{deleteRoute}, kindConflict, "Conflict"}, + {"Cascade", "demo", true, terminalInput("demo\n"), []int{200}, []string{cascadeRoute}, 0, ""}, + {"CascadeNotATerminal", "demo", true, &confirmation{in: strings.NewReader("demo\n")}, []int{200}, nil, kindInvalid, "pass --yes"}, + {"CascadeConflictRetried", "demo", true, nil, []int{409, 200}, []string{cascadeRoute, cascadeRoute}, 0, ""}, + {"CascadeRetryThenNotFound", "demo", true, nil, []int{502, 404}, []string{cascadeRoute, cascadeRoute}, 0, ""}, + {"CascadeNotFound", "demo", true, nil, []int{404}, []string{cascadeRoute}, kindNotFound, "Not Found"}, } { t.Run(tc.Name, func(t *testing.T) { - client, requests := newFakeAPI(t, map[string]string{deleteRoute: `{"status":"ok"}`}) + fastDeleteRetries(t) + client, requests := newScriptedAPI(t, tc.Statuses...) var out bytes.Buffer - var err error - if tc.Confirm == nil { - err = deleteProject(client, tc.Project, nil, &out) - } else { - err = deleteProject(client, tc.Project, strings.NewReader(*tc.Confirm), &out) - } - if deleted := len(*requests) == 1; deleted != tc.WantDelete { - t.Fatalf("requests %+v, want delete %v", *requests, tc.WantDelete) + err := deleteProject(client, tc.Project, tc.Cascade, tc.Confirm, &out) + if strings.Join(*requests, ",") != strings.Join(tc.WantRequests, ",") { + t.Fatalf("requests %v, want %v", *requests, tc.WantRequests) } if tc.WantErr != "" { if err == nil || !strings.Contains(err.Error(), tc.WantErr) { t.Fatalf("error = %v, want one containing %q", err, tc.WantErr) } + if got := classify(err, kindFailed); got != tc.WantKind { + t.Errorf("kind = %v, want %v", got, tc.WantKind) + } return } if err != nil { @@ -82,11 +94,22 @@ func TestDeleteProject(t *testing.T) { } func TestDeleteProject_PromptNamesRetirement(t *testing.T) { - client, _ := newFakeAPI(t, map[string]string{deleteRoute: `{"status":"ok"}`}) - var out bytes.Buffer - deleteProject(client, "demo", strings.NewReader("no\n"), &out) - if !strings.Contains(out.String(), "retires its name") { - t.Errorf("prompt %q does not warn that the name is retired", out.String()) + for _, tc := range []struct { + Name string + Cascade bool + Want string + }{ + {"Empty", false, "retires its name"}, + {"Cascade", true, "deletes all its services and domain claims"}, + } { + t.Run(tc.Name, func(t *testing.T) { + client, _ := newScriptedAPI(t, 200) + var out bytes.Buffer + deleteProject(client, "demo", tc.Cascade, terminalInput("no\n"), &out) + if !strings.Contains(out.String(), tc.Want) { + t.Errorf("prompt %q lacks %q", out.String(), tc.Want) + } + }) } } diff --git a/cmd/services.go b/cmd/services.go index 2b5f4f4..041fffa 100644 --- a/cmd/services.go +++ b/cmd/services.go @@ -247,6 +247,43 @@ func enableService(client *api.Client, project, service string, w io.Writer) err } } +var serviceDeleteYes bool + +var serviceDeleteCmd = &cobra.Command{ + Use: "delete [--yes] [service]", + Short: "Delete a service and everything it holds.", + Long: `Delete a service with its builds, deployments, batch executions, +environment, secrets, schedules and the permission rules on it. Its linked +domains are unlinked; the project keeps their claims. + +The service defaults to the one in .valar.yml. The command asks for the +service name to confirm, unless --yes is given; without a terminal to ask on it +refuses instead. A deletion that fails leaves the service disabled, and running +the command again finishes it.`, + Args: cobra.MaximumNArgs(1), + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + client, err := globalConfiguration.APIClient() + if err != nil { + return err + } + var service string + if len(args) == 1 { + service = args[0] + } + cfg, err := config.NewServiceConfigWithFallback(functionConfiguration, &service, globalConfiguration) + if err != nil { + return err + } + if err := deleteService(client, cfg.Project(), cfg.Service(), stdinConfirmation(serviceDeleteYes), os.Stderr); err != nil { + return err + } + return result(struct { + Service string `json:"service"` + Deleted bool `json:"deleted"` + }{cfg.Service(), true}, func(io.Writer) error { return nil }) + }), +} + var serviceURLService string var serviceURLCmd = &cobra.Command{ @@ -325,6 +362,7 @@ func initServicesCmd() { serviceURLCmd.Flags().StringVarP(&serviceURLService, "service", "s", "", "The service to target") serviceDisableCmd.Flags().StringVarP(&serviceDisableService, "service", "s", "", "The service to target") serviceEnableCmd.Flags().StringVarP(&serviceEnableService, "service", "s", "", "The service to target") - serviceCmd.AddCommand(serviceListCmd, serviceLogsCmd, serviceInitCmd, serviceEnableCmd, serviceDisableCmd, serviceURLCmd) + serviceDeleteCmd.Flags().BoolVarP(&serviceDeleteYes, "yes", "y", false, "Delete without asking for the service name") + serviceCmd.AddCommand(serviceListCmd, serviceLogsCmd, serviceInitCmd, serviceEnableCmd, serviceDisableCmd, serviceURLCmd, serviceDeleteCmd) rootCmd.AddCommand(serviceCmd) }