* feat(label): add --prefix to bd label remove
bd list/bd ready already support --label-pattern/--label-regex for
finding issues by label shape. label remove had no equivalent for
stripping a whole label family in one call: callers had to fetch an
issue's labels themselves and issue one exact-match "bd label
remove" per matching label.
--prefix resolves the matching labels per issue (labelsWithPrefix, a
plain strings.HasPrefix filter over the labels already returned by
GetLabels) and removes them in a single transaction. Implemented for
both the embedded store path and the proxied-server (bd serve) path,
wisp-aware in the latter via workapi.GetIssueOrWisp — gc bd in Gas
Town runs proxied against a shared Dolt server, so an embedded-only
implementation would not have been usable there.
TDD: pure-function unit test (TestLabelsWithPrefix), plus embedded
and proxied CLI-level integration test cases mirroring the existing
label_remove_batch/add_list_remove conventions. Full existing
cmd/bd label suite re-run green (24/24 embedded subtests) for
regressions. The new proxied integration subtest could not be run
locally (this environment has no Docker, which the
testcontainers-go Dolt harness requires) but compiles clean under
go vet and golangci-lint and mirrors the existing, working
labelMutateProxied/runLabelListProxiedServer structure exactly.
Ref: ga-r8haw (gastownhall Gas Town city, Proposal 1).
* fix(label): address review feedback on --prefix (tense, arg validation, help text)
steveyegge's PR review (2026-08-08) asked for three small fixes before
merge, none of which the two subsequent rebases (2026-08-29, 2026-09-07)
touched:
1. Error-string tense: both label-remove failure paths (applyLabelEdit,
shared with label add; removeLabelsByPrefix) rendered "label
removed"/"added" on a FAILURE, claiming success on the very branch
that reports an error. Added labelOperationGerund() and used it on
both failure paths ("removing"/"adding"); the success-path constants
(labelOperationAdded/Removed, used by reportLabelEdit's JSON status
and human-readable verb) are untouched — they were already correct.
2. Reject --prefix combined with a label-shaped positional explicitly:
`bd label remove bd-1 stale-label --prefix x` used to hand ALL
positionals to resolveLabelIssueIDs, which (a) failed with a
confusing "could not resolve issue ID" error whose hint recommends
the exact comma-separated label syntax --prefix does not take, and
(b) left a live (if unlikely) risk that ResolvePartialID's fuzziness
could silently resolve a label-shaped string to an unrelated real
issue. Added resolveIssueIDsForPrefix, used only by the --prefix
branch of labelRemoveCmd's RunE, which fails with an explicit
"cannot combine --prefix with label arguments" instead.
3. Sharp-edge guard: per the reviewer's "at minimum" option, expanded
the --prefix flag help text to name the blast radius (a short
prefix can remove multiple unrelated label families in one
transaction) and point at `bd set-state` for state-dimension labels
(launch:, scalegate:), which --prefix bypasses without the
event-bead audit trail bd set-state provides.
TDD: new TestLabelOperationGerund (pure unit) and
label_remove_prefix_rejects_label_shaped_positional (embedded CLI
integration, mirrors the existing label_remove_prefix* subtests) —
both confirmed RED against the pre-fix code (temporarily reverted,
re-run, restored) before GREEN. Full cmd/bd label suite re-run green:
25/25 embedded subtests (24 pre-existing + 1 new), no regressions.
go vet + gofmt clean.
Ref: ga-r8haw (gastownhall Gas Town city, Proposal 1 — addresses the
2026-08-08 review verdict "MERGE AFTER FIXES (small ones)" on PR #5384).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* chore(bazel): add label_prefix_test.go to cmd/bd go_test srcs
cmd/bd/BUILD.bazel enumerates go_test srcs explicitly, so this PR's new
label_prefix_test.go was absent from the list. bazel.yml's "BUILD files in
sync" step runs `make bazel-sync` and exits 1 on any resulting drift
(.github/workflows/bazel.yml:382-406), and that job feeds pr.yml's
required CI_GATE_REQUIRED contexts (BAZEL, BAZEL_TEST, BAZEL_PURE, ...),
so the branch would red a required gate.
The bazel lane did not exist at the merge base the PR's green CI run was
built on, so no existing green covers it.
Generated with `make bazel-sync` (gazelle); re-running it is a no-op.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(label): report --prefix removals from the write result, not the pre-read set
Review fixes for the adopted PR. The gating finding is the reporting
contract on the new --prefix path.
MAJOR - removeLabelsByPrefix discarded the UpdateResult (`if _, uerr :=
lifecycle.Update(...)`) and then printed one `status: "removed"` row and one
`✓ Removed` line per entry in the pre-read snapshot, so it asserted label
removals that had not happened. That is the GH#5988 false-confirmation
defect base commit 0b9e644ba9 removed from the sibling path three commits
earlier, reintroduced on a new surface that never called the handler which
fixes it.
The path now builds a labelEditOutcome per issue from the returned
UpdateResult and reports through reportLabelEdit, the same handler the plain
path uses, so an edit that wrote nothing reports "unchanged" and the human
"was not on" line instead of a removal. Per-label attribution stays
best-effort on the same terms applyLabelEdit documents (the Get is outside
the write transaction); what is no longer possible is claiming a removal for
an edit that wrote nothing at all.
labelEditOutcome carries its own label set, because --prefix resolves a
different set per issue while applyLabelEdit repeats one caller-supplied
set. reportLabelEdit therefore reads outcome.labels and its shared `labels`
parameter is gone; it had one caller before this change and has two now.
resolveIssueIDsForPrefix collapses duplicate ids. Naming one issue twice
used to yield two "removed" rows per label deterministically - the grouping
map recorded the repeat once, but the report loops iterated the ungrouped
pairs - which is the arm that needed no concurrency to reproduce.
Minors from the same review:
- cmd/bd/label.go:159 passed the past-tense `operation` constant into an
error string, the anti-pattern this PR's own labelOperationGerund exists
to remove; the site is byte-identical at base, so the PR did not introduce
it, it shipped the remedy and applied it 13 lines below only.
- resolveIssueIDsForPrefix prefixed EVERY resolution failure with "cannot
combine --prefix with label arguments", blaming a lone typo'd id on an
argument mistake the caller did not make. The hint is speculative, so it
is now gated on len(issueIDs) > 1, matching resolveLabelIssueIDs' twin.
- The --prefix help text claimed a short prefix "removes every match in one
transaction", but a multi-issue call is one Update per issue and can land
some and fail others - the partial application applyLabelEdit documents.
Reworded to per-issue semantics, keeping the breadth caution. The same
overclaim was in this PR's own CHANGELOG entry and is reworded there too.
Tests: six subtests on TestEmbeddedLabel covering the surfaces that had no
guard - the --json row shape, the no-match empty array, two issues with
different matching sets, the duplicate-id arm, an already-removed re-run,
and the lone-bad-id message. The duplicate-id case is the pin for the
major: run against the pre-fix label.go it gets 4 rows for 2 labels. The
re-run case is not a pin. A re-run matches nothing and takes the no-match
branch before any write, so it passes against the pre-fix code too; the
"unchanged" report it cannot reach is covered through the shared handler
by the plain path's GH#5988 subtests.
Verified at this head: cmd/bd TestEmbeddedLabel 36/36 subtests and
TestProxiedServerLabel 22/22 PASS (BEADS_TEST_EMBEDDED_DOLT=1 and
BEADS_TEST_PROXIED_SERVER=1, ambient BEADS_* scrubbed), TestLabelsWithPrefix
5/5, TestLabelOperationGerund 3/3, 0 FAIL and 0 SKIP; the GH#5988
discovery-suite regression checks for the plain path
(TestDiscovery_LabelRemoveNonexistentSilentSuccess,
TestDiscovery_LabelAddDuplicateReportsAdded) PASS; build, vet and gofmt
clean; `make bazel-sync` produces no drift (no files added); and
scripts/check-doc-flags.sh passes, including the CLI docs freshness gate.
Measured complexity moved down where it changed: removeLabelsByPrefix
cyclomatic 16 to 12 and cognitive 21 to 16; reportLabelEdit is unchanged at
12 and 25.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
1083 lines
41 KiB
Go
1083 lines
41 KiB
Go
// Package main implements the bd CLI label management commands.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
var labelCmd = &cobra.Command{
|
|
Use: "label",
|
|
GroupID: "issues",
|
|
Short: "Manage issue labels",
|
|
}
|
|
|
|
// openIssueLifecycle hands back the guarded write role for whichever route this
|
|
// invocation is on, each through its own capability accessor. Neither branch
|
|
// opens a unit of work, names a use case or composes a transaction: the label
|
|
// edit is a patch, and the role is what applies it.
|
|
func openIssueLifecycle() (issueops.Lifecycle, error) {
|
|
if usesProxiedServer() {
|
|
return proxiedIssueLifecycle()
|
|
}
|
|
return store.IssueLifecycle()
|
|
}
|
|
|
|
// openIssueReader hands back the read role the same way. `bd label list` is a
|
|
// detail read whose answer is already hydrated — issueops.Reader.Get returns
|
|
// IssueDetails with Labels on it — so there is nothing here for a label-shaped
|
|
// read surface to add.
|
|
func openIssueReader() (issueops.Reader, error) {
|
|
if usesProxiedServer() {
|
|
return proxiedIssueReader()
|
|
}
|
|
return store.IssueReader()
|
|
}
|
|
|
|
// resolveLabelTarget turns one positional argument into the EXACT id the roles
|
|
// take, on whichever route this invocation is on.
|
|
//
|
|
// This is the ONE fork left in this command, and it is a fork over how a route
|
|
// REACHES the store rather than over what it does once it has an answer. The
|
|
// proxied arm is not a second policy: it is the same exact-then-wisp lookup
|
|
// internal/workapi already defines for every proxied front door, and its
|
|
// not-found is normalized to the same message shape.
|
|
func resolveLabelTarget(ctx context.Context, id string) (string, error) {
|
|
if usesProxiedServer() {
|
|
return resolveLabelTargetProxied(ctx, id)
|
|
}
|
|
return utils.ResolvePartialID(ctx, store, id)
|
|
}
|
|
|
|
// applyLabelEdit applies ONE label patch to each named issue through
|
|
// issueops.Lifecycle, and is the whole of what `bd label add` and
|
|
// `bd label remove` do differently.
|
|
//
|
|
// ONE CALL PER ISSUE, AND ONE PATCH PER CALL. Every label of the request goes
|
|
// into a single LabelPatch, so an N-issue, M-label edit is N calls rather than
|
|
// the N*M raw writes both routes used to make. The role is what makes that
|
|
// safe to say: LabelPatch applies Replace, then Add, then Remove, de-duplicates
|
|
// within an edit, drops an empty entry rather than storing it, and refuses an
|
|
// over-length label with ErrFieldTooLong before anything is written.
|
|
//
|
|
// The wisp plane needs no branch here. UpdateRequest.IssuePlaneOnly stays
|
|
// false, so the role resolves the plane INSIDE its own transaction and an
|
|
// ephemeral row's labels land in the ephemeral table — which is the four-way
|
|
// switch the proxied route used to hand-roll, and the one place a front door
|
|
// could put a wisp's label in the durable table by getting a boolean backwards.
|
|
//
|
|
// WHAT THE LOOP COSTS, stated in full because it is the one place this
|
|
// migration is not free. Both routes used to put the whole edit in ONE
|
|
// transaction — the direct one through transactHonoringAutoCommit, the proxied
|
|
// one through uow.RunTx — and a per-issue role call cannot. So for N issues:
|
|
//
|
|
// - N history entries where there was one, each naming its own issue;
|
|
// - under `--dolt-auto-commit on`, which is the DEFAULT, N Dolt version
|
|
// commits where the old transaction made one. Batch mode still makes zero,
|
|
// via issueOpsContext above, so the multiplication is only on the mode
|
|
// that was already committing per command;
|
|
// - a failure on the third id leaves the first two written, where the old
|
|
// shape rolled the good ones back with the bad one.
|
|
//
|
|
// PARTIAL APPLICATION IS ACCEPTABLE HERE, and that is an argument rather than
|
|
// a shrug. issueops.ApplyLabelPatch computes the TARGET SET and returns
|
|
// Changed false without writing when it equals the existing one, so an add and
|
|
// a remove are both idempotent: re-running the same command over the same ids
|
|
// is a no-op on the ids that already landed and does the remaining work on the
|
|
// ids that did not. A partial batch therefore CONVERGES on retry, which is the
|
|
// property that makes "landed some" a recoverable state rather than a
|
|
// corrupted one. It would not be acceptable for an edit whose replay is not
|
|
// the identity — which is exactly why this is stated here and not generalized.
|
|
//
|
|
// THE ATOMIC SHAPE IS EXPRESSIBLE ON THE FACADE ALREADY and is the named
|
|
// follow-up, not a vague later: issueops.BatchApplier.ApplyBatch takes one
|
|
// ItemUpdate per issue carrying this same IssuePatch, applies them in order and
|
|
// commits them together, so the N calls collapse back to one transaction and
|
|
// one history entry with no new role and no new request type. It is not in this
|
|
// slice because it needs a cmd/bd accessor of its own and because its end gate
|
|
// runs a hierarchy and cycle walk a label-only request has no use for.
|
|
func applyLabelEdit(ctx context.Context, issueIDs []string, labels []string, operation string) error {
|
|
lifecycle, err := openIssueLifecycle()
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
// The role creates its Dolt version commit inside the storage layer, so
|
|
// `--dolt-auto-commit batch` cannot be honored by blanking a commit message
|
|
// the way transactHonoringAutoCommit did on the old direct route: it has to
|
|
// be said on the CONTEXT. This is the one thing a command loses by moving
|
|
// off the raw transaction, and issueOpsContext is where every other
|
|
// role-routed write says it.
|
|
ctx, err = issueOpsContext(ctx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
patch := issueops.IssuePatch{}
|
|
if operation == labelOperationRemoved {
|
|
patch.Labels.Remove = labels
|
|
} else {
|
|
patch.Labels.Add = labels
|
|
}
|
|
// WHICH LABELS ACTUALLY MOVED is what the report has to say (GH#5988).
|
|
// UpdateResult.Changed is one flag per issue, which answers it exactly
|
|
// for a single label; a multi-label edit that changed something also
|
|
// needs the pre-edit set to tell its moved labels from its no-ops, so
|
|
// only that case pays for a read.
|
|
//
|
|
// THAT PRE-EDIT SET IS READ OUTSIDE THE WRITE TRANSACTION, so per-label
|
|
// attribution on the multi-label path is best-effort: a concurrent edit
|
|
// landing between the read and the Update can misattribute one label's
|
|
// line. What it cannot do is write the wrong thing — the target set is
|
|
// recomputed from current.Labels inside the write transaction
|
|
// (issueops.ApplyLabelPatch), so the stored labels, the JSON shape and
|
|
// the exit code stay correct and the state converges. A single-label
|
|
// edit is immune by construction, deriving its outcome from the write's
|
|
// own transaction. The batch shape named above closes the window
|
|
// structurally by collapsing the read and the write into one
|
|
// transaction; it is not worth a second read protocol before then.
|
|
var reader issueops.Reader
|
|
if len(labels) > 1 {
|
|
if reader, err = openIssueReader(); err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
}
|
|
outcomes := make([]labelEditOutcome, 0, len(issueIDs))
|
|
for _, issueID := range issueIDs {
|
|
var before map[string]bool
|
|
if reader != nil {
|
|
details, gerr := reader.Get(ctx, issueops.GetRequest{ID: issueID})
|
|
if gerr != nil {
|
|
return HandleErrorRespectJSON("label %s: reading labels on %s: %v",
|
|
labelOperationGerund(operation), issueID, gerr)
|
|
}
|
|
before = make(map[string]bool, len(details.Labels))
|
|
for _, label := range details.Labels {
|
|
before[label] = true
|
|
}
|
|
}
|
|
result, uerr := lifecycle.Update(ctx, issueops.UpdateRequest{
|
|
Actor: actor,
|
|
IssueID: issueID,
|
|
Patch: patch,
|
|
})
|
|
if uerr != nil {
|
|
gerund := labelOperationGerund(operation)
|
|
return HandleErrorRespectJSON("label %s: %s label '%s' on %s: %v",
|
|
gerund, gerund, strings.Join(labels, "', '"), issueID, uerr)
|
|
}
|
|
// Marked per issue rather than once after the loop: the edits land one
|
|
// call at a time, so a request that failed on its third id has still
|
|
// written its first two and the deferred commit has to know about them.
|
|
commandDidWrite.Store(true)
|
|
outcome := labelEditOutcome{issueID: issueID, labels: labels, changed: make([]bool, len(labels))}
|
|
for i, label := range labels {
|
|
switch {
|
|
case !result.Changed:
|
|
// The role wrote nothing, so no label of this edit moved.
|
|
case before == nil:
|
|
outcome.changed[i] = true
|
|
case operation == labelOperationRemoved:
|
|
outcome.changed[i] = before[label]
|
|
default:
|
|
outcome.changed[i] = !before[label]
|
|
}
|
|
}
|
|
outcomes = append(outcomes, outcome)
|
|
}
|
|
return reportLabelEdit(outcomes, operation, jsonOutput)
|
|
}
|
|
|
|
// The two label edits this command performs, spelled once. They are the words
|
|
// the JSON "status" member and the human line both carry, so they are constants
|
|
// rather than two string literals that have to agree. labelStatusUnchanged is
|
|
// the status of a label the edit left as it was: an add of a label the issue
|
|
// already had, or a remove of one it never had.
|
|
const (
|
|
labelOperationAdded = "added"
|
|
labelOperationRemoved = "removed"
|
|
labelStatusUnchanged = "unchanged"
|
|
)
|
|
|
|
// labelEditOutcome is what one issue's edit did: labels is the set the edit
|
|
// named for THAT issue and changed[i] reports whether labels[i] actually
|
|
// moved. The label set is per issue rather than one shared slice because
|
|
// --prefix resolves a different set for each issue from its own current
|
|
// labels; applyLabelEdit's fixed caller-supplied set is the degenerate case
|
|
// where every outcome repeats it.
|
|
type labelEditOutcome struct {
|
|
issueID string
|
|
labels []string
|
|
changed []bool
|
|
}
|
|
|
|
// labelOperationGerund returns the present-participle form of a
|
|
// labelOperation* constant, for error messages on a failure path. The past
|
|
// tense constants above are correct on success (that's what happened) but
|
|
// read as a false success report when the same word appears next to a
|
|
// non-nil error — "label removed: ...: connection refused" claims the removal
|
|
// that in fact just failed.
|
|
func labelOperationGerund(operation string) string {
|
|
switch operation {
|
|
case labelOperationAdded:
|
|
return "adding"
|
|
case labelOperationRemoved:
|
|
return "removing"
|
|
default:
|
|
return operation
|
|
}
|
|
}
|
|
|
|
// reportLabelEdit prints what landed, in the shape both routes have always
|
|
// printed it: one JSON row per (issue, label) pair, or one human line per issue
|
|
// naming every label that moved. A label the edit left as it was is reported
|
|
// as such — status "unchanged", and a line of its own — rather than as the
|
|
// operation, so a no-op cannot be read as a confirmation (GH#5988). It is
|
|
// still not an error: the exit code stays 0 so idempotent callers keep working.
|
|
func reportLabelEdit(outcomes []labelEditOutcome, operation string, jsonOut bool) error {
|
|
if jsonOut {
|
|
// One row per (issue, label) pair; the hint is the one-label-per-issue
|
|
// floor rather than an exact count, since each outcome carries its own
|
|
// label set and append grows from there.
|
|
results := make([]map[string]interface{}, 0, len(outcomes))
|
|
for _, outcome := range outcomes {
|
|
for i, label := range outcome.labels {
|
|
status := operation
|
|
if !outcome.changed[i] {
|
|
status = labelStatusUnchanged
|
|
}
|
|
results = append(results, map[string]interface{}{
|
|
"status": status,
|
|
"issue_id": outcome.issueID,
|
|
"label": label,
|
|
})
|
|
}
|
|
}
|
|
return outputJSON(results)
|
|
}
|
|
verb, prep := "Added", "to"
|
|
if operation == labelOperationRemoved {
|
|
verb, prep = "Removed", "from"
|
|
}
|
|
for _, outcome := range outcomes {
|
|
var moved, unmoved []string
|
|
for i, label := range outcome.labels {
|
|
if outcome.changed[i] {
|
|
moved = append(moved, label)
|
|
} else {
|
|
unmoved = append(unmoved, label)
|
|
}
|
|
}
|
|
if len(moved) > 0 {
|
|
fmt.Printf("%s %s %s '%s' %s %s\n", ui.RenderPass("✓"), verb,
|
|
labelNoun(moved, "label", "labels"), strings.Join(moved, "', '"), prep, outcome.issueID)
|
|
}
|
|
if len(unmoved) == 0 {
|
|
continue
|
|
}
|
|
unmovedDesc := strings.Join(unmoved, "', '")
|
|
if operation == labelOperationRemoved {
|
|
fmt.Printf("%s %s '%s' %s not on %s\n", ui.RenderAccent("•"),
|
|
labelNoun(unmoved, "Label", "Labels"), unmovedDesc, labelNoun(unmoved, "was", "were"), outcome.issueID)
|
|
} else {
|
|
fmt.Printf("%s %s already has %s '%s'\n", ui.RenderAccent("•"),
|
|
outcome.issueID, labelNoun(unmoved, "label", "labels"), unmovedDesc)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// labelNoun picks the singular or plural word for a list of labels.
|
|
func labelNoun(labels []string, singular, plural string) string {
|
|
if len(labels) > 1 {
|
|
return plural
|
|
}
|
|
return singular
|
|
}
|
|
|
|
// removeLabelsByPrefix removes every label starting with prefix from each
|
|
// issue in issueIDs, through issueops.Lifecycle — the same role
|
|
// applyLabelEdit uses, so the events journal and both storage routes see this
|
|
// edit the same way they see a plain `label remove`. Unlike applyLabelEdit
|
|
// (which applies one fixed, caller-supplied label set to every issue), the
|
|
// label set here is resolved per-issue from that issue's current labels via
|
|
// issueops.Reader, since different issues may carry different prefix-matching
|
|
// labels — so the loop is one Get plus one Update per issue rather than one
|
|
// shared patch for all of them.
|
|
//
|
|
// The report goes through reportLabelEdit, the same handler the plain path
|
|
// uses, so a removal this call did not actually make is reported as
|
|
// "unchanged" rather than as a removal (GH#5988). Reimplementing the report
|
|
// here is what let the pre-review version of this function claim removals off
|
|
// its pre-read snapshot.
|
|
func removeLabelsByPrefix(ctx context.Context, issueIDs []string, prefix string, jsonOut bool) error {
|
|
reader, err := openIssueReader()
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
// Grouped per issue from the start: one LabelPatch.Remove applies every
|
|
// matching label for that issue in one Update, which is applyLabelEdit's
|
|
// "one call per issue, one patch per call" contract. issueIDs carries no
|
|
// duplicates (resolveIssueIDsForPrefix collapses them), so this is one Get
|
|
// and one Update per distinct issue named on the command line.
|
|
type prefixTarget struct {
|
|
issueID string
|
|
labels []string
|
|
}
|
|
var targets []prefixTarget
|
|
for _, issueID := range issueIDs {
|
|
details, gerr := reader.Get(ctx, issueops.GetRequest{ID: issueID})
|
|
if gerr != nil {
|
|
return HandleErrorRespectJSON("getting labels for %s: %v", issueID, gerr)
|
|
}
|
|
if matched := labelsWithPrefix(details.Labels, prefix); len(matched) > 0 {
|
|
targets = append(targets, prefixTarget{issueID: issueID, labels: matched})
|
|
}
|
|
}
|
|
if len(targets) == 0 {
|
|
if jsonOut {
|
|
return outputJSON([]map[string]interface{}{})
|
|
}
|
|
fmt.Printf("No labels matching prefix '%s' found\n", prefix)
|
|
return nil
|
|
}
|
|
|
|
lifecycle, err := openIssueLifecycle()
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
ctx, err = issueOpsContext(ctx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
outcomes := make([]labelEditOutcome, 0, len(targets))
|
|
for _, target := range targets {
|
|
result, uerr := lifecycle.Update(ctx, issueops.UpdateRequest{
|
|
Actor: actor,
|
|
IssueID: target.issueID,
|
|
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{Remove: target.labels}},
|
|
})
|
|
if uerr != nil {
|
|
return HandleErrorRespectJSON("label removing (prefix): %s: %v", target.issueID, uerr)
|
|
}
|
|
commandDidWrite.Store(true)
|
|
// WHICH LABELS ACTUALLY MOVED, derived from the write rather than from
|
|
// the Get that chose them. Every label in target.labels was on the
|
|
// issue when it was read, so UpdateResult.Changed answers for the
|
|
// whole set at once: false means the role wrote nothing and none of
|
|
// them moved. Per-label attribution is best-effort for the reason
|
|
// applyLabelEdit states at length — the read is outside the write
|
|
// transaction — but the claim that cannot be made any more is
|
|
// "removed" for an edit that wrote nothing at all.
|
|
changed := make([]bool, len(target.labels))
|
|
for i := range changed {
|
|
changed[i] = result.Changed
|
|
}
|
|
outcomes = append(outcomes, labelEditOutcome{
|
|
issueID: target.issueID,
|
|
labels: target.labels,
|
|
changed: changed,
|
|
})
|
|
}
|
|
return reportLabelEdit(outcomes, labelOperationRemoved, jsonOut)
|
|
}
|
|
|
|
// parseLabelArgs splits positional args into issue IDs and labels. The final
|
|
// arg is the label spec; commas separate multiple labels ("label1,label2").
|
|
func parseLabelArgs(args []string) (issueIDs []string, labels []string) {
|
|
labels = splitLabelArg(args[len(args)-1])
|
|
issueIDs = args[:len(args)-1]
|
|
return
|
|
}
|
|
|
|
// splitLabelArg splits a comma-separated label argument into individual
|
|
// labels, trimming whitespace and dropping empty entries. Matches the
|
|
// comma-separated convention of bd create --labels.
|
|
func splitLabelArg(arg string) []string {
|
|
parts := strings.Split(arg, ",")
|
|
labels := make([]string, 0, len(parts))
|
|
for _, part := range parts {
|
|
if part = strings.TrimSpace(part); part != "" {
|
|
labels = append(labels, part)
|
|
}
|
|
}
|
|
return labels
|
|
}
|
|
|
|
// labelsWithPrefix returns the subset of labels whose name starts with
|
|
// prefix, preserving input order.
|
|
func labelsWithPrefix(labels []string, prefix string) []string {
|
|
var matched []string
|
|
for _, label := range labels {
|
|
if strings.HasPrefix(label, prefix) {
|
|
matched = append(matched, label)
|
|
}
|
|
}
|
|
return matched
|
|
}
|
|
|
|
// resolveLabelIssueIDs resolves every issue-ID positional arg to the EXACT id
|
|
// the role takes, failing hard on the first arg that doesn't resolve.
|
|
//
|
|
// Resolution stays a front-door job and does not move behind the role:
|
|
// GetRequest.ID and UpdateRequest.IssueID are both exact by contract, for the
|
|
// reason those docs give — an affordance that can resolve to a different issue
|
|
// than the caller named has no place on a contract two front doors share. This
|
|
// is therefore the ONE thing that still forks by route, and it forks on how a
|
|
// route reaches the store rather than on what it then does with the answer.
|
|
//
|
|
// Labels come last on the command line, so when several ID-position args fail
|
|
// the caller almost certainly passed labels space-separated ("bd label add
|
|
// bd-123 a b c"); the error hints at the comma-separated form instead of
|
|
// silently skipping the bad args (bd-vu5kv).
|
|
func resolveLabelIssueIDs(ctx context.Context, subcommand string, issueIDs []string) ([]string, error) {
|
|
resolved := make([]string, 0, len(issueIDs))
|
|
for _, id := range issueIDs {
|
|
fullID, err := resolveLabelTarget(ctx, id)
|
|
if err != nil {
|
|
if len(issueIDs) > 1 {
|
|
return nil, fmt.Errorf("resolving issue ID %q: %w (to %s multiple labels, pass one comma-separated argument: bd label %s <issue-id> label1,label2)",
|
|
id, err, subcommand, subcommand)
|
|
}
|
|
return nil, fmt.Errorf("resolving issue ID %q: %w", id, err)
|
|
}
|
|
resolved = append(resolved, fullID)
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
// resolveIssueIDsForPrefix resolves every positional arg to an issue ID for
|
|
// the --prefix form of `bd label remove`. Unlike the plain add/remove path,
|
|
// --prefix takes no trailing label argument — every positional is an issue
|
|
// ID — so a positional that fails to resolve is reported as a likely
|
|
// mixed-up label argument (e.g. a caller who reflexively kept the old
|
|
// trailing-label habit: `bd label remove bd-1 stale-label --prefix x`)
|
|
// rather than with resolveLabelIssueIDs' "pass one comma-separated argument"
|
|
// hint, which recommends exactly the label-argument syntax --prefix does not
|
|
// take and would only compound the confusion.
|
|
//
|
|
// That hint is SPECULATIVE, so it is gated on the same condition as the twin's:
|
|
// only a line carrying more than one positional can plausibly have ended with
|
|
// a stray label. A single positional that does not resolve is just a bad issue
|
|
// ID — usually a typo or a deleted issue — and blaming an argument mistake the
|
|
// caller did not make sends them looking for the wrong thing.
|
|
//
|
|
// Duplicate ids collapse. Two positionals naming the same issue (directly or
|
|
// through different resolvable forms) are one issue to remove labels from, and
|
|
// leaving the repeat in would make the caller pay a second Get and read a
|
|
// second report line for one edit.
|
|
func resolveIssueIDsForPrefix(ctx context.Context, issueIDs []string) ([]string, error) {
|
|
resolved := make([]string, 0, len(issueIDs))
|
|
seen := make(map[string]bool, len(issueIDs))
|
|
for _, id := range issueIDs {
|
|
fullID, err := resolveLabelTarget(ctx, id)
|
|
if err != nil {
|
|
if len(issueIDs) > 1 {
|
|
return nil, fmt.Errorf("cannot combine --prefix with label arguments: %q is not an issue ID: %w", id, err)
|
|
}
|
|
return nil, fmt.Errorf("resolving issue ID %q: %w", id, err)
|
|
}
|
|
if seen[fullID] {
|
|
continue
|
|
}
|
|
seen[fullID] = true
|
|
resolved = append(resolved, fullID)
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
//nolint:dupl // labelAddCmd and labelRemoveCmd are similar but serve different operations
|
|
var labelAddCmd = &cobra.Command{
|
|
Use: "add [issue-id...] [label[,label...]]",
|
|
Short: "Add one or more labels to one or more issues",
|
|
Long: "Add labels to issues. Issue IDs come first; the final argument is the label. Pass multiple labels comma-separated: bd label add bd-123 label1,label2",
|
|
Args: cobra.MinimumNArgs(2),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("label add")
|
|
|
|
evt := metrics.NewCommandEvent("label-add")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
return runLabelAdd(rootCtx, args)
|
|
},
|
|
}
|
|
|
|
//nolint:dupl // labelRemoveCmd and labelAddCmd are similar but serve different operations
|
|
var labelRemoveCmd = &cobra.Command{
|
|
Use: "remove [issue-id...] [label[,label...]]",
|
|
Short: "Remove one or more labels from one or more issues",
|
|
Long: "Remove labels from issues. Issue IDs come first; the final argument is the label. Pass multiple labels comma-separated: bd label remove bd-123 label1,label2\n\n" +
|
|
"With --prefix, no label argument is needed: every label on the given issue(s) starting with the prefix is removed, e.g. bd label remove bd-123 --prefix pool:refused:",
|
|
Args: func(cmd *cobra.Command, args []string) error {
|
|
prefix, _ := cmd.Flags().GetString("prefix")
|
|
if prefix != "" {
|
|
return cobra.MinimumNArgs(1)(cmd, args)
|
|
}
|
|
return cobra.MinimumNArgs(2)(cmd, args)
|
|
},
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("label remove")
|
|
|
|
evt := metrics.NewCommandEvent("label-remove")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
prefix, _ := cmd.Flags().GetString("prefix")
|
|
if prefix != "" {
|
|
issueIDs, err := resolveIssueIDsForPrefix(rootCtx, args)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
return removeLabelsByPrefix(rootCtx, issueIDs, prefix, jsonOutput)
|
|
}
|
|
return runLabelRemove(rootCtx, args)
|
|
},
|
|
}
|
|
var labelListCmd = &cobra.Command{
|
|
Use: "list [issue-id]",
|
|
Short: "List labels for an issue",
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("label-list")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
return runLabelList(rootCtx, args)
|
|
},
|
|
}
|
|
|
|
// labelListAllSearcher is the whole storage surface `bd label list-all`
|
|
// needs. SearchIssues already hydrates Issue.Labels in bulk; omitting
|
|
// GetLabels here keeps the per-issue lookup — one extra connection and
|
|
// transaction per issue in embedded mode — unreachable (GH#5325).
|
|
type labelListAllSearcher interface {
|
|
SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error)
|
|
}
|
|
|
|
func countLabelsAcrossIssues(ctx context.Context, s labelListAllSearcher) (map[string]int, error) {
|
|
issues, err := s.SearchIssues(ctx, "", types.IssueFilter{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
labelCounts := make(map[string]int)
|
|
for _, issue := range issues {
|
|
for _, label := range issue.Labels {
|
|
labelCounts[label]++
|
|
}
|
|
}
|
|
return labelCounts, nil
|
|
}
|
|
|
|
var labelListAllCmd = &cobra.Command{
|
|
Use: "list-all",
|
|
Short: "List all unique labels in the database",
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("label-list-all")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if usesProxiedServer() {
|
|
return runLabelListAllProxiedServer(rootCtx)
|
|
}
|
|
|
|
labelCounts, err := countLabelsAcrossIssues(rootCtx, store)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
type labelInfo struct {
|
|
Label string `json:"label"`
|
|
Count int `json:"count"`
|
|
}
|
|
if len(labelCounts) == 0 {
|
|
if jsonOutput {
|
|
return outputJSON([]labelInfo{})
|
|
}
|
|
fmt.Println("\nNo labels found in database")
|
|
return nil
|
|
}
|
|
labels := make([]string, 0, len(labelCounts))
|
|
for label := range labelCounts {
|
|
labels = append(labels, label)
|
|
}
|
|
sort.Strings(labels)
|
|
if jsonOutput {
|
|
result := make([]labelInfo, 0, len(labels))
|
|
for _, label := range labels {
|
|
result = append(result, labelInfo{
|
|
Label: label,
|
|
Count: labelCounts[label],
|
|
})
|
|
}
|
|
return outputJSON(result)
|
|
}
|
|
fmt.Printf("\n%s All labels (%d unique):\n", ui.RenderAccent("🏷"), len(labels))
|
|
maxLen := 0
|
|
for _, label := range labels {
|
|
if len(label) > maxLen {
|
|
maxLen = len(label)
|
|
}
|
|
}
|
|
for _, label := range labels {
|
|
padding := strings.Repeat(" ", maxLen-len(label))
|
|
fmt.Printf(" %s%s (%d issues)\n", label, padding, labelCounts[label])
|
|
}
|
|
fmt.Println()
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var labelPropagateCmd = &cobra.Command{
|
|
Use: "propagate [parent-id] [label]",
|
|
Short: "Propagate a label from a parent issue to all its children",
|
|
Long: "Push a label from a parent down to all direct children that don't already have it. Useful for applying branch: labels across an epic's subtasks.",
|
|
Args: cobra.ExactArgs(2),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("label propagate")
|
|
|
|
evt := metrics.NewCommandEvent("label-propagate")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if usesProxiedServer() {
|
|
return runLabelPropagateProxiedServer(rootCtx, args)
|
|
}
|
|
|
|
ctx := rootCtx
|
|
|
|
parentID, err := utils.ResolvePartialID(ctx, store, args[0])
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("resolving parent %s: %v", args[0], err)
|
|
}
|
|
label := strings.TrimSpace(args[1])
|
|
if label == "" {
|
|
return HandleErrorRespectJSON("label cannot be empty")
|
|
}
|
|
|
|
if strings.HasPrefix(label, "provides:") {
|
|
return HandleErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:"))
|
|
}
|
|
|
|
children, err := store.SearchIssues(ctx, "", types.IssueFilter{ParentID: &parentID})
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("searching children of %s: %v", parentID, err)
|
|
}
|
|
|
|
if len(children) == 0 {
|
|
if jsonOutput {
|
|
return outputJSON([]map[string]interface{}{})
|
|
}
|
|
fmt.Printf("No children found for %s\n", parentID)
|
|
return nil
|
|
}
|
|
|
|
commitMsg := fmt.Sprintf("bd: propagate label '%s' from %s to %d children", label, parentID, len(children))
|
|
err = transactHonoringAutoCommit(ctx, store, commitMsg, func(tx storage.Transaction) error {
|
|
for _, child := range children {
|
|
if err := tx.AddLabel(ctx, child.ID, label, actor); err != nil {
|
|
return fmt.Errorf("add label '%s' on %s: %w", label, child.ID, err)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("label propagate: %v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
results := make([]map[string]interface{}, 0, len(children))
|
|
for _, child := range children {
|
|
results = append(results, map[string]interface{}{
|
|
"status": "propagated",
|
|
"issue_id": child.ID,
|
|
"label": label,
|
|
})
|
|
}
|
|
return outputJSON(results)
|
|
}
|
|
for _, child := range children {
|
|
fmt.Printf("%s Propagated label '%s' to %s\n", ui.RenderPass("✓"), label, child.ID)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// labelRenamePreviewLimit caps how many issues a `--dry-run` blast-radius
|
|
// preview names before collapsing the rest into a count.
|
|
const labelRenamePreviewLimit = 10
|
|
|
|
var labelRenameCmd = &cobra.Command{
|
|
Use: "rename <old-label> <new-label>",
|
|
Short: "Rename a label across every issue and wisp that carries it",
|
|
Long: "Rename a label everywhere it appears. An issue that already carries " +
|
|
"the new label keeps it and drops the old one instead of erroring - a " +
|
|
"merge, reported honestly (the write path measures merged from what " +
|
|
"the insert actually affected, never from a snapshot check, so its " +
|
|
"count is correct under concurrent writes). Pass --dry-run to preview " +
|
|
"the blast radius (a count and the first issues) without writing " +
|
|
"anything; the preview's merged count is a plain snapshot intersection " +
|
|
"of two separate reads, so treat it as an estimate, not the number the " +
|
|
"rename itself will report.",
|
|
Args: cobra.ExactArgs(2),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
|
if !dryRun {
|
|
CheckReadonly("label rename")
|
|
}
|
|
|
|
evt := metrics.NewCommandEvent("label-rename")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
return runLabelRename(rootCtx, args, dryRun)
|
|
},
|
|
}
|
|
|
|
// validateLabelRename trims and checks the two rename arguments, returning
|
|
// the trimmed labels or the refusal a caller should surface. It is a pure
|
|
// function so the refusal rules are testable without a store.
|
|
func validateLabelRename(rawOld, rawNew string) (oldLabel, newLabel string, err error) {
|
|
oldLabel = strings.TrimSpace(rawOld)
|
|
newLabel = strings.TrimSpace(rawNew)
|
|
if oldLabel == "" || newLabel == "" {
|
|
return "", "", fmt.Errorf("label cannot be empty")
|
|
}
|
|
if oldLabel == newLabel {
|
|
return "", "", fmt.Errorf("cannot rename label '%s' to itself", oldLabel)
|
|
}
|
|
// Same reserved-prefix refusal runLabelAdd and label propagate apply: a
|
|
// rename is effectively an add of newLabel, and touching oldLabel would
|
|
// let a caller strip a 'provides:' capability outside 'bd ship'.
|
|
for _, label := range [2]string{oldLabel, newLabel} {
|
|
if strings.HasPrefix(label, "provides:") {
|
|
return "", "", fmt.Errorf("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship' instead")
|
|
}
|
|
}
|
|
return oldLabel, newLabel, nil
|
|
}
|
|
|
|
func runLabelRename(ctx context.Context, args []string, dryRun bool) error {
|
|
oldLabel, newLabel, err := validateLabelRename(args[0], args[1])
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
warnLabelsContainingWhitespace([]string{oldLabel, newLabel})
|
|
|
|
if dryRun {
|
|
return runLabelRenameDryRun(ctx, oldLabel, newLabel)
|
|
}
|
|
|
|
var renamed, merged int
|
|
if usesProxiedServer() {
|
|
renamed, merged, err = runLabelRenameProxiedServer(ctx, oldLabel, newLabel)
|
|
} else {
|
|
renamed, merged, _, err = store.RenameLabel(ctx, oldLabel, newLabel, actor)
|
|
}
|
|
// Recorded from renamed>0 BEFORE the error check: a rename can commit its
|
|
// SQL side and still return a non-nil err (e.g. the Dolt publication step
|
|
// failing after the working-set write landed), and the caller's deferred
|
|
// commit needs to know a write happened either way.
|
|
if renamed > 0 {
|
|
commandDidWrite.Store(true)
|
|
}
|
|
if err != nil {
|
|
// The counts are assigned INSIDE the transaction closure on both
|
|
// routes (label_proxied_server.go RunTx, dolt/labels.go
|
|
// withRetryTx), so a Commit failure or retry exhaustion returns
|
|
// them still holding the rolled-back attempt's numbers - nothing
|
|
// landed. Only doltAddAndCommit failing after the SQL tx committed
|
|
// is a genuine partial, and renamed>0 cannot discriminate the two.
|
|
// Report an UPPER BOUND rather than assert a write that may not
|
|
// have happened; commandDidWrite above shares the premise but is
|
|
// fail-safe in the other direction, this message is not.
|
|
if renamed > 0 {
|
|
return HandleErrorRespectJSON("%s", labelRenamePartialFailureMessage(renamed, merged, err))
|
|
}
|
|
return HandleErrorRespectJSON("label rename: %v", err)
|
|
}
|
|
return reportLabelRename(oldLabel, newLabel, renamed, merged, jsonOutput)
|
|
}
|
|
|
|
// labelRenameCandidatesProxied is the read-only counterpart of
|
|
// runLabelRenameProxiedServer, used only by --dry-run: two label searches, no
|
|
// write. Kept separate from the write path so a dry-run can never reach a
|
|
// uow.RunTx call.
|
|
func labelRenameCandidatesProxied(ctx context.Context, oldLabel, newLabel string) (oldIssues, newIssues []*types.Issue, err error) {
|
|
uw, err := proxiedOpenReadUOW(ctx)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
defer uw.Close(ctx)
|
|
|
|
oldPage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Labels: []string{oldLabel}})
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("searching issues with label %q: %w", oldLabel, err)
|
|
}
|
|
if len(oldPage.Items) == 0 {
|
|
return nil, nil, nil
|
|
}
|
|
newPage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Labels: []string{newLabel}})
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("searching issues with label %q: %w", newLabel, err)
|
|
}
|
|
return oldPage.Items, newPage.Items, nil
|
|
}
|
|
|
|
func runLabelRenameDryRun(ctx context.Context, oldLabel, newLabel string) error {
|
|
var (
|
|
oldIssues, newIssues []*types.Issue
|
|
err error
|
|
)
|
|
if usesProxiedServer() {
|
|
oldIssues, newIssues, err = labelRenameCandidatesProxied(ctx, oldLabel, newLabel)
|
|
} else {
|
|
oldIssues, err = store.GetIssuesByLabel(ctx, oldLabel)
|
|
if err == nil {
|
|
newIssues, err = store.GetIssuesByLabel(ctx, newLabel)
|
|
}
|
|
}
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("label rename --dry-run: %v", err)
|
|
}
|
|
|
|
// A preview-only snapshot intersection of two independent reads, NOT the
|
|
// write path's measured count: renameLabelInPlane derives merged from
|
|
// what its INSERT IGNORE actually affected, specifically to avoid the
|
|
// schedule-dependent count a check-then-insert shape used to produce
|
|
// under a concurrent AddLabel/RemoveLabel between the two reads (see the
|
|
// comment on that function). This dry-run has no insert to measure
|
|
// against, so it falls back to exactly that check-then-count shape - an
|
|
// acceptable estimate for a preview, but callers must not treat it as
|
|
// authoritative. The flag help and command Long text say so too.
|
|
alreadyNew := make(map[string]struct{}, len(newIssues))
|
|
for _, issue := range newIssues {
|
|
alreadyNew[issue.ID] = struct{}{}
|
|
}
|
|
merged := 0
|
|
for _, issue := range oldIssues {
|
|
if _, ok := alreadyNew[issue.ID]; ok {
|
|
merged++
|
|
}
|
|
}
|
|
|
|
if jsonOutput {
|
|
preview := make([]map[string]interface{}, 0, len(oldIssues))
|
|
for _, issue := range oldIssues {
|
|
preview = append(preview, map[string]interface{}{
|
|
"issue_id": issue.ID,
|
|
"title": issue.Title,
|
|
})
|
|
}
|
|
return outputJSON(map[string]interface{}{
|
|
"dry_run": true,
|
|
"old_label": oldLabel,
|
|
"new_label": newLabel,
|
|
"count": len(oldIssues),
|
|
"merged": merged,
|
|
"issues": preview,
|
|
})
|
|
}
|
|
|
|
if len(oldIssues) == 0 {
|
|
fmt.Printf("No issues found with label '%s'\n", oldLabel)
|
|
return nil
|
|
}
|
|
fmt.Printf("Would rename label '%s' to '%s': %d issues", oldLabel, newLabel, len(oldIssues))
|
|
if merged > 0 {
|
|
fmt.Printf(" (%d already have '%s')", merged, newLabel)
|
|
}
|
|
fmt.Println()
|
|
limit := len(oldIssues)
|
|
if limit > labelRenamePreviewLimit {
|
|
limit = labelRenamePreviewLimit
|
|
}
|
|
for _, issue := range oldIssues[:limit] {
|
|
fmt.Printf(" %s %s\n", issue.ID, issue.Title)
|
|
}
|
|
if len(oldIssues) > limit {
|
|
fmt.Printf(" ... and %d more\n", len(oldIssues)-limit)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// labelRenamePartialFailureMessage phrases a failed rename as an UPPER BOUND.
|
|
// Both routes assign the counts inside the transaction closure, so on a Commit
|
|
// failure or retry exhaustion they still hold the rolled-back attempt's numbers
|
|
// and nothing landed; only doltAddAndCommit failing after the SQL transaction
|
|
// committed is a genuine partial, and renamed > 0 cannot tell the two apart.
|
|
// Every number in the sentence is therefore hedged - a definite count here would
|
|
// assert a write that may never have happened.
|
|
func labelRenamePartialFailureMessage(renamed, merged int, err error) string {
|
|
return fmt.Sprintf("label rename: up to %d issue(s) (of which up to %d merged) may have been renamed before failing: %v",
|
|
renamed, merged, err)
|
|
}
|
|
|
|
// reportLabelRename prints what a (non-dry-run) rename landed: an honest
|
|
// zero-issues no-op, or the count plus how many of those were merges.
|
|
func reportLabelRename(oldLabel, newLabel string, renamed, merged int, jsonOut bool) error {
|
|
if jsonOut {
|
|
return outputJSON(map[string]interface{}{
|
|
"status": "renamed",
|
|
"old_label": oldLabel,
|
|
"new_label": newLabel,
|
|
"renamed": renamed,
|
|
"merged": merged,
|
|
})
|
|
}
|
|
if renamed == 0 {
|
|
fmt.Printf("No issues found with label '%s'\n", oldLabel)
|
|
return nil
|
|
}
|
|
noun := "issue"
|
|
if renamed != 1 {
|
|
noun = "issues"
|
|
}
|
|
fmt.Printf("Renamed label '%s' to '%s': %d %s", oldLabel, newLabel, renamed, noun)
|
|
if merged > 0 {
|
|
fmt.Printf(" (%d already had '%s')", merged, newLabel)
|
|
}
|
|
fmt.Println()
|
|
return nil
|
|
}
|
|
|
|
func init() {
|
|
// Issue ID completions
|
|
labelAddCmd.ValidArgsFunction = issueIDCompletion
|
|
labelRemoveCmd.ValidArgsFunction = issueIDCompletion
|
|
labelListCmd.ValidArgsFunction = issueIDCompletion
|
|
labelPropagateCmd.ValidArgsFunction = issueIDCompletion
|
|
|
|
labelRemoveCmd.Flags().String("prefix", "", "Remove every label matching this prefix instead of an exact label (e.g., 'pool:refused:' removes all pool:refused:* labels). No label positional argument is needed when set. CAUTION: a short prefix removes every match on an issue in a single edit, including labels you may not have meant to touch (e.g. --prefix t removes both 'tier:opus' and 'test-needed') — check `bd label list <issue-id>` first if unsure. State-dimension labels (e.g. 'launch:', 'scalegate:') should move via `bd set-state` instead, which this flag bypasses without its event-bead audit trail.")
|
|
|
|
labelRenameCmd.Flags().Bool("dry-run", false, "Preview the blast radius without renaming anything (merged count is a snapshot intersection, not authoritative - see --help)")
|
|
|
|
labelCmd.AddCommand(labelAddCmd)
|
|
labelCmd.AddCommand(labelRemoveCmd)
|
|
labelCmd.AddCommand(labelListCmd)
|
|
labelCmd.AddCommand(labelListAllCmd)
|
|
labelCmd.AddCommand(labelPropagateCmd)
|
|
labelCmd.AddCommand(labelRenameCmd)
|
|
rootCmd.AddCommand(labelCmd)
|
|
}
|
|
|
|
// runLabelAdd, runLabelRemove and runLabelList are ONE body each, for both
|
|
// routes. The route fork is gone from these three commands: what used to be an
|
|
// `if usesProxiedServer() { return run…ProxiedServer(...) }` in the middle of a
|
|
// RunE — with a second, separately-maintained implementation on the other side
|
|
// of it — is now a fork inside resolveLabelTarget and inside the accessor, and
|
|
// both arms end at the same role.
|
|
func runLabelAdd(ctx context.Context, args []string) error {
|
|
issueIDs, labels := parseLabelArgs(args)
|
|
if len(labels) == 0 {
|
|
return HandleErrorRespectJSON("label cannot be empty")
|
|
}
|
|
// The reserved-prefix refusal is checked BEFORE anything is resolved, and
|
|
// that ORDER CHANGED: the direct route used to resolve every id first and
|
|
// refuse the label afterwards. A caller that both typo'd an id and reached
|
|
// for a reserved label is now told about the label — the one of the two
|
|
// this command will never accept, at any id — rather than being sent to fix
|
|
// an id that was never going to be labeled. The proxied route already
|
|
// checked in this order, so this is the two routes agreeing on the earlier
|
|
// of the two answers rather than a new rule.
|
|
for _, label := range labels {
|
|
if strings.HasPrefix(label, "provides:") {
|
|
return HandleErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:"))
|
|
}
|
|
}
|
|
// splitLabelArg already trims and drops empties, so this route never stored
|
|
// the untrimmed class. What it could not tell a caller is that
|
|
// `bd label add bd-1 'theme:a theme:b'` is ONE label — the same silent
|
|
// miscount #5812 is about, reached by a different command. Warning here
|
|
// keeps the whole CLI saying the same thing about the same input.
|
|
warnLabelsContainingWhitespace(labels)
|
|
issueIDs, err := resolveLabelIssueIDs(ctx, "add", issueIDs)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
return applyLabelEdit(ctx, issueIDs, labels, labelOperationAdded)
|
|
}
|
|
|
|
func runLabelRemove(ctx context.Context, args []string) error {
|
|
issueIDs, labels := parseLabelArgs(args)
|
|
if len(labels) == 0 {
|
|
return HandleErrorRespectJSON("label cannot be empty")
|
|
}
|
|
issueIDs, err := resolveLabelIssueIDs(ctx, "remove", issueIDs)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
return applyLabelEdit(ctx, issueIDs, labels, labelOperationRemoved)
|
|
}
|
|
|
|
func runLabelList(ctx context.Context, args []string) error {
|
|
issueID, err := resolveLabelTarget(ctx, args[0])
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("resolving %s: %v", args[0], err)
|
|
}
|
|
reader, err := openIssueReader()
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
// The detail read already carries the labels, sorted, for whichever
|
|
// plane holds the row — so there is no label-shaped read here, and no
|
|
// wisp branch either.
|
|
details, err := reader.Get(ctx, issueops.GetRequest{ID: issueID})
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
labels := details.Labels
|
|
if jsonOutput {
|
|
if labels == nil {
|
|
labels = []string{}
|
|
}
|
|
return outputJSON(labels)
|
|
}
|
|
if len(labels) == 0 {
|
|
fmt.Printf("\n%s has no labels\n", issueID)
|
|
return nil
|
|
}
|
|
fmt.Printf("\n%s Labels for %s:\n", ui.RenderAccent("🏷"), issueID)
|
|
for _, label := range labels {
|
|
fmt.Printf(" - %s\n", label)
|
|
}
|
|
fmt.Println()
|
|
return nil
|
|
}
|