beads/cmd/bd/create_input.go
postoso de8567eaae
fix(cli): --until, --defer and --due rejections name the supported unit set (#5718)
* fix(cli): --until rejection names the supported unit set

bd defer --until "+3mo" failed with: invalid --until format "+3mo".
Examples: +1h, tomorrow, next monday, 2025-01-15

The compact-duration parser accepts h, d, w, m and y, so "+3w" and "+3m"
both work. The message jumped from a single hours example straight to
absolute dates and never stated the unit set, so a caller who wanted three
months had to find "+3m" by trying units one at a time.

Months were already supported, spelled "+3m" (internal/timeparsing
applyDuration case "m" is AddDate(0, amount, 0)). This is a message change
only, parsing behavior is untouched.

The regression test pins the message to the parser it describes: every unit
the hint names must parse, and the real failure path must put the unit set
on stderr rather than only the constant being well formed.

* fix(cli): share the --until unit hint with --defer and --due

bd defer --until was not the only door onto ParseRelativeTime. bd create
--defer, bd update --defer and both --due flags still printed "Examples:
+1h, tomorrow, next monday, 2025-01-15", which names one example per
category and leaves a caller who typed +3mo guessing which units exist.

Reuse deferUntilFormatHint at the eight remaining sites, covering the
direct create and update paths and their proxied-input twins. Message
only, the parser is untouched.

A source guard pins the uniformity, because a site that re-inlines its own
example list still passes every call-level test. The proxied-input paths
also get a behavioural test that the unit set reaches the caller.

* fix(cli): name min=minutes in the shared relative-time hint

Adoption review iteration 1 found the shared hint under-reports the parser
by exactly one unit. internal/timeparsing accepts `min|[hdwmy]`
(parser.go:22) and its doc comment spells out `m = months (NOT minutes;
use "min" for minutes)`, but deferUntilFormatHint named only h/d/w/m/y --
so all nine rejection messages told a caller that minutes are unsupported,
defeating the premise the PR is built on. Measured at this head: +30min,
-15min and 90min parse; +3mo and +30mins do not.

The gap is rebase-introduced, not contributor error: min arrived on main in
eb1689cb9d (GH#6609/#6629) after the contributor's merge base. Nothing
could red on it, because the PR's own guard test hardcoded the same
five-unit list in three places, so the constant and its enforcement drifted
together.

Add min=minutes to the constant and to all three lists, and show +30min
beside +3m so the m-vs-min boundary the message exists to explain is
visible in the message itself. Reverting min out of the constant alone reds
TestDeferUntilFormatHintCoversCompactUnits,
TestDeferUntilRejectionNamesUnitSet and all five
TestGatherInputRejectionsNameUnitSet subtests, while
TestRelativeTimeRejectionsShareTheHint stays green -- it pins that sites
reference the constant, not what the constant says.

Two non-gating items from the same review, taken because they are adjacent:

- The four update sites use HandleErrorRespectJSON, whose --json branch
  writes to stdout inside a JSON error payload instead of to stderr. The
  existing subtests pin jsonOutput = false, so that branch carried the
  ~190-char hint untested. A new subtest flips jsonOutput and asserts the
  unit set in the decoded payload; decoding is required because
  json.Encoder HTML-escapes the angle brackets in "[+-]?<n><unit>". Making
  HandleErrorRespectJSON ignore jsonOutput reds only the new subtest and
  leaves the four stderr subtests green, which is what proves it is not a
  duplicate of them.
- Four pins strings in tests/oracle-a/harness/scenarios/enumerated.json
  quoted the message text this PR replaces. pins is documentation the
  runner ignores (harness/PROVENANCE.md:13), so nothing was broken, only
  stale; refreshed in place. Their stale update.go line references are left
  byte-intact deliberately -- those line numbers are identical at the merge
  base and at HEAD, so that staleness is base-owned, not this PR's.

Also records two edges the review raised on the PR's own mechanism: the
sign is optional, so the notation is now [+-]?<n><unit> (measured), and the
uniformity guard matches per line, which is now stated in its comment
rather than left for the next reader to rediscover.

Deliberately left out: the flag --help usage strings (create.go:955,
defer.go:156, update.go:1002) still carry the old bare example lists. They
feed the generated-and-pinned CLI reference, so aligning them owes the
docs-regen check and belongs in a follow-up. deferUntilFormatHint has no
help-string consumer today (censused: nine rejection sites and nothing
else), so this commit owes no CLI-docs regen.

Also carries the rebase gate's bazel repair, unchanged from this commit's
previous revision:

    chore(bazel): enumerate defer_until_hint_test.go in cmd/bd go_test

    gazelle output for the PR's new untagged test file. cmd/bd/BUILD.bazel
    enumerates go_test srcs explicitly (667 files at the merge base) and the
    enumeration is exhaustive for untagged tests -- the only 4 unenumerated
    _test.go files on disk all carry build tags. Without this row the target
    builds green while running none of the PR's 4 new tests (-test.list: 0 of
    4 unrepaired, 4 of 4 repaired), and bazel.yml's BUILD-sync step reds on
    the post-'make bazel-sync' git diff.

    The //internal/timeparsing deps row is gazelle canonicalization, not a
    compile fix: bd_test embeds bd_lib, whose deps already carry it.

The new subtest adds no BUILD row: encoding/json is stdlib, and a
re-run of make bazel-sync after these edits leaves the tree clean.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 01:29:58 -07:00

379 lines
13 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/timeparsing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
)
type createInput struct {
markdownFile string
graphFile string
title string
explicitID string
parentID string
issueType string
status string
priority int
assignee string
externalRef string
specID string
description string
design string
acceptanceCriteria string
notes string
appendNotes string
labels []string
noInheritLabels bool
deps []string
waitsFor string
waitsForGate string
waitsForGateSet bool // true when --waits-for-gate was explicitly passed (not relying on default)
silent bool
dryRun bool
force bool
validate bool
ephemeral bool
noHistory bool
storageClass types.StorageClass
storageClassFlag string
molType types.MolType
wispType types.WispType
eventCategory string
eventActor string
eventTarget string
eventPayload string
dueAt *time.Time
deferUntil *time.Time
metadata json.RawMessage
metadataSet bool
estimatedMinutes *int
repoOverride string
repoOverrideSet bool
createdBy string
owner string
jsonOutput bool
validationMode string
}
// graphApplyOptions projects the plan-wide CLI flags into the options every
// graph validation/materialization helper takes.
func (in createInput) graphApplyOptions() GraphApplyOptions {
return GraphApplyOptions{Ephemeral: in.ephemeral, NoHistory: in.noHistory, Force: in.force}
}
// graphApplyOptionsFromFlags is the embedded-path projection of the plan-wide
// flags, delegating to graphApplyOptions so both transports share one
// flags→options mapping (the embedded create path reads flags directly
// rather than through gatherCreateInput).
func graphApplyOptionsFromFlags(cmd *cobra.Command) GraphApplyOptions {
var in createInput
in.ephemeral, _ = cmd.Flags().GetBool("ephemeral")
in.noHistory, _ = cmd.Flags().GetBool("no-history")
in.force, _ = cmd.Flags().GetBool("force")
return in.graphApplyOptions()
}
func gatherCreateInput(cmd *cobra.Command, args []string) (createInput, error) {
in := createInput{}
in.markdownFile, _ = cmd.Flags().GetString("file")
in.graphFile, _ = cmd.Flags().GetString("graph")
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
if in.markdownFile != "" && in.graphFile != "" {
return in, HandleError("cannot specify both --file and --graph")
}
if in.markdownFile != "" {
if len(args) > 0 {
return in, HandleError("cannot specify both title and --file flag; for a single issue's description from a file, use --body-file")
}
if in.dryRun {
return in, HandleError("--dry-run is not supported with --file flag")
}
if err := rejectSingleIssueFlagsForMarkdown(cmd); err != nil {
return in, err
}
}
if in.graphFile != "" {
if len(args) > 0 {
return in, HandleError("cannot specify both title and --graph flag")
}
if err := rejectSingleIssueFlagsForGraph(cmd); err != nil {
return in, err
}
}
in.silent, _ = cmd.Flags().GetBool("silent")
in.force, _ = cmd.Flags().GetBool("force")
in.validate, _ = cmd.Flags().GetBool("validate")
in.noInheritLabels, _ = cmd.Flags().GetBool("no-inherit-labels")
in.ephemeral, _ = cmd.Flags().GetBool("ephemeral")
in.noHistory, _ = cmd.Flags().GetBool("no-history")
if in.ephemeral && in.noHistory {
return in, HandleError("--ephemeral and --no-history are mutually exclusive")
}
titleFlag, _ := cmd.Flags().GetString("title")
title, err := resolveTitle(args, titleFlag, in.markdownFile, in.graphFile)
if err != nil {
return in, err
}
in.title = title
desc, descChanged, err := getDescriptionFlag(cmd)
if err != nil {
return in, err
}
if err := validateDescriptionUpdate(cmd, desc, descChanged); err != nil {
return in, HandleError("%v", err)
}
in.description = desc
skills, _ := cmd.Flags().GetString("skills")
if skills != "" {
if in.description != "" {
in.description += "\n\n"
}
in.description += "## Required Skills\n" + skills
}
ctxStr, _ := cmd.Flags().GetString("context")
if ctxStr != "" {
if in.description != "" {
in.description += "\n\n"
}
in.description += "## Context\n" + ctxStr
}
design, _, err := getDesignFlag(cmd)
if err != nil {
return in, err
}
in.design = design
in.acceptanceCriteria, _ = cmd.Flags().GetString("acceptance")
in.notes, _ = cmd.Flags().GetString("notes")
in.appendNotes, _ = cmd.Flags().GetString("append-notes")
in.specID, _ = cmd.Flags().GetString("spec-id")
if in.markdownFile == "" && in.graphFile == "" {
if in.description == "" && !isTestIssue(in.title) {
if config.GetBool("create.require-description") {
return in, HandleError("description is required (set create.require-description: false in config.yaml to disable)")
}
}
}
priorityStr, _ := cmd.Flags().GetString("priority")
priority, err := validation.ValidatePriority(priorityStr)
if err != nil {
return in, HandleError("%v", err)
}
in.priority = priority
in.issueType, _ = cmd.Flags().GetString("type")
// The raw flag rides along for the --file batch, which resolves the class
// per template (the per-type config default needs a type to key on, and only
// a template has one). --graph rejects the flag outright, so the only route
// that resolves it here is the single-issue create, on both transports.
in.storageClassFlag, _ = cmd.Flags().GetString("storage-class")
if in.markdownFile == "" && in.graphFile == "" {
class, wisp, err := resolveCreateStorageClass(in.storageClassFlag, types.IssueType(in.issueType), in.ephemeral, in.noHistory)
if err != nil {
return in, HandleError("%v", err)
}
in.storageClass = class
in.ephemeral = wisp
}
in.status, _ = cmd.Flags().GetString("status")
in.assignee, _ = cmd.Flags().GetString("assignee")
in.externalRef, _ = cmd.Flags().GetString("external-ref")
in.explicitID, _ = cmd.Flags().GetString("id")
in.parentID, _ = cmd.Flags().GetString("parent")
in.waitsFor, _ = cmd.Flags().GetString("waits-for")
in.waitsForGate, _ = cmd.Flags().GetString("waits-for-gate")
in.waitsForGateSet = cmd.Flags().Changed("waits-for-gate")
if in.explicitID != "" && in.parentID != "" {
return in, HandleError("cannot specify both --id and --parent flags")
}
in.labels, _ = cmd.Flags().GetStringSlice("labels")
labelAlias, _ := cmd.Flags().GetStringSlice("label")
if len(labelAlias) > 0 {
in.labels = append(in.labels, labelAlias...)
}
// Normalize after merging the alias so dedupe spans both flags. Read paths
// (list, search, ready, orphans) already do this; without it here, `--labels
// 'a, b'` stores " b" with pflag's leading space and can never match its own
// filter.
in.labels = utils.NormalizeLabels(in.labels)
warnLabelsContainingWhitespace(in.labels)
in.deps, _ = cmd.Flags().GetStringSlice("deps")
in.repoOverride, _ = cmd.Flags().GetString("repo")
in.repoOverrideSet = cmd.Flags().Changed("repo")
if molTypeStr, _ := cmd.Flags().GetString("mol-type"); molTypeStr != "" {
mt := types.MolType(molTypeStr)
if !mt.IsValid() {
return in, HandleError("invalid mol-type %q (must be %s)", molTypeStr, types.ValidMolTypeNames())
}
in.molType = mt
}
if wispTypeStr, _ := cmd.Flags().GetString("wisp-type"); wispTypeStr != "" {
wt := types.WispType(wispTypeStr)
if !wt.IsValid() {
return in, HandleError("invalid wisp-type %q (must be %s)", wispTypeStr, types.ValidWispTypeNames())
}
in.wispType = wt
}
in.eventCategory, _ = cmd.Flags().GetString("event-category")
in.eventActor, _ = cmd.Flags().GetString("event-actor")
in.eventTarget, _ = cmd.Flags().GetString("event-target")
in.eventPayload, _ = cmd.Flags().GetString("event-payload")
if (in.eventCategory != "" || in.eventActor != "" || in.eventTarget != "" || in.eventPayload != "") && in.issueType != "event" {
return in, HandleError("--event-category, --event-actor, --event-target, and --event-payload flags require --type=event")
}
if dueStr, _ := cmd.Flags().GetString("due"); dueStr != "" {
t, err := timeparsing.ParseRelativeTime(dueStr, time.Now())
if err != nil {
return in, HandleError("invalid --due format %q. %s", dueStr, deferUntilFormatHint)
}
in.dueAt = &t
}
if deferStr, _ := cmd.Flags().GetString("defer"); deferStr != "" {
t, err := timeparsing.ParseRelativeTime(deferStr, time.Now())
if err != nil {
return in, HandleError("invalid --defer format %q. %s", deferStr, deferUntilFormatHint)
}
if t.Before(time.Now()) && !in.silent && !debug.IsQuiet() {
fmt.Fprintf(os.Stderr, "%s Defer date %q is in the past. Issue will appear in bd ready immediately.\n",
ui.RenderWarn("!"), t.Local().Format("2006-01-02 15:04"))
fmt.Fprintf(os.Stderr, " Did you mean a future date? Use --defer=+1h or --defer=tomorrow\n")
}
in.deferUntil = &t
}
if cmd.Flags().Changed("metadata") {
metadataValue, _ := cmd.Flags().GetString("metadata")
metadata, err := readMetadataFlag(metadataValue)
if err != nil {
return in, HandleError("%v", err)
}
in.metadata = metadata
in.metadataSet = true
}
if cmd.Flags().Changed("estimate") {
est, _ := cmd.Flags().GetInt("estimate")
if est < 0 {
return in, HandleError("estimate must be a non-negative number of minutes")
}
in.estimatedMinutes = &est
}
in.createdBy = getActorWithGit()
in.owner = getOwner()
in.jsonOutput = jsonOutput
in.validationMode = config.GetString("validation.on-create")
if in.validate {
in.validationMode = "error"
}
return in, nil
}
var singleIssueOnlyFlags = []string{
"title",
"id", "parent", "no-inherit-labels",
"deps", "waits-for", "waits-for-gate",
"type", "priority", "assignee", "external-ref", "spec-id",
"status",
"description", "body", "message", "body-file", "description-file", "stdin",
"design", "design-file", "acceptance", "notes", "append-notes",
"allow-empty-description",
"labels", "label", "skills", "context",
"event-category", "event-actor", "event-target", "event-payload",
"due", "defer",
"metadata", "estimate", "wisp-type",
}
func rejectSingleIssueFlagsForMarkdown(cmd *cobra.Command) error {
for _, name := range singleIssueOnlyFlags {
if cmd.Flags().Changed(name) {
return HandleError("--%s is not valid with --file (markdown templates supply per-issue fields)", name)
}
}
// --force is plan-wide for --graph (foreign-prefix explicit IDs) but the
// markdown path never consults it, so reject it here rather than accept
// and silently ignore.
if cmd.Flags().Changed("force") {
return HandleError("--force is not valid with --file (markdown templates supply per-issue fields)")
}
return nil
}
func rejectSingleIssueFlagsForGraph(cmd *cobra.Command) error {
for _, name := range singleIssueOnlyFlags {
if cmd.Flags().Changed(name) {
return HandleError("--%s is not valid with --graph (graph plans supply per-node fields)", name)
}
}
if cmd.Flags().Changed("mol-type") {
return HandleError("--mol-type is not valid with --graph (set mol_type per node in the plan instead)")
}
// Same shape as --mol-type: a plan-wide class would duplicate the per-node
// storage_class field (plus its per-type config default) that graph-apply
// already honors, so the flag is refused rather than accepted and ignored.
if cmd.Flags().Changed("storage-class") {
return HandleError("--storage-class is not valid with --graph (set storage_class per node in the plan instead)")
}
return nil
}
func resolveTitle(args []string, titleFlag, markdownFile, graphFile string) (string, error) {
if markdownFile != "" || graphFile != "" {
return "", nil
}
var title string
switch {
case len(args) > 0 && titleFlag != "":
if args[0] != titleFlag {
return "", HandleError("cannot specify different titles as both positional argument and --title flag\n Positional: %q\n --title: %q", args[0], titleFlag)
}
title = args[0]
case len(args) > 0:
if strings.HasPrefix(args[0], "-") {
return "", HandleError("title %q looks like a flag (starts with '-').\n Run 'bd create --help' for available options.\n To use this title anyway, pass it explicitly: bd create --title=%q", args[0], args[0])
}
title = args[0]
case titleFlag != "":
title = titleFlag
default:
return "", HandleError("title required (or use --file to create from markdown)")
}
if strings.TrimSpace(title) == "" {
return "", HandleError("title cannot be empty or whitespace-only")
}
return title, nil
}