* test(delete): pin that a stale id never deletes the issue it prefixes (be-ksd) bd delete resolves each id through the abbreviation-tolerant resolver (resolveAndGetIssueForMutation -> utils.ResolvePartialID). When the exact id is absent, that resolver falls through to leading-prefix abbreviation, so an id that was already deleted resolves to a different issue whose id it happens to begin, and --force deletes that issue. The shape is ordinary: hash length is adaptive (3 to 8 characters) so a grown store holds short ids beside longer ones, --id makes any shape, and a hierarchical child's id always extends its parent's. On a fixture, after fx-t00003 was deleted, bd delete fx-t00003 resolved to fx-t000031; a re-run of a finished --from-file list with --force --quiet deleted two issues it never named, silently. The test drives deleteCmd in-process against a stub DoltStorage (no cgo, no Dolt server) and records every request handed to the Deleter role. It covers the single-id --force path, the preview, a deleted parent's id with an orphaned child, the --from-file batch path, and an abbreviation of one and of two live issues; each refusal must say delete needs the full id and name the ids the input matches. An over-refusal guard checks that exact ids (full, bare hash, child, batch) still delete exactly what they name. The six refusal cases fail at this commit; the guard passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman * fix(delete): resolve ids exactly, never by prefix abbreviation (be-ksd) bd delete's direct route resolved each id with the abbreviation-tolerant resolver, so an id that no longer exists resolved to the surviving issue whose id it begins, and --force deleted that issue. Both of its resolution sites now use resolveAndGetIssueForMutationExact (#5393's exact sibling, until now used only by bd comment): the inline single-id path and deleteBatch, which --from-file, multiple ids and --cascade take. The resolver cannot tell a stale full id from an abbreviation. Hash length is adaptive with store size, so one store holds 3- to 8-character ids side by side and "fx-t00003" is both a valid full id and a valid abbreviation of "fx-t000031". The rule therefore has to be per command, the way #5393 made it for bd comment. Delete is exact on both preview and --force: the preview prints the next command to run ("To proceed, run: bd delete fx-t000031 --force"), so a tolerant preview hands the caller the wrong deletion to confirm. This matches the team-server route, which passes ids to issueops.Deleter unresolved, and DeleteRequest.IDs' own contract ("IDs ARE EXACT"). The partial-ID notice (#6302) did not protect this path: --quiet silences it, and a --force --quiet re-run of a finished --from-file list deleted two issues it never named. The refusal says what to do: "bd delete needs the full issue id: no issue has the id "t000", which is the start of fx-t000031". To name the matches, ResolvePartialIDExact now returns *utils.AbbreviatedIDError, which carries the input and the sorted matches, wraps ErrAbbreviatedIDNotAllowed and keeps the old error text, so bd comment's errors.Is checks and messages are unchanged. Cost: bd delete <abbreviation> is refused, naming the full ids, so the caller retypes one. Exact ids, bare full hashes, child, cross-prefix and routed ids resolve as before. The other deleteBatch callers (cleanup, wisp gc, mol burn) pass full ids read from the store, so nothing changes for them except under a race, where they now refuse instead of reaching a neighbor. Reads and other writes keep abbreviation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman * docs(ids): say bd delete requires the full id, like bd comment (be-ksd) The Working with IDs section named bd comment as the one command that refuses abbreviations and said every other mutation keeps them. bd delete now requires the exact id too, so the section covers both, says why a delete reaches the wrong issue so easily (an already-deleted id is still the start of its child's id, or of a longer hash), and adds the bd delete lines to the example block. Best Practices #1 names both commands. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman * docs(changelog): link the bd delete exact-id entry to #7375 (be-ksd) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman * fix(delete): report a gone parent's id as a lost race under --if-revision (be-ksd) Review-loop iteration 1 for #7375: a maintainer fixup on top of the contributor's branch. Major (codex+claude): a guarded `bd delete --if-revision` whose target was deleted, and whose id is still the start of a surviving id (a gone parent with a live <parent>.1 child), exited 1 with the abbreviation refusal. Any other gone target gets the documented lost race (precondition_failed, exit 13), and gascity's conditional deletes switch on that code, so a benign race read as a hard failure. - reportIfRevisionTargetGone (the single-id path) also takes utils.ErrAbbreviatedIDNotAllowed as a gone target: under delete's exact resolution that id names no row either. - The refusal is a typed error, deleteAbbreviationError, that unwraps to storage.ErrNotFound beside the *utils.AbbreviatedIDError, so the --cascade caller of deleteBatch classifies it through reportIfRevisionFailure the same way. errors.New(msg) dropped every sentinel. Minor (claude), taken: the refusal leads with the not-found fact, `issue "t000" not found: bd delete needs the full issue id, and "t000" is only the start of fx-t000031`, so gascity's isBdNotFound reads an already-gone full id that begins a survivor's id as the idempotent not-found it reads for any other gone id. The CHANGELOG entry quotes the new text and the --if-revision outcome. Minor (gemini), declined: threading the source command into the refusal's wording. deleteBatch's other callers (bd cleanup, wisp gc, mol burn) pass store-minted full ids that no user retypes, and the text now leads with "issue X not found", which holds for every caller. Tests: - TestDeleteIfRevisionGoneIDThatPrefixesAnotherIssue: single id, --json, --cascade and --cascade --json each exit 13 with "precondition failed: issue no longer exists" and the precondition_failed body, never the refusal text, and the guarded write never runs. Two no-survivor rows are the plain gone id they must match. - TestReportIfRevisionTargetGone: abbreviation rows, guarded and not. - TestDeleteRefusesStaleIDThatPrefixesAnotherIssue also asserts the refusal says "not found". - TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed, end to end on embedded Dolt: delete a parent, its child survives and `bd show <parent>` resolves to it; a guarded delete of the parent exits 13 on the single-id and --cascade paths and leaves the child. The TestEmbedded name is what puts it in a CI lane; its line in embedded-cmd-test-shards.txt is the generator's incremental --write. Mutation checks, each reverted afterwards: dropping the ErrAbbreviatedIDNotAllowed match fails the single-id cases and the abbreviation_guarded row; dropping ErrNotFound from Unwrap fails the --cascade cases; dropping "not found" from the text fails every refusal case; reverting both fixes fails both embedded legs (exit 1, the refusal text, no "precondition failed"). Validation: the focused delete and if-revision tests; the embedded pair under BEADS_TEST_EMBEDDED_DOLT=1; the scripts shard-manifest policy tests and the generator's --check; gofmt; git diff --check. The full ./cmd/bd and ./internal/utils packages (-short, BEADS_TEST_SKIP=dolt) pass but for TestRunApplyAllOK, which fails only because this worktree sets core.hooksPath=/dev/null ("mkdir /dev/null: not a directory") and passes with core.hooksPath overridden. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
615 lines
22 KiB
Go
615 lines
22 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
storeissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
var deleteCmd = &cobra.Command{
|
|
Use: "delete <issue-id> [issue-id...]",
|
|
GroupID: "issues",
|
|
Short: "Delete one or more issues and clean up references",
|
|
Long: `Delete one or more issues and clean up all references to them.
|
|
This command will:
|
|
1. Remove all dependency links (any type, both directions) involving the issues
|
|
2. Update text references to "[deleted:ID]" in directly connected issues
|
|
3. Permanently delete the issues from the database
|
|
|
|
This is a destructive operation that cannot be undone. Use with caution.
|
|
|
|
BATCH DELETION:
|
|
Delete multiple issues at once:
|
|
bd delete bd-1 bd-2 bd-3 --force
|
|
|
|
Delete from file (one ID per line):
|
|
bd delete --from-file deletions.txt --force
|
|
|
|
Preview before deleting:
|
|
bd delete --from-file deletions.txt --dry-run
|
|
|
|
DEPENDENCY HANDLING (the same on a local database and against a team server):
|
|
Default: Fails if any issue has dependents not in deletion set
|
|
bd delete bd-1 bd-2
|
|
|
|
Cascade: Recursively delete all dependents
|
|
bd delete bd-1 --cascade --force
|
|
|
|
Force: Delete and orphan dependents
|
|
bd delete bd-1 --force`,
|
|
Args: cobra.MinimumNArgs(0),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("delete")
|
|
|
|
evt := metrics.NewCommandEvent("delete")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if usesProxiedServer() {
|
|
return runDeleteProxiedServer(cmd, rootCtx, args)
|
|
}
|
|
|
|
fromFile, _ := cmd.Flags().GetString("from-file")
|
|
force, _ := cmd.Flags().GetBool("force")
|
|
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
|
cascade, _ := cmd.Flags().GetBool("cascade")
|
|
issueIDs := make([]string, 0, len(args))
|
|
issueIDs = append(issueIDs, args...)
|
|
if fromFile != "" {
|
|
fileIDs, err := readIssueIDsFromFile(fromFile)
|
|
if err != nil {
|
|
return HandleError("reading file: %v", err)
|
|
}
|
|
issueIDs = append(issueIDs, fileIDs...)
|
|
}
|
|
if len(issueIDs) == 0 {
|
|
_ = cmd.Usage()
|
|
return HandleError("no issue IDs provided")
|
|
}
|
|
issueIDs = uniqueStrings(issueIDs)
|
|
|
|
// A8 (beads#4682): issueops.DeleteRequest.ExpectedVersion already refuses
|
|
// (ErrValidation) a non-nil token beside more than one distinct id, but
|
|
// that refusal reads differently from the other three verbs' —
|
|
// requireSingleIfRevisionID gives this one the same wording and the same
|
|
// "before any write" timing as update/close/assign.
|
|
ifRevision, err := parseIfRevisionFlag(cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := requireSingleIfRevisionID(ifRevision, issueIDs); err != nil {
|
|
return err
|
|
}
|
|
|
|
if store == nil {
|
|
if err := ensureStoreActive(); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
|
|
if len(issueIDs) > 1 || cascade {
|
|
if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, ifRevision); err != nil {
|
|
if ifRevision != nil {
|
|
if reported, ok := reportIfRevisionFailure("deleting", issueIDs[0], err, ifRevision); ok {
|
|
return reported
|
|
}
|
|
}
|
|
if _, ok := exitCodeFromError(err); ok {
|
|
return err
|
|
}
|
|
return HandleError("%v", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
issueID := issueIDs[0]
|
|
ctx := rootCtx
|
|
// Get the issue to be deleted, using prefix-based routing. Resolution
|
|
// stays in the front door: issueops.DeleteRequest.IDs are exact, because
|
|
// resolving an ambiguous prefix and then deleting the row it hit is the
|
|
// one place a convenience is not.
|
|
//
|
|
// Exact here too, never a leading-prefix abbreviation: an id that is
|
|
// gone (already deleted, a re-run script) would otherwise resolve to
|
|
// whichever surviving issue's id it begins, and the preview would
|
|
// print `bd delete <that issue> --force` as the next step.
|
|
routedResult, err := resolveAndGetIssueForMutationExact(ctx, store, issueID)
|
|
if err != nil {
|
|
// mc-zndi7.81: this pre-flight existence check runs before
|
|
// deleter.Delete() and the per-id lock fence #7244 added, so a
|
|
// same-token --if-revision racer that loses the fence sees the
|
|
// row disappear right here instead of inside the guarded write
|
|
// below — see reportIfRevisionTargetGone.
|
|
if reported, ok := reportIfRevisionTargetGone("deleting", issueID, err, ifRevision); ok {
|
|
return reported
|
|
}
|
|
if isNotFoundErr(err) {
|
|
return HandleError("issue %s not found", issueID)
|
|
}
|
|
if refusal := deleteAbbreviationRefusal(err); refusal != nil {
|
|
return HandleError("%v", refusal)
|
|
}
|
|
return HandleError("%v", err)
|
|
}
|
|
defer routedResult.Close()
|
|
issue := routedResult.Issue
|
|
issueID = routedResult.ResolvedID
|
|
activeStore := routedResult.Store
|
|
|
|
deleter, err := activeStore.Deleter()
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
// --force is this command's CONFIRMATION as well as its orphan mode, so an
|
|
// unconfirmed run asks the role the same question a --dry-run does. The
|
|
// rewrite runs INSIDE the transaction that deletes, because it is the
|
|
// role's.
|
|
request := issueops.DeleteRequest{
|
|
Actor: currentActor(),
|
|
IDs: []string{issueID},
|
|
Force: force,
|
|
DryRun: dryRun || !force,
|
|
ExpectedVersion: ifRevision,
|
|
}
|
|
opsCtx, err := issueOpsContext(ctx)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result, err := deleter.Delete(opsCtx, request)
|
|
if request.DryRun {
|
|
if err != nil {
|
|
// A8 (beads#4682): a guard mismatch is reported through the
|
|
// dedicated conditional-write envelope instead of the generic
|
|
// preview-with-error below — same split delete's real run makes,
|
|
// so --dry-run and the real run answer a stale token identically.
|
|
if ifRevision != nil {
|
|
if reported, ok := reportIfRevisionFailure("deleting", issueID, err, ifRevision); ok {
|
|
return reported
|
|
}
|
|
}
|
|
if previewErr := outputDeletionPreview([]string{issueID}, map[string]*types.Issue{issueID: issue}, false, dryRun, nil, err, jsonOutput); previewErr != nil {
|
|
return previewErr
|
|
}
|
|
if jsonOutput {
|
|
return outputJSONError(err, "")
|
|
}
|
|
return HandleError("previewing deletion: %v", err)
|
|
}
|
|
if jsonOutput || isQuiet() {
|
|
return outputDeletionPreview([]string{issueID}, map[string]*types.Issue{issueID: issue}, false, dryRun, &result, nil, jsonOutput)
|
|
}
|
|
return renderSingleDeletePreview(ctx, activeStore, issueID, issue, dryRun, result)
|
|
}
|
|
if err != nil {
|
|
if ifRevision != nil {
|
|
if reported, ok := reportIfRevisionFailure("deleting", issueID, err, ifRevision); ok {
|
|
return reported
|
|
}
|
|
}
|
|
return HandleError("deleting issue: %v", err)
|
|
}
|
|
|
|
commandDidWrite.Store(true)
|
|
|
|
// NO COMMIT COMPENSATION HERE. The role versions its own deletion on
|
|
// every backend now, including the embedded one, which publishes the
|
|
// entry after its SQL commit — and it does so on the store the rows
|
|
// were actually deleted from, which for a prefix-routed id is the
|
|
// TARGET repository rather than this workspace. This route once had to
|
|
// mint that commit itself, because the port onto the role dropped the
|
|
// version commit embedded deletes used to get; a compensation here
|
|
// would now find a clean working set and add nothing but a second
|
|
// spelling of the same event. Batch and off modes are still honored:
|
|
// issueOpsContext above defers the role's commit in either.
|
|
|
|
if jsonOutput {
|
|
// The single-issue keys, unchanged: `deleted` is the id rather than a
|
|
// list here, which is what every `bd delete <one-id> --json` parses.
|
|
if err := outputJSON(map[string]interface{}{
|
|
"deleted": issueID,
|
|
"dependencies_removed": result.Dependencies,
|
|
"references_updated": result.ReferencesUpdated,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
fmt.Printf("%s Deleted %s\n", ui.RenderPass("✓"), issueID)
|
|
fmt.Printf(" Removed %d dependency link(s)\n", result.Dependencies)
|
|
fmt.Printf(" Updated text references in %d issue(s)\n", result.ReferencesUpdated)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// renderSingleDeletePreview prints the human preview for a one-issue delete. The
|
|
// counts come from the role's dry run; the edge listing and the "which neighbors
|
|
// cite this id" lines are reads this handler makes, because a delete answers
|
|
// with an effect rather than with rows.
|
|
func renderSingleDeletePreview(
|
|
ctx context.Context, activeStore storage.DoltStorage,
|
|
issueID string, issue *types.Issue, dryRun bool, result issueops.DeleteResult,
|
|
) error {
|
|
connectedIssues := make(map[string]*types.Issue)
|
|
deps, err := activeStore.GetDependencies(ctx, issueID)
|
|
if err != nil {
|
|
return HandleError("getting dependencies: %v", err)
|
|
}
|
|
for _, dep := range deps {
|
|
connectedIssues[dep.ID] = dep
|
|
}
|
|
dependents, err := activeStore.GetDependents(ctx, issueID)
|
|
if err != nil {
|
|
return HandleError("getting dependents: %v", err)
|
|
}
|
|
for _, dependent := range dependents {
|
|
connectedIssues[dependent.ID] = dependent
|
|
}
|
|
depRecords, err := activeStore.GetDependencyRecords(ctx, issueID)
|
|
if err != nil {
|
|
return HandleError("getting dependency records: %v", err)
|
|
}
|
|
// The role's own citation rule, not a second copy: a preview naming a
|
|
// different set of neighbors than the deletion rewrites is worse than none.
|
|
re := storeissueops.DeletedReferencePattern(issueID)
|
|
|
|
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
|
|
fmt.Printf("\nIssue to delete:\n")
|
|
fmt.Printf(" %s: %s\n", issueID, issue.Title)
|
|
totalDeps := len(depRecords) + len(dependents)
|
|
if totalDeps > 0 {
|
|
fmt.Printf("\nDependency links to remove: %d\n", totalDeps)
|
|
for _, dep := range depRecords {
|
|
fmt.Printf(" %s → %s (%s)\n", dep.IssueID, dep.DependsOnID, dep.Type)
|
|
}
|
|
for _, dep := range dependents {
|
|
fmt.Printf(" %s → %s (inbound)\n", dep.ID, issueID)
|
|
}
|
|
}
|
|
if len(connectedIssues) > 0 {
|
|
fmt.Printf("\nConnected issues where text references will be updated:\n")
|
|
issuesWithRefs := 0
|
|
for id, connIssue := range connectedIssues {
|
|
hasRefs := re.MatchString(connIssue.Description) ||
|
|
(connIssue.Notes != "" && re.MatchString(connIssue.Notes)) ||
|
|
(connIssue.Design != "" && re.MatchString(connIssue.Design)) ||
|
|
(connIssue.AcceptanceCriteria != "" && re.MatchString(connIssue.AcceptanceCriteria))
|
|
if hasRefs {
|
|
fmt.Printf(" %s: %s\n", id, connIssue.Title)
|
|
issuesWithRefs++
|
|
}
|
|
}
|
|
if issuesWithRefs == 0 {
|
|
fmt.Printf(" (none have text references)\n")
|
|
}
|
|
}
|
|
if dryRun {
|
|
fmt.Printf("\nWould delete: %d issues\n", result.Deleted)
|
|
fmt.Printf("Would remove: %d dependencies, %d labels, %d events\n", result.Dependencies, result.Labels, result.Events)
|
|
if len(result.Orphaned) > 0 {
|
|
fmt.Printf("Would orphan: %d issues\n", len(result.Orphaned))
|
|
}
|
|
fmt.Printf("\n(Dry-run mode - no changes made)\n")
|
|
} else {
|
|
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
|
|
fmt.Printf("To proceed, run: %s\n\n", ui.RenderWarn("bd delete "+issueID+" --force"))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// deleteAbbreviationRefusal is the refusal of an id that names no issue
|
|
// exactly but is the start of one or more: delete needs the full id, so say
|
|
// that and name the ids it begins. It is nil for any other error.
|
|
func deleteAbbreviationRefusal(err error) error {
|
|
var abbrev *utils.AbbreviatedIDError
|
|
if !errors.As(err, &abbrev) {
|
|
return nil
|
|
}
|
|
return &deleteAbbreviationError{abbrev: abbrev}
|
|
}
|
|
|
|
// deleteAbbreviationError is that refusal. To a delete, an id that is only the
|
|
// start of other ids names no row, so the text leads with "not found" — the
|
|
// words gascity's isBdNotFound reads as an already-gone bead — and the error
|
|
// unwraps to storage.ErrNotFound, which lets a guarded `bd delete --cascade`
|
|
// report it as the same lost race as any other gone target (see
|
|
// reportIfRevisionTargetGone).
|
|
type deleteAbbreviationError struct {
|
|
abbrev *utils.AbbreviatedIDError
|
|
}
|
|
|
|
func (e *deleteAbbreviationError) Error() string {
|
|
return fmt.Sprintf("issue %q not found: bd delete needs the full issue id, and %q is only the start of %s",
|
|
e.abbrev.Input, e.abbrev.Input, strings.Join(e.abbrev.Matches, ", "))
|
|
}
|
|
|
|
func (e *deleteAbbreviationError) Unwrap() []error { return []error{storage.ErrNotFound, e.abbrev} }
|
|
|
|
// deleteIssue removes an issue from the database.
|
|
func deleteIssue(ctx context.Context, issueID string) error {
|
|
return store.DeleteIssue(ctx, issueID)
|
|
}
|
|
|
|
// deleteBatch is the multi-id and cascade path, shared by `bd delete`,
|
|
// `bd cleanup`, `bd wisp gc` and `bd mol burn`.
|
|
//
|
|
// It resolves the ids in the front door - exact-id matching and
|
|
// cross-repository routing, which issueops.DeleteRequest deliberately does not
|
|
// do - and hands the RESOLVED ids to the role. Never a leading-prefix
|
|
// abbreviation: a re-run of a finished --from-file list would otherwise
|
|
// delete every surviving issue whose id one of its ids begins.
|
|
//
|
|
// ifRevision is non-nil only via `bd delete`'s own --if-revision (beads#4682);
|
|
// its other three callers always pass nil, and requireSingleIfRevisionID has
|
|
// already refused this path if it were asked to guard more than one id.
|
|
//
|
|
//nolint:unparam // cmd parameter required for potential future use
|
|
func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool, _ bool, ifRevision *int64, _ ...string) error {
|
|
if store == nil {
|
|
if err := ensureStoreActive(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
ctx := rootCtx
|
|
issues := make(map[string]*types.Issue)
|
|
resolvedIDs := make([]string, 0, len(issueIDs))
|
|
notFound := []string{}
|
|
var routedStore storage.DoltStorage
|
|
for _, id := range issueIDs {
|
|
result, err := resolveAndGetIssueForMutationExact(ctx, store, id)
|
|
if err != nil {
|
|
if isNotFoundErr(err) {
|
|
notFound = append(notFound, id)
|
|
} else if refusal := deleteAbbreviationRefusal(err); refusal != nil {
|
|
return refusal
|
|
} else {
|
|
return fmt.Errorf("getting issue %s: %v", id, err)
|
|
}
|
|
} else {
|
|
issues[result.ResolvedID] = result.Issue
|
|
resolvedIDs = append(resolvedIDs, result.ResolvedID)
|
|
if result.Routed && routedStore == nil {
|
|
routedStore = result.Store
|
|
} else {
|
|
result.Close()
|
|
}
|
|
}
|
|
}
|
|
if routedStore != nil {
|
|
defer func() { _ = routedStore.Close() }()
|
|
}
|
|
if len(notFound) > 0 {
|
|
// The role's own existence probe reports a missing id with this same
|
|
// error, and its text is the flat list every caller has always
|
|
// printed. What it adds is the storage.ErrNotFound sentinel, which
|
|
// lets the guarded `bd delete --cascade` caller's
|
|
// reportIfRevisionFailure report a target that a concurrent `bd
|
|
// delete` removed before this resolution as the same lost race as one
|
|
// removed inside deleter.Delete below: precondition_failed, not exit 1
|
|
// (see reportIfRevisionTargetGone).
|
|
return &issueops.NotFoundError{IDs: notFound}
|
|
}
|
|
batchStore := store
|
|
if routedStore != nil {
|
|
batchStore = routedStore
|
|
}
|
|
|
|
deleter, err := batchStore.Deleter()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// --force is the confirmation as well as the orphan mode, so an unconfirmed
|
|
// run asks the role what it WOULD do; see the single-id path.
|
|
request := issueops.DeleteRequest{
|
|
Actor: currentActor(),
|
|
IDs: resolvedIDs,
|
|
Cascade: cascade,
|
|
Force: force,
|
|
DryRun: dryRun || !force,
|
|
ExpectedVersion: ifRevision,
|
|
}
|
|
opsCtx, err := issueOpsContext(ctx)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result, err := deleter.Delete(opsCtx, request)
|
|
if request.DryRun {
|
|
if err != nil {
|
|
// A8 (beads#4682): let the caller's dedicated conditional-write
|
|
// envelope report a guard mismatch instead of the generic
|
|
// preview-with-error below -- see the single-id path's identical
|
|
// split. classifyIfRevisionFailure, not a bare ifRevision!=nil check,
|
|
// because an unrelated dry-run failure (not-found, bad request) on a
|
|
// guarded call still belongs to the generic preview path.
|
|
if ifRevision != nil {
|
|
if _, _, _, _, ok := classifyIfRevisionFailure(err, ifRevision); ok {
|
|
return err
|
|
}
|
|
}
|
|
if previewErr := outputDeletionPreview(resolvedIDs, issues, cascade, dryRun, nil, err, jsonOutput); previewErr != nil {
|
|
return previewErr
|
|
}
|
|
if jsonOutput {
|
|
return outputJSONError(err, "")
|
|
}
|
|
return err
|
|
}
|
|
if previewErr := outputDeletionPreview(resolvedIDs, issues, cascade, dryRun, &result, nil, jsonOutput); previewErr != nil {
|
|
return previewErr
|
|
}
|
|
if !dryRun && !jsonOutput && !isQuiet() {
|
|
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
|
|
if cascade {
|
|
fmt.Printf("To proceed with cascade deletion, run: %s\n",
|
|
ui.RenderWarn("bd delete "+strings.Join(resolvedIDs, " ")+" --cascade --force"))
|
|
} else {
|
|
fmt.Printf("To proceed, run: %s\n",
|
|
ui.RenderWarn("bd delete "+strings.Join(resolvedIDs, " ")+" --force"))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
commandDidWrite.Store(true)
|
|
|
|
// Tell this command's own auto-export that these ids are supposed to be
|
|
// gone. Without it the export's orphan guard sees them as JSONL-only
|
|
// records absent from the store, refuses to overwrite, and never saves
|
|
// state — which is the permanent wedge of GH#5896. Recorded for the
|
|
// requested ids; anything cascade removed alongside them is proven later
|
|
// by the store's own history instead.
|
|
commandDeletedIssueIDs.add(resolvedIDs...)
|
|
|
|
// NO COMMIT COMPENSATION HERE, for the reason the single-id path gives:
|
|
// the role versions the deletion itself, on the store the rows were
|
|
// deleted from, and defers it in batch and off modes.
|
|
|
|
if jsonOutput {
|
|
if err := outputJSON(map[string]interface{}{
|
|
"deleted": resolvedIDs,
|
|
"deleted_count": result.Deleted,
|
|
"dependencies_removed": result.Dependencies,
|
|
"labels_removed": result.Labels,
|
|
"events_removed": result.Events,
|
|
"references_updated": result.ReferencesUpdated,
|
|
"orphaned_issues": result.Orphaned,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("✓"), result.Deleted)
|
|
fmt.Printf(" Removed %d dependency link(s)\n", result.Dependencies)
|
|
fmt.Printf(" Removed %d label(s)\n", result.Labels)
|
|
fmt.Printf(" Removed %d event(s)\n", result.Events)
|
|
fmt.Printf(" Updated text references in %d issue(s)\n", result.ReferencesUpdated)
|
|
if len(result.Orphaned) > 0 {
|
|
fmt.Printf(" %s Orphaned %d issue(s): %s\n",
|
|
ui.RenderWarn("⚠"), len(result.Orphaned), strings.Join(result.Orphaned, ", "))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// outputDeletionPreview renders a deletion preview without exposing issue
|
|
// payloads in machine-readable or quiet output.
|
|
//
|
|
// result is the ROLE's dry run, or nil when the role refused: printing zeros
|
|
// beside a refusal would read as "nothing would have been deleted" rather than
|
|
// "we did not get that far".
|
|
func outputDeletionPreview(issueIDs []string, issues map[string]*types.Issue, cascade bool, dryRun bool, result *issueops.DeleteResult, depError error, jsonOutput bool) error {
|
|
if jsonOutput {
|
|
preview := map[string]interface{}{
|
|
"preview": true,
|
|
"dry_run": dryRun,
|
|
"issue_ids": issueIDs,
|
|
"cascade": cascade,
|
|
}
|
|
if result != nil {
|
|
preview["would_delete"] = result.Deleted
|
|
preview["would_remove_dependencies"] = result.Dependencies
|
|
preview["would_remove_labels"] = result.Labels
|
|
preview["would_remove_events"] = result.Events
|
|
preview["would_orphan"] = len(result.Orphaned)
|
|
}
|
|
if depError != nil {
|
|
preview["error"] = depError.Error()
|
|
}
|
|
return outputJSON(preview)
|
|
}
|
|
if isQuiet() {
|
|
return nil
|
|
}
|
|
|
|
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
|
|
fmt.Printf("\nIssues to delete (%d):\n", len(issueIDs))
|
|
for _, id := range issueIDs {
|
|
if issue := issues[id]; issue != nil {
|
|
fmt.Printf(" %s: %s\n", id, issue.Title)
|
|
}
|
|
}
|
|
if cascade {
|
|
fmt.Printf("\n%s Cascade mode enabled - will also delete all dependent issues\n", ui.RenderWarn("⚠"))
|
|
}
|
|
if depError != nil {
|
|
fmt.Printf("\n%s\n", ui.RenderFail(depError.Error()))
|
|
}
|
|
if result != nil {
|
|
fmt.Printf("\nWould delete: %d issues\n", result.Deleted)
|
|
fmt.Printf("Would remove: %d dependencies, %d labels, %d events\n",
|
|
result.Dependencies, result.Labels, result.Events)
|
|
if len(result.Orphaned) > 0 {
|
|
fmt.Printf("Would orphan: %d issues\n", len(result.Orphaned))
|
|
}
|
|
if dryRun {
|
|
fmt.Printf("\n(Dry-run mode - no changes made)\n")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// readIssueIDsFromFile reads issue IDs from a file (one per line)
|
|
func readIssueIDsFromFile(filename string) ([]string, error) {
|
|
// #nosec G304 - user-provided file path is intentional
|
|
f, err := os.Open(filename)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
var ids []string
|
|
scanner := bufio.NewScanner(f)
|
|
for scanner.Scan() {
|
|
line := strings.TrimSpace(scanner.Text())
|
|
// Skip empty lines and comments
|
|
if line == "" || strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
ids = append(ids, line)
|
|
}
|
|
if err := scanner.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return ids, nil
|
|
}
|
|
|
|
// uniqueStrings removes duplicates from a slice of strings
|
|
func uniqueStrings(slice []string) []string {
|
|
seen := make(map[string]bool)
|
|
result := make([]string, 0, len(slice))
|
|
for _, s := range slice {
|
|
if !seen[s] {
|
|
seen[s] = true
|
|
result = append(result, s)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func init() {
|
|
deleteCmd.Flags().BoolP("force", "f", false, "Actually delete (without this flag, shows preview)")
|
|
deleteCmd.Flags().String("from-file", "", "Read issue IDs from file (one per line)")
|
|
deleteCmd.Flags().Bool("dry-run", false, "Preview what would be deleted without making changes")
|
|
deleteCmd.Flags().Bool("cascade", false, "Recursively delete all dependent issues")
|
|
// A8 (beads#4682)
|
|
deleteCmd.Flags().String("if-revision", "", ifRevisionFlagHelp)
|
|
deleteCmd.ValidArgsFunction = issueIDCompletion
|
|
rootCmd.AddCommand(deleteCmd)
|
|
}
|