* perf(git): locate the repository in-process instead of running git rev-parse Every bd invocation resolved the process-wide git context (beads directory discovery reads it) with `git rev-parse --git-dir --git-common-dir --show-toplevel`: one git subprocess per bd call before any work. Tools that call bd hundreds of times (gascity's doctor issues ~250 bd calls per run) paid it on every call. On Linux, initGitContext now first runs discoverGitInProcess, which mirrors Git's discovery walk (physical cwd, .git as directory or gitfile, bare-dir check, filesystem-boundary stop) and produces byte-for-byte what rev-parse prints for ordinary repositories (top and subdirectories), linked worktrees (absolute or relative gitfile, symlinked targets), submodules (core.worktree pointing back at the gitfile's directory), nested repositories and no repository. Both answers feed one shared normalization (gitContextFromRevParse), so downstream values are unchanged. It declines, and git runs exactly as before, whenever it cannot prove the answer: GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR / GIT_CEILING_DIRECTORIES / GIT_DISCOVERY_ACROSS_FILESYSTEM / GIT_OBJECT_DIRECTORY / GIT_CONFIG_PARAMETERS / GIT_CONFIG_COUNT in the environment; a symlinked .git, an invalid gitfile or git directory, a cwd inside a git directory; repository config with core.worktree (other than the submodule shape), core.bare, extensions, include directives, a format version above 1 or unmodeled syntax; any path not owned by the effective uid (safe.directory is git's to evaluate), or root under sudo. darwin and windows keep the subprocess (case folding and ownership semantics). Tests compare discoverGitFrom with real `git rev-parse` output across those layouts, pin every decline case, and check the resulting cached context equals the subprocess-derived one. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(cli): resolve the git user.name actor fallback only when needed PersistentPreRunE assigned `actor = getActorWithGit()` for every command, which, with no --actor / BEADS_ACTOR / BD_ACTOR / config actor, runs `git config user.name`: the second git subprocess of every bd call, paid by read-only commands that never consult the actor. The pre-run now calls deferActorGitFallback, which marks an empty actor as pending; currentActor (and getActorWithGit, getActor) resolve it on first use with the unchanged priority order and store it in the global and the CommandContext copy, as the eager assignment did. Command code reads the actor through currentActor() instead of the raw global (a mechanical rewrite of every read site the compiler reported; writes, the flag binding and the pre-run config binding keep the raw variable). setActor cancels a pending fallback. The telemetry span's bd.actor attribute is still set, but only for a recording span, so a noop span does not force the lookup. With the in-process repository discovery from the previous commit, a read-only `bd list` / `bd show` now starts no git process at startup, in the main checkout and in a linked worktree; a write asks git for user.name once (bd create previously asked once, now still once) and records the same value. Measured on 50 sequential `bd list` calls: 100 -> 0 git execs (embedded and proxied-server workspaces, main checkout and worktree). TestEmbeddedReadOnlyCommandsSpawnNoGit counts git execs through a PATH shim; TestDeferredActorGitFallback pins the deferral semantics. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(git): decline in-process discovery on any config line git might read differently Review follow-ups to the in-process repository discovery. - The repository config scanner was looser than git: a config starting with a UTF-8 BOM followed by `[core] worktree = /other` made git report /other while discovery returned the cwd repository, and `[ core ]` or `!!! = x` (which git refuses) were accepted. scanGitConfig (gitconfig_linux.go) now skips a leading BOM exactly as git does and accepts only a narrow grammar: blank/comment lines, `[section]` / `[section "sub"]` headers at column 0, and `key` / `key = value` lines inside a section, with values free of backslashes and unbalanced quotes. Any other line declines to git. - Walk from getcwd(2) (syscall.Getwd), as git does, instead of os.Getwd, which trusts $PWD when it names the same inode (bind-mount aliases). - Resolve relative gitfile and commondir targets without filepath.Join's lexical Clean, so "link/.." resolves physically like git's realpath. - A mount-boundary stop reports its own reason in the not-a-repository error. - Tests: every decline case (BOM + core.worktree, malformed headers and keys, keys before a section, escapes, continuations, bare repositories, a commondir inside .git, ...) now also checks that what startup derives equals git's answer; BOM and CRLF/comment configs are equivalence cases; the no-repository case must be answered in-process instead of skipping; a $PWD alias test pins the getcwd walk. - The exec-count test drops every GIT_* variable except the config-file selectors, so a runner exporting GIT_CONFIG_PARAMETERS & co. cannot make it fail spuriously. - Comment the two places that touch the raw actor before the deferral. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(backup): decide embedded auto-backup's git-remote probe without git In an embedded workspace whose backup.enabled is unset, maybeAutoBackup asks isBackupAutoEnabled -> primeHasGitRemote after every command, reads included. That built a RepoContext (`git -C .beads rev-parse --git-common-dir`) and ran `git remote`: two git processes per read even after the startup calls were gone. The throttle cannot short-circuit it: without a remote no backup ever runs, so there is no backup state to throttle on. Both probes are now answered in-process when provable, and the subprocess remains the fallback, so the decision and every warning/notice downstream of it are unchanged: - internal/beads getGitCommonDirForPath uses git.CommonDirInProcess (the discovery walk from the given directory, git's spelling). - primeHasGitRemote uses git.HasRemoteInProcess in the same directory primeGitCmd would run git in (primeGitDir, factored out). It answers only when every config file `git remote` reads -- system (GIT_CONFIG_SYSTEM, or /etc/gitconfig and <prefix>/etc/gitconfig of the git on PATH), global (GIT_CONFIG_GLOBAL, or XDG and ~/.gitconfig) and the repository's own -- is absent or within scanGitConfig's grammar and include-free, no GIT_CONFIG_PARAMETERS/COUNT/GIT_CONFIG or discovery override is set, and no legacy .git/remotes or .git/branches entries exist. A remote seen only in a system-config candidate declines. Remote names outside [A-Za-z0-9._-] decline. Tests compare HasRemoteInProcess with `git remote` (no remote, local, worktree, submodule, remote.pushDefault only, global remote, no repo) and pin the declines (global include, malformed global, command-line config); CommonDirInProcess is compared with `git -C dir rev-parse --git-common-dir`. TestEmbeddedReadOnlyCommandsSpawnNoGit now runs with backup.enabled at its default, with and without a git remote, and still expects zero git processes for list/show. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
298 lines
10 KiB
Go
298 lines
10 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
"github.com/steveyegge/beads/internal/storage/uow"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
type deleteInput struct {
|
|
ids []string
|
|
cascade bool
|
|
force bool
|
|
dryRun bool
|
|
jsonOutput bool
|
|
quiet bool
|
|
// ifRevision is A8's --if-revision guard (beads#4682). requireSingleIfRevisionID
|
|
// refuses it alongside more than one id before gatherDeleteInput's caller ever
|
|
// reaches the role.
|
|
ifRevision *int64
|
|
}
|
|
|
|
func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error) {
|
|
in := &deleteInput{}
|
|
in.ids = append(in.ids, args...)
|
|
|
|
if fromFile, _ := cmd.Flags().GetString("from-file"); fromFile != "" {
|
|
ids, err := readIssueIDsFromFile(fromFile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("reading file: %w", err)
|
|
}
|
|
in.ids = append(in.ids, ids...)
|
|
}
|
|
in.ids = uniqueStrings(in.ids)
|
|
|
|
// --cascade IS SUPPORTED HERE NOW. This route used to refuse the flag
|
|
// outright ("delete always cascades") and hardcode Cascade: true, so on a
|
|
// team server there was no way to delete an issue without taking its
|
|
// dependents. Both routes now mean the same three things by the same flags.
|
|
in.cascade, _ = cmd.Flags().GetBool("cascade")
|
|
in.force, _ = cmd.Flags().GetBool("force")
|
|
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
|
|
in.jsonOutput = jsonOutput
|
|
in.quiet = isQuiet()
|
|
return in, nil
|
|
}
|
|
|
|
// proxiedDeleter hands back the named-row erasure surface for the proxied
|
|
// route, through the provider's OWN capability accessor.
|
|
func proxiedDeleter() (issueops.Deleter, error) {
|
|
if uowProvider == nil {
|
|
return nil, fmt.Errorf("proxied-server UOW provider not initialized")
|
|
}
|
|
source, ok := uowProvider.(uow.DeleterSource)
|
|
if !ok {
|
|
return nil, fmt.Errorf("proxied-server provider %T does not offer the Deleter accessor", uowProvider)
|
|
}
|
|
return source.Deleter()
|
|
}
|
|
|
|
// runDeleteProxiedServer is `bd delete` against a team server. The selection,
|
|
// the guard and the deletion are issueops.Deleter, the same library surface the
|
|
// direct route calls; what is left here is this route's own output, which is
|
|
// not the direct route's and is pinned separately.
|
|
func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
|
|
in, err := gatherDeleteInput(cmd, args)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
if len(in.ids) == 0 {
|
|
_ = cmd.Usage()
|
|
return HandleError("no issue IDs provided")
|
|
}
|
|
|
|
// A8 (beads#4682): parsed directly rather than inside gatherDeleteInput, so
|
|
// a refusal here returns straight through -- requireSingleIfRevisionID's
|
|
// error is already a fully reported HandleErrorRespectJSON result, and
|
|
// wrapping it a second time (the way gatherDeleteInput's other errors are
|
|
// wrapped above) would print it twice.
|
|
ifRevision, err := parseIfRevisionFlag(cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := requireSingleIfRevisionID(ifRevision, in.ids); err != nil {
|
|
return err
|
|
}
|
|
in.ifRevision = ifRevision
|
|
|
|
deleter, err := proxiedDeleter()
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
// --force is the confirmation as well as the orphan mode, exactly as on the
|
|
// direct route, so an unconfirmed run asks the role what it WOULD do.
|
|
request := issueops.DeleteRequest{
|
|
Actor: currentActor(),
|
|
IDs: in.ids,
|
|
Cascade: in.cascade,
|
|
Force: in.force,
|
|
DryRun: in.dryRun || !in.force,
|
|
ExpectedVersion: ifRevision,
|
|
}
|
|
result, err := deleter.Delete(ctx, request)
|
|
// A8 (beads#4682): a guard mismatch is reported through the dedicated
|
|
// conditional-write envelope, win or lose on DryRun alike -- it is checked
|
|
// before the "blocked" special case below because a stale token means the
|
|
// caller is not yet in a position to read a dependents refusal it may not
|
|
// even still apply to.
|
|
if ifRevision != nil && err != nil {
|
|
if reported, ok := reportIfRevisionFailure("deleting", in.ids[0], err, in.ifRevision); ok {
|
|
return reported
|
|
}
|
|
}
|
|
// THE GUARD REFUSAL IS NOT A BARE ERROR HERE. Classic renders the preview
|
|
// and THEN the refusal, which is what tells the caller both what would go
|
|
// and how to proceed; returning early would print the second half only.
|
|
// Every other error still ends the command where it happened.
|
|
var blocked *issueops.DependentsOutsideRequestError
|
|
if err != nil && !errors.As(err, &blocked) {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
|
|
if request.DryRun {
|
|
// The role answered WHAT WOULD HAPPEN; this read answers WHICH ROWS,
|
|
// which is presentation this route has always printed and which no
|
|
// result carries.
|
|
preview, previewErr := runDeleteProxiedPreviewTx(ctx, in)
|
|
if previewErr != nil {
|
|
return HandleErrorRespectJSON("%v", previewErr)
|
|
}
|
|
if err := outputDeleteProxiedPreview(in, deletePreviewResult{
|
|
preview: preview, res: result, blocked: blocked,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
if blocked != nil {
|
|
// In JSON mode the payload above already carries the refusal in its
|
|
// "error" key; emitting a second document on stdout is the bug the
|
|
// same fix on main had to correct.
|
|
if in.jsonOutput {
|
|
return &exitError{Code: 1}
|
|
}
|
|
return HandleErrorRespectJSON("%v", blocked)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
commandDidWrite.Store(true)
|
|
renderDeleteProxiedResult(in, result)
|
|
return nil
|
|
}
|
|
|
|
type deletePreviewResult struct {
|
|
preview domain.DeletePreview
|
|
res issueops.DeleteResult
|
|
// blocked carries the role's dependents refusal so the preview can render
|
|
// the way classic does: what would go first, then why it will not.
|
|
blocked *issueops.DependentsOutsideRequestError
|
|
}
|
|
|
|
// runDeleteProxiedPreviewTx reads the titles and the neighborhood one preview
|
|
// prints. It is a READ unit of work and decides nothing.
|
|
func runDeleteProxiedPreviewTx(ctx context.Context, in *deleteInput) (domain.DeletePreview, error) {
|
|
return uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeletePreview, error) {
|
|
preview, err := uw.IssueUseCase().PreviewDelete(ctx, in.ids)
|
|
if err != nil {
|
|
return domain.DeletePreview{}, fmt.Errorf("preview: %w", err)
|
|
}
|
|
return preview, nil
|
|
})
|
|
}
|
|
|
|
// outputDeleteProxiedPreview is the proxied-server preview output boundary.
|
|
// JSON takes precedence over quiet, but neither mode may serialize issue payloads.
|
|
func outputDeleteProxiedPreview(in *deleteInput, result deletePreviewResult) error {
|
|
if in.jsonOutput {
|
|
payload := map[string]any{
|
|
"would_delete": result.res.Deleted,
|
|
"dependencies_removed": result.res.Dependencies,
|
|
"labels_removed": result.res.Labels,
|
|
"events_removed": result.res.Events,
|
|
"ids": in.ids,
|
|
"not_found": result.preview.NotFound,
|
|
"connected": sortedKeys(result.preview.ConnectedIssues),
|
|
"dry_run": in.dryRun,
|
|
"cascade": in.cascade,
|
|
"would_orphan": len(result.res.Orphaned),
|
|
}
|
|
if result.blocked != nil {
|
|
payload["error"] = result.blocked.Error()
|
|
}
|
|
return outputJSON(payload)
|
|
}
|
|
if in.quiet {
|
|
return nil
|
|
}
|
|
renderDeletePreview(in, result.preview, result.res, result.blocked)
|
|
return nil
|
|
}
|
|
|
|
func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res issueops.DeleteResult, blocked *issueops.DependentsOutsideRequestError) {
|
|
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
|
|
fmt.Printf("\nIssues to delete (%d):\n", len(in.ids))
|
|
for _, id := range in.ids {
|
|
title := ""
|
|
if iss, ok := preview.Issues[id]; ok && iss != nil {
|
|
title = iss.Title
|
|
}
|
|
fmt.Printf(" %s: %s\n", id, title)
|
|
}
|
|
if in.cascade {
|
|
fmt.Printf("\n%s Cascade mode enabled - will also delete all dependent issues\n", ui.RenderWarn("⚠"))
|
|
}
|
|
if blocked != nil {
|
|
// The refusal itself says how to proceed, so the "To proceed, run"
|
|
// footer below would be a second, weaker version of the same advice.
|
|
fmt.Printf("\n%s\n", ui.RenderFail(blocked.Error()))
|
|
return
|
|
}
|
|
fmt.Printf("\nWould remove:\n")
|
|
fmt.Printf(" %d issue(s) total\n", res.Deleted)
|
|
fmt.Printf(" %d dependency link(s)\n", res.Dependencies)
|
|
fmt.Printf(" %d label(s)\n", res.Labels)
|
|
fmt.Printf(" %d event(s)\n", res.Events)
|
|
if len(res.Orphaned) > 0 {
|
|
fmt.Printf(" %s Would orphan %d issue(s): %s\n",
|
|
ui.RenderWarn("⚠"), len(res.Orphaned), strings.Join(res.Orphaned, ", "))
|
|
}
|
|
|
|
if len(preview.ConnectedIssues) > 0 {
|
|
fmt.Printf("\nConnected issues (text references may be rewritten):\n")
|
|
for _, id := range sortedKeys(preview.ConnectedIssues) {
|
|
iss := preview.ConnectedIssues[id]
|
|
title := ""
|
|
if iss != nil {
|
|
title = iss.Title
|
|
}
|
|
fmt.Printf(" %s: %s\n", id, title)
|
|
}
|
|
}
|
|
|
|
if in.dryRun {
|
|
fmt.Printf("\n(Dry-run mode - no changes made)\n")
|
|
return
|
|
}
|
|
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
|
|
if in.cascade {
|
|
fmt.Printf("To proceed with cascade deletion, run: %s\n",
|
|
ui.RenderWarn("bd delete "+strings.Join(in.ids, " ")+" --cascade --force"))
|
|
return
|
|
}
|
|
fmt.Printf("To proceed, run: %s\n",
|
|
ui.RenderWarn("bd delete "+strings.Join(in.ids, " ")+" --force"))
|
|
}
|
|
|
|
func renderDeleteProxiedResult(in *deleteInput, res issueops.DeleteResult) {
|
|
if in.jsonOutput {
|
|
_ = outputJSON(map[string]any{
|
|
"deleted": in.ids,
|
|
"deleted_count": res.Deleted,
|
|
"dependencies_removed": res.Dependencies,
|
|
"labels_removed": res.Labels,
|
|
"events_removed": res.Events,
|
|
"references_updated": res.ReferencesUpdated,
|
|
// New on this route, and new because the behavior is: `--force`
|
|
// used to cascade here, so there was never anything to orphan.
|
|
"orphaned_issues": res.Orphaned,
|
|
})
|
|
return
|
|
}
|
|
fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("✓"), res.Deleted)
|
|
fmt.Printf(" Removed %d dependency link(s)\n", res.Dependencies)
|
|
fmt.Printf(" Removed %d label(s)\n", res.Labels)
|
|
fmt.Printf(" Removed %d event(s)\n", res.Events)
|
|
fmt.Printf(" Updated text references in %d issue(s)\n", res.ReferencesUpdated)
|
|
if len(res.Orphaned) > 0 {
|
|
fmt.Printf(" %s Orphaned %d issue(s): %s\n",
|
|
ui.RenderWarn("⚠"), len(res.Orphaned), strings.Join(res.Orphaned, ", "))
|
|
}
|
|
}
|
|
|
|
func sortedKeys[V any](m map[string]V) []string {
|
|
out := make([]string, 0, len(m))
|
|
for k := range m {
|
|
out = append(out, k)
|
|
}
|
|
sort.Strings(out)
|
|
return out
|
|
}
|