diff --git a/.abcd/development/brief/04-surfaces/21-update.md b/.abcd/development/brief/04-surfaces/21-update.md index ce7c27230a..46d838ea12 100644 --- a/.abcd/development/brief/04-surfaces/21-update.md +++ b/.abcd/development/brief/04-surfaces/21-update.md @@ -290,6 +290,7 @@ Sub-verbs: none. | Flag | Type | |---|---| | `--answer` | string | +| `--change` | string | | `--full` | bool | | `--seen` | bool | diff --git a/.abcd/development/release/surface.json b/.abcd/development/release/surface.json index 53c0045a24..fe7576d23e 100644 --- a/.abcd/development/release/surface.json +++ b/.abcd/development/release/surface.json @@ -5216,6 +5216,13 @@ "required": false, "hidden": false }, + { + "name": "change", + "shorthand": "", + "type": "string", + "required": false, + "hidden": false + }, { "name": "full", "shorthand": "", diff --git a/.abcd/work/decisions/dcn-2612030746316432-the-full-news-groups-each-release-s.md b/.abcd/work/decisions/dcn-2612030746316432-the-full-news-groups-each-release-s.md new file mode 100644 index 0000000000..5658a0ea23 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030746316432-the-full-news-groups-each-release-s.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030746316432 +slug: the-full-news-groups-each-release-s +date: 2026-12-03 +--- +2026-12-03 — The full news groups each release's changes by kind, new or fixed, as the area: the release digest carries no area field, and adding one would change the digest schema and the release cut that writes it, which is more than the fix for iss-2612021706041724 needs; a change's impact is the only area-like fact the digest holds, and a hand-kept keyword taxonomy would drift diff --git a/.abcd/work/decisions/dcn-2612030746321009-the-full-news-draws-only-code-spans-and.md b/.abcd/work/decisions/dcn-2612030746321009-the-full-news-draws-only-code-spans-and.md new file mode 100644 index 0000000000..613ebdc0d0 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030746321009-the-full-news-draws-only-code-spans-and.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030746321009 +slug: the-full-news-draws-only-code-spans-and +date: 2026-12-03 +--- +2026-12-03 — The full news draws only code spans and strong emphasis as terminal styling, the two markdown constructs the 976 lines of the release digest use, pairing code spans through mdrecord.CodeSpanRanges and termsafe.PairCodeSpan and masking every line with termsafe.SanitizeLine first; abcd has no markdown-to-terminal renderer to reuse (mdrender writes HTML for the site), so the small reader lives beside the full news in internal/core/afterupdate (iss-2612021706041724) diff --git a/.abcd/work/decisions/dcn-2612030746325377-the-headline-changes-of-a-release-in-the.md b/.abcd/work/decisions/dcn-2612030746325377-the-headline-changes-of-a-release-in-the.md new file mode 100644 index 0000000000..932163d370 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030746325377-the-headline-changes-of-a-release-in-the.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030746325377 +slug: the-headline-changes-of-a-release-in-the +date: 2026-12-03 +--- +2026-12-03 — The headline changes of a release in the full news are its changes whose changelog paragraph opens with a bold lead, at most five, in changelog order, each shown as that lead; a change with no lead is shown as its first sentence (iss-2612021706041724) diff --git a/.abcd/work/decisions/dcn-2612030746332849-a-change-s-whole-text-is-shown-on.md b/.abcd/work/decisions/dcn-2612030746332849-a-change-s-whole-text-is-shown-on.md new file mode 100644 index 0000000000..40dc4ae85c --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030746332849-a-change-s-whole-text-is-shown-on.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030746332849 +slug: a-change-s-whole-text-is-shown-on +date: 2026-12-03 +--- +2026-12-03 — A change's whole text is shown on request with abcd update news --change , naming any record the change cites, over the same releases --full lists; the plain form (off a terminal and in --json lines) is the coloured drawing with its styling removed and nothing cut to a width (iss-2612021706041724) diff --git a/.abcd/work/issues/open/iss-2612021706041724-abcd-update-news-full-cannot-be-read-by.md b/.abcd/work/issues/resolved/iss-2612021706041724-abcd-update-news-full-cannot-be-read-by.md similarity index 83% rename from .abcd/work/issues/open/iss-2612021706041724-abcd-update-news-full-cannot-be-read-by.md rename to .abcd/work/issues/resolved/iss-2612021706041724-abcd-update-news-full-cannot-be-read-by.md index eb5809ee5c..478f7db880 100644 --- a/.abcd/work/issues/open/iss-2612021706041724-abcd-update-news-full-cannot-be-read-by.md +++ b/.abcd/work/issues/resolved/iss-2612021706041724-abcd-update-news-full-cannot-be-read-by.md @@ -10,6 +10,10 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/core/afterupdate/afterupdate.go" remedy: "Render the full news for a terminal person: per release, a short coloured summary first (what needs you, checked against this machine, then the few headline changes in one line each), the rest grouped by area and collapsed to one line per change with its record id, markdown rendered as terminal styling rather than printed raw, and the whole paragraph text only on request for a named change; plain output keeps the same structure without colour when the output is not a terminal." +resolution: "update news --full now draws each release as a summary (what needs the person, headline changes) then the rest as new or fixed, one line per change with its record id, styled and fitted at a terminal and plain elsewhere; --change shows one change whole" +impact: fix +resolved_by: + commit: "bd7b4cd94" --- abcd update news --full cannot be read by a person. After an update across four releases it printed 169 changes as one unbroken wall of plain text: each change is a whole changelog paragraph of up to ten lines written for agents (configuration keys, refusal rules, record ids), with no headings beyond the release line, no grouping by what a change means for the person, no colour, no emphasis the terminal renders (the markdown asterisks and backticks print literally), and no ordering by importance. The two changes marked as needing the person sit in the middle of a release's list in the same type as everything else. The person found it overwhelming and useless. Sibling of iss-2612021704499060, which covers whether a needs-you item applies to this machine at all. diff --git a/commands/update.md b/commands/update.md index 7bbf31f93a..c845fc285a 100644 --- a/commands/update.md +++ b/commands/update.md @@ -266,12 +266,18 @@ person's, and a mark written there would hide the news and the offer from the person's next session. **On request.** When the person asks for details, run -`"${CLAUDE_PLUGIN_ROOT}/abcd" update news --full` and relay it: every -change of the releases since the last update, those that need action first, -each with the record it cites, then what waits in this repository. It writes -nothing, so it can be shown again at any time, and it is the way to see the -summary on a host that runs no session-start hook. `--answer` takes neither -`--full` nor `--seen`. +`"${CLAUDE_PLUGIN_ROOT}/abcd" update news --full` and relay it: per +release, what needs the person first, then the few headline changes, then +the rest as new or fixed, one line per change with the record it cites, then +what waits in this repository. At a terminal it is drawn in colour and fitted +to the window; elsewhere the same lines come plain. When the person asks +about one change, run +`"${CLAUDE_PLUGIN_ROOT}/abcd" update news --change ` with the +record its line names, which prints that change's whole text. Neither writes +anything, so either can be shown again at any time, and `--full` is the way +to see the summary on a host that runs no session-start hook. `--answer` +takes neither `--full` nor `--seen`, and `--change` takes neither `--answer` +nor `--seen`. **Command facts, format version 3.** Where this block and `"${CLAUDE_PLUGIN_ROOT}/abcd" explain update` from the running binary disagree, follow the binary. diff --git a/docs/how-to/install.md b/docs/how-to/install.md index 9c38a473d3..89c6db3056 100644 --- a/docs/how-to/install.md +++ b/docs/how-to/install.md @@ -221,7 +221,9 @@ one line per release this computer has not been shown, naming how many changes it made and which of them need you to act. Where the update brings setup this repository has never answered, the reply also offers to run setup again. `abcd update news` prints the same lines, and `abcd update news --full` -lists every change. +lists every change: per release, what needs you first, then the headline +changes, then the rest as new or fixed, one line each with the record it +cites. `abcd update news --change ` prints one change in full. For a stronger root of trust than same-origin checksums, build from source — `go build ./cmd/abcd` — and place the binary in the plugin root and on your diff --git a/docs/reference/cli/commands.md b/docs/reference/cli/commands.md index dd7c37803f..ba1d7018a9 100644 --- a/docs/reference/cli/commands.md +++ b/docs/reference/cli/commands.md @@ -8079,12 +8079,13 @@ Say what changed since the update, and offer the setup that waits: Writes only a **Usage:** `abcd update news [flags]` -After an abcd update, print what the agent relays at the start of its first reply: one line per release this computer has not been shown, saying how many changes it made and which need the person to act, and, where the update brings this repository setup it never answered, the offer to run setup again. It prints nothing when there is nothing to say. --full prints every change of the releases since the last update, those that need action first, each with the record it cites, and what waits here. Neither writes anything. Only a person's reply is recorded: --answer yes|not-now records the answer to the offer for this repository and release, once, and --seen records that the news was read where no offer was made, both in abcd's home folder. On yes, run abcd ahoy install --only-waiting. The text comes only from the binary's own digest and checked release numbers, and nothing is fetched. +After an abcd update, print what the agent relays at the start of its first reply: one line per release this computer has not been shown, saying how many changes it made and which need the person to act, and, where the update brings this repository setup it never answered, the offer to run setup again. It prints nothing when there is nothing to say. --full prints the releases since the last update for a person: per release, what needs them, then the headline changes, then the rest as new or fixed, one line per change with the record it cites, in colour at a terminal and plain elsewhere, then what waits here; --change prints the whole text of the change citing that record. Neither writes anything. Only a person's reply is recorded: --answer yes|not-now records the answer to the offer for this repository and release, once, and --seen records that the news was read where no offer was made, both in abcd's home folder. On yes, run abcd ahoy install --only-waiting. The text comes only from the binary's own digest and checked release numbers, and nothing is fetched. **Flags:** ``` --answer string record the person's reply to the offer, yes | not-now, once for this repository and release; run it only with their reply + --change string print the whole text of the change citing this record id (itd-N or iss-N) in the releases since the last update; writes nothing --full[=true|false] print the full summary of the releases since the last update and what waits here; writes nothing --seen[=true|false] record that the person read the news where no offer was made; run it only after they were shown it ``` diff --git a/docs/reference/cli/commands/update.json b/docs/reference/cli/commands/update.json index 9f532708df..5772b4f727 100644 --- a/docs/reference/cli/commands/update.json +++ b/docs/reference/cli/commands/update.json @@ -40,6 +40,10 @@ "not-now" ] }, + { + "name": "change", + "type": "string" + }, { "name": "full", "type": "bool" diff --git a/internal/core/afterupdate/afterupdate.go b/internal/core/afterupdate/afterupdate.go index 1ea10af336..1c80a69a54 100644 --- a/internal/core/afterupdate/afterupdate.go +++ b/internal/core/afterupdate/afterupdate.go @@ -205,16 +205,7 @@ func Moment(cwd string) (MomentLines, error) { // the repository's setup version, else the running release alone. What // waits is listed where the repository's setup version is an older release. func Full(cwd, from string) (FullSummary, error) { - running, ok := release(runningVersion()) - if !ok { - return FullSummary{}, ErrNotRelease - } - if from == "" { - from = firstRelease(func() (string, bool) { return previousTag(cwd) }, func() (string, bool) { return setupVersion(cwd) }) - } else if _, err := launch.ParseReleaseTag(from); err != nil { - return FullSummary{}, releasedigest.ErrNotReleaseTag - } - sum, err := digestRange(from, running) + running, sum, err := fullRange(cwd, from) if err != nil { return FullSummary{}, err } @@ -228,10 +219,27 @@ func Full(cwd, from string) (FullSummary, error) { return FullSummary{}, err } } - f.Lines = fullLines(sum, f.Waiting) + f.Lines = RenderFull(f, Style{}) return f, nil } +// fullRange is the running release and the range the full summary covers: +// after from, or where from is "" after the binary record's previous release, +// else the repository's setup version, else the running release alone. +func fullRange(cwd, from string) (string, releasedigest.Summary, error) { + running, ok := release(runningVersion()) + if !ok { + return "", releasedigest.Summary{}, ErrNotRelease + } + if from == "" { + from = firstRelease(func() (string, bool) { return previousTag(cwd) }, func() (string, bool) { return setupVersion(cwd) }) + } else if _, err := launch.ParseReleaseTag(from); err != nil { + return "", releasedigest.Summary{}, releasedigest.ErrNotReleaseTag + } + sum, err := digestRange(from, running) + return running, sum, err +} + // Record records the person's answer to the offer for the repository at cwd // and the running release, and raises news-seen to that release, since the // answer was given to the moment that showed it. The answer is created @@ -556,44 +564,3 @@ func plural(n int, one, many string) string { } return fmt.Sprintf("%d %s", n, many) } - -// fullLines renders the full summary: each release, its entries needing -// action first, each with the records it cites; the releases not described; -// then what waits here. -func fullLines(sum releasedigest.Summary, w ahoy.WaitingSet) []string { - out := []string{} - if len(sum.Releases) == 0 && sum.Gap == nil { - out = append(out, "abcd "+sum.To+": no release to describe after "+sum.From+".") - } - for _, r := range sum.Releases { - head := "abcd " + r.Tag - if r.BaseTag != "" { - head += " (after " + r.BaseTag + ")" - } - out = append(out, head+": "+plural(len(r.Entries), "change", "changes")) - for _, e := range r.Entries { - ids := make([]string, len(e.Records)) - for i, rec := range e.Records { - ids[i] = rec.ID - } - mark := " - " - if e.NeedsAction() { - mark = " - needs you to act: " - } - out = append(out, mark+e.Line+" ("+strings.Join(ids, ", ")+")") - } - } - if sum.Gap != nil { - out = append(out, gapLine(*sum.Gap)) - } - if len(w.Questions)+len(w.Defaults) > 0 { - out = append(out, "Waiting in this repository:") - for _, q := range w.Questions { - out = append(out, " - setup question: "+q.Title) - } - for _, d := range w.Defaults { - out = append(out, " - changed default: "+d.Title) - } - } - return out -} diff --git a/internal/core/afterupdate/afterupdate_test.go b/internal/core/afterupdate/afterupdate_test.go index 5882f8f15c..8236623ff0 100644 --- a/internal/core/afterupdate/afterupdate_test.go +++ b/internal/core/afterupdate/afterupdate_test.go @@ -396,7 +396,7 @@ func TestADevBuildHoldsNothing(t *testing.T) { // TestFullShowsEveryChangeActionFirstAndAgain: the full summary lists each // release in the range, its breaking entries first, every entry with the -// record ids it cites, then what waits here; it is the same after the news +// record ids it cites, then the way to read one whole and what waits here; it is the same after the news // was seen and the offer answered, and an explicit start is honoured. func TestFullShowsEveryChangeActionFirstAndAgain(t *testing.T) { w := newWorld(t) @@ -406,12 +406,15 @@ func TestFullShowsEveryChangeActionFirstAndAgain(t *testing.T) { } want := []string{ "abcd v0.16.0 (after v0.15.0): 9 changes", - " - needs you to act: The bare verb no longer mints a record. (itd-2610161616086564)", + " Needs you (1)", + " ! The bare verb no longer mints a record. (itd-2610161616086564)", + " New (8)", } for i := 1; i <= 8; i++ { - want = append(want, fmt.Sprintf(" - Added change %d. (iss-%d)", i, 100+i)) + want = append(want, fmt.Sprintf(" - Added change %d. (iss-%d)", i, 100+i)) } want = append(want, + "The whole text of one change: "+ChangeCommand, "Waiting in this repository:", " - setup question: the README question is not answered", " - setup question: no drain eligibility record in this repository", diff --git a/internal/core/afterupdate/fullview.go b/internal/core/afterupdate/fullview.go new file mode 100644 index 0000000000..510376380a --- /dev/null +++ b/internal/core/afterupdate/fullview.go @@ -0,0 +1,464 @@ +package afterupdate + +// fullview.go draws the full summary for a person (iss-2612021706041724): per +// release, what needs them first, then the few headline changes, then the +// rest under the area each falls in, one line per change with its record id, +// the changelog's markdown drawn as terminal styling; and one change whole, +// only when it is asked for by the record it cites. +// +// Every changelog line is untrusted text: it is masked (termsafe.SanitizeLine) +// before it is read as markdown, so the only escapes a line carries are the +// sixteen-colour SGR sequences composed here, as the question frame +// (surface/cli/ask) and the status board compose theirs. Code spans are paired +// through the tree's one pairer (mdrecord.CodeSpanRanges, termsafe.PairCodeSpan) +// and read by CommonMark's content rules (termsafe.CodeSpanText); widths are +// measured and fitted with textwidth. The plain form is the coloured form with +// the styling taken off, so the structure never depends on colour. + +import ( + "errors" + "fmt" + "strings" + + "github.com/intentdriven/abcd/internal/core/mdrecord" + "github.com/intentdriven/abcd/internal/core/releasedigest" + "github.com/intentdriven/abcd/internal/termsafe" + "github.com/intentdriven/abcd/internal/textwidth" +) + +// ChangeCommand is the command that shows one change whole, named under the +// full summary. +const ChangeCommand = "abcd update news --change " + +// maxHeadlines bounds the headline changes a release's summary names. +const maxHeadlines = 5 + +// proseColumns is the widest the whole text of a change is wrapped, at any +// width, as the question frame wraps its prose. +const proseColumns = 80 + +var ( + // ErrNotRecordID is Change's refusal of a word that is not a record id. + ErrNotRecordID = errors.New("a change is named by a record id it cites, itd-N or iss-N (the value given is not repeated here)") + // ErrNoSuchChange is Change's refusal of a record no change in the range cites. + ErrNoSuchChange = errors.New("no change in the releases since the last update cites that record") +) + +// Style is how the summary is drawn: Colour composes the sixteen basic SGR +// colours, Width fits each change's line to that many columns (0 leaves it +// whole), and ASCII cuts a line with "..." where the locale is not UTF-8. +type Style struct { + Colour bool + Width int + ASCII bool +} + +// CitedChange is one change citing the record a ChangeDetail names, with the +// release that made it. +type CitedChange struct { + Release string `json:"release"` + Entry releasedigest.Entry `json:"entry"` +} + +// ChangeDetail is one record's changes in the range, shown whole. +type ChangeDetail struct { + ID string `json:"id"` + Changes []CitedChange `json:"changes"` + Lines []string `json:"lines"` +} + +// Change finds the changes citing the record id in the releases Full lists by +// default, reading only, and returns them whole. +func Change(cwd, id string) (ChangeDetail, error) { + if !releasedigest.IsRecordID(id) { + return ChangeDetail{}, ErrNotRecordID + } + _, sum, err := fullRange(cwd, "") + if err != nil { + return ChangeDetail{}, err + } + c := ChangeDetail{ID: id, Changes: []CitedChange{}} + for _, r := range sum.Releases { + for _, e := range r.Entries { + for _, rec := range e.Records { + if rec.ID == id { + c.Changes = append(c.Changes, CitedChange{Release: r.Tag, Entry: e}) + break + } + } + } + } + if len(c.Changes) == 0 { + return ChangeDetail{}, fmt.Errorf("%w (%s)", ErrNoSuchChange, id) + } + c.Lines = RenderChange(c, Style{}) + return c, nil +} + +// The SGR codes the drawing composes: the sixteen basic colours and two +// attributes only, whatever higher rung the terminal offers. +const ( + sgrBold = "1" + sgrDim = "2" + sgrRed = "31" + sgrYellow = "33" + sgrCyan = "36" + sgrReset = "\x1b[0m" +) + +// drawer carries one drawing's style. +type drawer struct{ st Style } + +// paint wraps s in the SGR codes, or leaves it plain without colour. +func (d drawer) paint(s string, codes ...string) string { + var cs []string + for _, c := range codes { + if c != "" { + cs = append(cs, c) + } + } + if !d.st.Colour || s == "" || len(cs) == 0 { + return s + } + return "\x1b[" + strings.Join(cs, ";") + "m" + s + sgrReset +} + +func (d drawer) ellipsis() string { + if d.st.ASCII { + return "..." + } + return "…" +} + +// span is a run of one changelog line read as markdown: text, strong +// emphasis, or a code span's text. +type span struct { + text string + bold, code bool +} + +// inline masks a changelog line and reads its markdown: code spans and ** +// strong emphasis, the two constructs abcd's changelog writes. Anything else +// is text. +func inline(line string) []span { + s := termsafe.SanitizeLine(line) + var out []span + bold := false + add := func(text string, code bool) { + if text != "" { + out = append(out, span{text: text, bold: bold, code: code}) + } + } + // text reads the stretch between code spans for ** pairs; a ** with no + // partner later in the line is text. The stretch and the rest of the line + // are searched apart, so no opener copies the line. + text := func(t string, rest string) { + for { + i := strings.Index(t, "**") + if i < 0 { + add(t, false) + return + } + if !bold && !strings.Contains(t[i+2:], "**") && !strings.Contains(rest, "**") { + add(t, false) + return + } + add(t[:i], false) + bold = !bold + t = t[i+2:] + } + } + at := 0 + for _, r := range mdrecord.CodeSpanRanges(s) { + sp, ok := termsafe.PairCodeSpan(s, r[0]) + if !ok || sp.Start < at { + continue + } + text(s[at:sp.Start], s[sp.Start:]) + add(termsafe.CodeSpanText(sp.Raw(s)), true) + at = sp.End + } + text(s[at:], "") + return out +} + +// columns is the width spans take as drawn. +func columns(spans []span) int { + n := 0 + for _, s := range spans { + n += textwidth.Columns(s.text) + } + return n +} + +// headline is a change's one-line form: its bold lead where it opens with +// one, else its first sentence. It is drawn without the lead's emphasis. +func headline(spans []span) []span { + var out []span + if len(spans) > 0 && spans[0].bold { + for _, s := range spans { + if !s.bold { + break + } + s.bold = false + out = append(out, s) + } + return trimSpans(out) + } + for _, s := range spans { + if !s.code { + if i := strings.Index(s.text, ". "); i >= 0 { + s.text = s.text[:i+1] + return trimSpans(append(out, s)) + } + } + out = append(out, s) + } + return trimSpans(out) +} + +// trimSpans drops the space at either end of a run of spans. +func trimSpans(spans []span) []span { + if len(spans) == 0 { + return spans + } + spans[0].text = strings.TrimLeft(spans[0].text, " ") + last := len(spans) - 1 + spans[last].text = strings.TrimRight(spans[last].text, " ") + return spans +} + +// fit cuts spans to limit columns, ending them with the ellipsis, where they +// are wider; a limit below one leaves them whole. +func (d drawer) fit(spans []span, limit int) []span { + if limit < 1 || columns(spans) <= limit { + return spans + } + room := limit - textwidth.Columns(d.ellipsis()) + var out []span + used := 0 + for _, s := range spans { + if used+textwidth.Columns(s.text) <= room { + out = append(out, s) + used += textwidth.Columns(s.text) + continue + } + if cut := textwidth.Fit(s.text, room-used, ""); cut != "" { + s.text = cut + out = append(out, s) + } + break + } + out = trimSpans(out) + return append(out, span{text: d.ellipsis()}) +} + +// draw paints spans, each in its own emphasis over the line's codes. +func (d drawer) draw(spans []span, base ...string) string { + var b strings.Builder + for _, s := range spans { + codes := append([]string{}, base...) + if s.bold { + codes = append(codes, sgrBold) + } + if s.code { + codes = append(codes, sgrCyan) + } + b.WriteString(d.paint(s.text, codes...)) + } + return b.String() +} + +// ids names the records a change cites: the first, and a count of the rest. +func ids(e releasedigest.Entry) string { + if len(e.Records) == 0 { + return "" + } + s := termsafe.SanitizeLine(e.Records[0].ID) + if n := len(e.Records) - 1; n > 0 { + s += fmt.Sprintf(" and %d more", n) + } + return "(" + s + ")" +} + +// minSummaryColumns is the narrowest a change's summary is drawn beside its +// record id; a window with less room drops the id. +const minSummaryColumns = 10 + +// changeLine is one change on one line: the mark, its one-line form fitted to +// the window, and its record id. A window too narrow for the id beside a +// readable summary drops the id, and the summary is cut to what is left. +func (d drawer) changeLine(mark string, markCodes []string, e releasedigest.Entry) string { + const indent = " " + tail := ids(e) + room := 0 + if d.st.Width > 0 { + lead := len(indent) + len(mark) + 1 + if room = d.st.Width - lead - 1 - textwidth.Columns(tail); room < minSummaryColumns { + tail, room = "", max(d.st.Width-lead, 1) + } + } + line := indent + d.paint(mark, markCodes...) + " " + d.draw(d.fit(headline(inline(e.Line)), room)) + if tail != "" { + line += " " + d.paint(tail, sgrDim) + } + return line +} + +// isHeadline reports whether a change opens with a bold lead, the changelog's +// mark of a headline change. +func isHeadline(e releasedigest.Entry) bool { + spans := inline(e.Line) + return len(spans) > 0 && spans[0].bold +} + +// isNew reports whether a change adds something: any record it cites is +// additive. A change citing only fixes is a fix. +func isNew(e releasedigest.Entry) bool { + for _, r := range e.Records { + if r.Impact == releasedigest.ImpactAdditive { + return true + } + } + return false +} + +// RenderFull draws the full summary in the style st: per release, its line, +// what needs the person, the headline changes, then the rest by area (what +// is new, what is fixed), one line per change with its record id; then the +// way to read one change whole, the releases not described, and what waits +// here. Full's Lines are this drawing in the plain style. +func RenderFull(f FullSummary, st Style) []string { + d := drawer{st: st} + sum := f.Summary + out := []string{} + if len(sum.Releases) == 0 && sum.Gap == nil { + out = append(out, "abcd "+termsafe.SanitizeLine(sum.To)+": no release to describe after "+termsafe.SanitizeLine(sum.From)+".") + } + for _, r := range sum.Releases { + head := "abcd " + termsafe.SanitizeLine(r.Tag) + if r.BaseTag != "" { + head += " (after " + termsafe.SanitizeLine(r.BaseTag) + ")" + } + out = append(out, d.paint(head+": "+plural(len(r.Entries), "change", "changes"), sgrBold)) + var needs, heads, added, fixed []releasedigest.Entry + for _, e := range r.Entries { + switch { + case e.NeedsAction(): + needs = append(needs, e) + case len(heads) < maxHeadlines && isHeadline(e): + heads = append(heads, e) + case isNew(e): + added = append(added, e) + default: + fixed = append(fixed, e) + } + } + out = d.group(out, fmt.Sprintf("Needs you (%d)", len(needs)), []string{sgrBold, sgrRed}, "!", []string{sgrBold, sgrRed}, needs) + out = d.group(out, "Headlines", []string{sgrBold, sgrYellow}, "*", []string{sgrYellow}, heads) + out = d.group(out, fmt.Sprintf("New (%d)", len(added)), []string{sgrBold, sgrCyan}, "-", nil, added) + out = d.group(out, fmt.Sprintf("Fixed (%d)", len(fixed)), []string{sgrBold, sgrCyan}, "-", nil, fixed) + } + if len(sum.Releases) > 0 { + out = append(out, d.paint("The whole text of one change: "+ChangeCommand, sgrDim)) + } + if sum.Gap != nil { + out = append(out, gapLine(*sum.Gap)) + } + w := f.Waiting + if len(w.Questions)+len(w.Defaults) > 0 { + out = append(out, d.paint("Waiting in this repository:", sgrBold)) + for _, q := range w.Questions { + out = append(out, " - setup question: "+termsafe.SanitizeLine(q.Title)) + } + for _, df := range w.Defaults { + out = append(out, " - changed default: "+termsafe.SanitizeLine(df.Title)) + } + } + return out +} + +// group draws one heading and its changes, or nothing for no change. +func (d drawer) group(out []string, title string, titleCodes []string, mark string, markCodes []string, entries []releasedigest.Entry) []string { + if len(entries) == 0 { + return out + } + out = append(out, " "+d.paint(title, titleCodes...)) + for _, e := range entries { + out = append(out, d.changeLine(mark, markCodes, e)) + } + return out +} + +// RenderChange draws each change of c whole in the style st: the release and +// the records it cites with their impact, then its whole text with its +// markdown drawn as styling, wrapped to the window at up to 80 columns (one +// line where st has no width). +func RenderChange(c ChangeDetail, st Style) []string { + d := drawer{st: st} + var out []string + for _, ch := range c.Changes { + recs := make([]string, len(ch.Entry.Records)) + for i, r := range ch.Entry.Records { + recs[i] = termsafe.SanitizeLine(r.ID) + " (" + termsafe.SanitizeLine(string(r.Impact)) + ")" + } + out = append(out, d.paint("abcd "+termsafe.SanitizeLine(ch.Release)+": "+strings.Join(recs, ", "), sgrBold)) + measure := 0 + if st.Width > 0 { + measure = max(min(st.Width, proseColumns)-2, 20) + } + for _, l := range d.wrap(trimSpans(inline(ch.Entry.Line)), measure) { + out = append(out, " "+l) + } + } + return out +} + +// wrap breaks spans into lines of at most measure columns at the spaces of +// their text, never inside a code span, and draws each line; a measure below +// one draws them as one line. +func (d drawer) wrap(spans []span, measure int) []string { + type word []span + var words []word + var cur word + flush := func() { + if len(cur) > 0 { + words = append(words, cur) + cur = nil + } + } + for _, s := range spans { + if s.code { + cur = append(cur, s) + continue + } + for i, part := range strings.Split(s.text, " ") { + if i > 0 { + flush() + } + if part != "" { + cur = append(cur, span{text: part, bold: s.bold}) + } + } + } + flush() + var lines []string + var line []string + used := 0 + for _, w := range words { + n := columns(w) + if measure > 0 && len(line) > 0 && used+1+n > measure { + lines = append(lines, strings.Join(line, " ")) + line, used = nil, 0 + } + if len(line) > 0 { + used++ + } + line = append(line, d.draw(w)) + used += n + } + if len(line) > 0 { + lines = append(lines, strings.Join(line, " ")) + } + return lines +} diff --git a/internal/core/afterupdate/fullview_test.go b/internal/core/afterupdate/fullview_test.go new file mode 100644 index 0000000000..4fd8404574 --- /dev/null +++ b/internal/core/afterupdate/fullview_test.go @@ -0,0 +1,272 @@ +package afterupdate + +import ( + "encoding/json" + "errors" + "regexp" + "runtime" + "slices" + "strings" + "testing" + + "github.com/intentdriven/abcd/internal/core/ahoy" + "github.com/intentdriven/abcd/internal/core/releasedigest" + "github.com/intentdriven/abcd/internal/textwidth" +) + +// sgrRe is one SGR sequence the renderer composes. +var sgrRe = regexp.MustCompile("\x1b\\[[0-9;]*m") + +// plainOf is a rendered line with its styling taken off. +func plainOf(lines []string) []string { + out := make([]string, len(lines)) + for i, l := range lines { + out[i] = sgrRe.ReplaceAllString(l, "") + } + return out +} + +// richDigest is v0.16.0 written the way abcd's own changelog is: paragraphs +// with a bold lead or none, code spans, a break, a fix, and more bold leads +// than the summary has room for as headlines. +func richDigest(t *testing.T) *releasedigest.Digest { + t.Helper() + entry := func(line string, recs ...string) map[string]any { + var rs []map[string]string + for i := 0; i < len(recs); i += 2 { + rs = append(rs, map[string]string{"id": recs[i], "impact": recs[i+1]}) + } + return map[string]any{"line": line, "records": rs} + } + entries := []map[string]any{ + entry("**A drive carries on from one command.** Typing `abcd drain --drive` again takes up the runs the interrupt left, with nothing else typed. It says so in one line.", "itd-11", "additive"), + entry("A drive's start lets go a run that no drain lists, releasing its reservation. The drain's first move never opens a lane beside it.", "iss-12", "fix", "iss-22", "fix"), + entry("**Verbs that move records now require a dry run first.** `capture resolve` takes `--dry-run`, which names what the run would move.", "itd-13", "breaking"), + entry("**Head four.** Body four.", "itd-14", "additive"), + entry("**Head five.** Body five.", "itd-15", "additive"), + entry("**Head six.** Body six.", "itd-16", "additive"), + entry("**Head seven.** Body seven.", "itd-17", "additive"), + entry("**Head eight.** Body eight.", "itd-18", "additive"), + entry("`abcd decide accept ` sets a proposed ADR accepted. It refuses at exit 2.", "itd-19", "additive", "iss-29", "fix"), + } + doc := map[string]any{"schema_version": 1, "releases": []map[string]any{ + {"tag": "v0.16.0", "base_tag": "v0.15.0", "entries": entries}, + {"tag": "v0.15.0", "base_tag": "v0.14.2", "entries": []map[string]any{entry("Fixed one.", "iss-1", "fix")}}, + {"tag": "v0.14.2", "base_tag": "v0.14.1", "entries": []map[string]any{entry("Fixed three.", "iss-3", "fix")}}, + }} + data, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + d, err := releasedigest.Parse(data) + if err != nil { + t.Fatal(err) + } + return d +} + +// richWorld is the world with the rich digest and nothing waiting. +func richWorld(t *testing.T) *world { + t.Helper() + w := newWorld(t) + digestRange = richDigest(t).Range + w.waiting = ahoy.WaitingSet{Questions: []ahoy.WaitingItem{}, Defaults: []ahoy.WaitingItem{}} + return w +} + +// TestFullReadsAsASummaryThenAreas is the person's view of a release: what +// needs them first, then the few headline changes, then the rest under the +// area each falls in, every change on one line with its record id, the +// markdown taken as styling rather than printed, and the way to read one +// change whole. +func TestFullReadsAsASummaryThenAreas(t *testing.T) { + richWorld(t) + f, err := Full("", "") + if err != nil { + t.Fatal(err) + } + want := []string{ + "abcd v0.16.0 (after v0.15.0): 9 changes", + " Needs you (1)", + " ! Verbs that move records now require a dry run first. (itd-13)", + " Headlines", + " * A drive carries on from one command. (itd-11)", + " * Head four. (itd-14)", + " * Head five. (itd-15)", + " * Head six. (itd-16)", + " * Head seven. (itd-17)", + " New (2)", + " - Head eight. (itd-18)", + " - abcd decide accept sets a proposed ADR accepted. (itd-19 and 1 more)", + " Fixed (1)", + " - A drive's start lets go a run that no drain lists, releasing its reservation. (iss-12 and 1 more)", + "The whole text of one change: " + ChangeCommand, + } + if !slices.Equal(f.Lines, want) { + t.Fatalf("full:\n%s\nwant:\n%s", strings.Join(f.Lines, "\n"), strings.Join(want, "\n")) + } + if got := RenderFull(f, Style{}); !slices.Equal(got, f.Lines) { + t.Fatalf("the plain rendering is not the summary's lines:\n%s", strings.Join(got, "\n")) + } +} + +// TestFullInColourIsThePlainFormStyled: at a terminal the same lines are +// drawn with colour and emphasis, and taking the styling off gives the plain +// form exactly, so the structure does not depend on colour. +func TestFullInColourIsThePlainFormStyled(t *testing.T) { + richWorld(t) + f, err := Full("", "") + if err != nil { + t.Fatal(err) + } + colour := RenderFull(f, Style{Colour: true}) + if !slices.Equal(plainOf(colour), f.Lines) { + t.Fatalf("the coloured form, unstyled:\n%s\nwant:\n%s", strings.Join(plainOf(colour), "\n"), strings.Join(f.Lines, "\n")) + } + joined := strings.Join(colour, "\n") + for _, want := range []string{"\x1b[1mabcd v0.16.0", "\x1b[1;31m", "\x1b[36mabcd decide accept \x1b[0m"} { + if !strings.Contains(joined, want) { + t.Errorf("the coloured form lacks %q:\n%q", want, joined) + } + } + if strings.Contains(joined, "**") { + t.Errorf("markdown emphasis printed raw:\n%s", joined) + } +} + +// TestFullMasksEveryChangelogLine: a changelog line is untrusted text, so an +// escape or a C1 control in one is masked before any styling is composed, +// and the only escapes drawn are the renderer's own. +func TestFullMasksEveryChangelogLine(t *testing.T) { + f := FullSummary{Summary: releasedigest.Summary{To: "v0.16.0", Releases: []releasedigest.Release{{ + Tag: "v0.16.0", + Entries: []releasedigest.Entry{ + {Line: "Clears \x1b[2Jthe screen\u009b31m here. More.", Records: []releasedigest.Record{{ID: "iss-1", Impact: releasedigest.ImpactFix}}}, + {Line: "**Lead \x1b]0;title\x07 here.** Body.", Records: []releasedigest.Record{{ID: "itd-2", Impact: releasedigest.ImpactAdditive}}}, + }, + }}}} + for _, st := range []Style{{}, {Colour: true}, {Colour: true, Width: 40}} { + lines := RenderFull(f, st) + for _, l := range plainOf(lines) { + if strings.ContainsAny(l, "\x1b\u009b\x07") { + t.Errorf("%+v: an untrusted control reached a line: %q", st, l) + } + } + joined := strings.Join(lines, "\n") + if !strings.Contains(joined, "Clears ?[2Jthe screen?31m") { + t.Errorf("%+v: the masked line is not shown masked:\n%q", st, joined) + } + } + d := RenderChange(ChangeDetail{ID: "iss-1", Changes: []CitedChange{{Release: "v0.16.0", Entry: f.Summary.Releases[0].Entries[0]}}}, Style{Colour: true, Width: 30}) + for _, l := range plainOf(d) { + if strings.ContainsAny(l, "\x1b\u009b") { + t.Errorf("an untrusted control reached the whole text: %q", l) + } + } +} + +// TestFullFitsTheWindow: at a terminal each change takes one line that fits +// the window, cut with an ellipsis where its summary is longer. +func TestFullFitsTheWindow(t *testing.T) { + richWorld(t) + f, err := Full("", "") + if err != nil { + t.Fatal(err) + } + for _, st := range []Style{{Colour: true, Width: 50}, {Width: 50, ASCII: true}} { + lines := plainOf(RenderFull(f, st)) + cut := false + for _, l := range lines { + if strings.HasPrefix(l, "The whole text") { + continue + } + if c := textwidth.Columns(l); c > 50 { + t.Errorf("%+v: %d columns: %q", st, c, l) + } + if strings.Contains(l, "(iss-12 and 1 more)") && (strings.Contains(l, "…") || strings.Contains(l, "...")) { + cut = true + } + } + if !cut { + t.Errorf("%+v: the long summary was not cut to the window:\n%s", st, strings.Join(lines, "\n")) + } + } +} + +// TestChangeShowsOneChangeWhole: the whole paragraph is shown only on +// request, for the change citing a named record, wrapped to the window; a +// record no change in the range cites, and a word that is no record id, are +// refused. +func TestChangeShowsOneChangeWhole(t *testing.T) { + richWorld(t) + c, err := Change("", "iss-22") + if err != nil { + t.Fatal(err) + } + want := []string{ + "abcd v0.16.0: iss-12 (fix), iss-22 (fix)", + " A drive's start lets go a run that no drain lists, releasing its reservation. The drain's first move never opens a lane beside it.", + } + if !slices.Equal(c.Lines, want) { + t.Fatalf("change:\n%s\nwant:\n%s", strings.Join(c.Lines, "\n"), strings.Join(want, "\n")) + } + narrow := plainOf(RenderChange(c, Style{Colour: true, Width: 40})) + if len(narrow) < 4 { + t.Fatalf("the whole text was not wrapped:\n%s", strings.Join(narrow, "\n")) + } + for _, l := range narrow[1:] { + if textwidth.Columns(l) > 40 { + t.Errorf("wrapped line of %d columns: %q", textwidth.Columns(l), l) + } + } + lead, err := Change("", "itd-11") + if err != nil { + t.Fatal(err) + } + styled := strings.Join(RenderChange(lead, Style{Colour: true, Width: 200}), "\n") + if !strings.Contains(styled, "\x1b[1mA\x1b[0m") || !strings.Contains(styled, "\x1b[36mabcd drain --drive\x1b[0m") || strings.Contains(styled, "**") { + t.Errorf("the whole text's markdown is not drawn as styling:\n%q", styled) + } + if _, err := Change("", "iss-999"); !errors.Is(err, ErrNoSuchChange) { + t.Errorf("a record no change cites: %v", err) + } + if _, err := Change("", "drop table"); !errors.Is(err, ErrNotRecordID) { + t.Errorf("a word that is no record id: %v", err) + } +} + +// TestFullDegradesInANarrowWindow: in a window too narrow for a summary and +// its record id beside it, a change's line drops the id and is cut, so it +// still fits the window. +func TestFullDegradesInANarrowWindow(t *testing.T) { + richWorld(t) + f, err := Full("", "") + if err != nil { + t.Fatal(err) + } + for _, width := range []int{12, 20, 28} { + for _, l := range plainOf(RenderFull(f, Style{Colour: true, Width: width})) { + if strings.HasPrefix(l, " ") && textwidth.Columns(l) > width { + t.Errorf("width %d: a change line of %d columns: %q", width, textwidth.Columns(l), l) + } + } + } +} + +// TestInlineIsLinearInStrongEmphasis: reading a line with many ** pairs +// before a code span does not copy the rest of the line at each opener, so +// its cost stays in line with the line's length. +func TestInlineIsLinearInStrongEmphasis(t *testing.T) { + line := strings.Repeat("**a**b", 10000) + " `x`" + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + spans := inline(line) + runtime.ReadMemStats(&after) + if len(spans) != 20001 || !spans[0].bold || spans[1].bold || !spans[20000].code { + t.Fatalf("read %d spans, first %+v", len(spans), spans[:min(2, len(spans))]) + } + if got := after.TotalAlloc - before.TotalAlloc; got > 32<<20 { + t.Fatalf("reading a %d-byte line allocated %d bytes", len(line), got) + } +} diff --git a/internal/core/releasedigest/releasedigest.go b/internal/core/releasedigest/releasedigest.go index ee708bacae..a115c59d49 100644 --- a/internal/core/releasedigest/releasedigest.go +++ b/internal/core/releasedigest/releasedigest.go @@ -67,6 +67,10 @@ const ( // recordIDRe is a cited record id: the grammar the cut's bijection reads. var recordIDRe = regexp.MustCompile(`\A(?:itd|iss)-[0-9]+\z`) +// IsRecordID reports whether s is a record id a line may cite: itd-N or iss-N, +// within the cap the cut holds an id to. +func IsRecordID(s string) bool { return len(s) <= maxRecordIDBytes && recordIDRe.MatchString(s) } + // ErrNotReleaseTag is Range's refusal of a version that is not exactly a // release tag; a dev build takes no part. var ErrNotReleaseTag = errors.New("not a release tag of the form vMAJOR.MINOR.PATCH") diff --git a/internal/surface/cli/update_news.go b/internal/surface/cli/update_news.go index 14d4684ffb..27787d33d5 100644 --- a/internal/surface/cli/update_news.go +++ b/internal/surface/cli/update_news.go @@ -4,7 +4,8 @@ package cli // (spc-2610170635097509, step 7): `abcd update news` prints what the agent // relays at the start of its first reply, the one line per release saying // what changed and the offer to run setup again; --full prints the full -// summary; --answer records the person's answer to the offer and --seen that +// summary, drawn for a person at a terminal (afterupdate.RenderFull), and +// --change one change whole; --answer records the person's answer to the offer and --seen that // the news was read. Bare and --full write nothing. The words are core's // (internal/core/afterupdate): numbers, checked release tags, core's titles // and the digest inside the binary, never the repository's text. @@ -23,6 +24,7 @@ import ( "github.com/intentdriven/abcd/internal/core/afterupdate" "github.com/intentdriven/abcd/internal/core/ahoy" "github.com/intentdriven/abcd/internal/fsutil" + "github.com/intentdriven/abcd/internal/term" "github.com/intentdriven/abcd/internal/termsafe" "github.com/spf13/cobra" ) @@ -37,22 +39,26 @@ type newsRecorded struct { func newUpdateNewsCommand(asJSON *bool) *cobra.Command { var full, seen bool - var answer string + var answer, change string cmd := &cobra.Command{ Use: "news", Args: cobra.NoArgs, Long: "After an abcd update, print what the agent relays at the start of its first reply: " + "one line per release this computer has not been shown, saying how many changes it made and which need the person to act, " + "and, where the update brings this repository setup it never answered, the offer to run setup again. " + - "It prints nothing when there is nothing to say. --full prints every change of the releases since the last update, " + - "those that need action first, each with the record it cites, and what waits here. " + + "It prints nothing when there is nothing to say. --full prints the releases since the last update for a person: " + + "per release, what needs them, then the headline changes, then the rest as new or fixed, one line per change with the record it cites, " + + "in colour at a terminal and plain elsewhere, then what waits here; --change prints the whole text of the change citing that record. " + "Neither writes anything. Only a person's reply is recorded: --answer yes|not-now records the answer to the offer " + "for this repository and release, once, and --seen records that the news was read where no offer was made, both in " + "abcd's home folder. On yes, run " + onlyWaitingCommand + ". The text comes only from the binary's own digest and " + "checked release numbers, and nothing is fetched.", RunE: func(cmd *cobra.Command, _ []string) error { answered := cmd.Flags().Changed("answer") + changed := cmd.Flags().Changed("change") switch { + case changed && (answered || seen): + return &exitError{Code: 2, Msg: "abcd update news: --change shows one change and writes nothing, so it takes neither --answer nor --seen; nothing was written"} case answered && (full || seen): return &exitError{Code: 2, Msg: "abcd update news: --answer records the reply to the offer and takes neither --full nor --seen; nothing was written"} case full && seen: @@ -69,12 +75,22 @@ func newUpdateNewsCommand(asJSON *bool) *cobra.Command { return runUpdateNewsAnswer(cmd, cwd, answer, *asJSON) case seen: return runUpdateNewsSeen(cmd, *asJSON) + case changed: + c, err := afterupdate.Change(cwd, change) + if err != nil { + return updateNewsRefusal(err) + } + return render(cmd.OutOrStdout(), *asJSON, c, func(w io.Writer) { + printNewsView(w, c.Lines, func(st afterupdate.Style) []string { return afterupdate.RenderChange(c, st) }) + }) case full: f, err := afterupdate.Full(cwd, "") if err != nil { return updateNewsRefusal(err) } - return render(cmd.OutOrStdout(), *asJSON, f, func(w io.Writer) { printUpdateNewsLines(w, f.Lines) }) + return render(cmd.OutOrStdout(), *asJSON, f, func(w io.Writer) { + printNewsView(w, f.Lines, func(st afterupdate.Style) []string { return afterupdate.RenderFull(f, st) }) + }) } m, err := afterupdate.Moment(cwd) if err != nil { @@ -84,6 +100,7 @@ func newUpdateNewsCommand(asJSON *bool) *cobra.Command { }, } cmd.Flags().BoolVar(&full, "full", false, "print the full summary of the releases since the last update and what waits here; writes nothing") + cmd.Flags().StringVar(&change, "change", "", "print the whole text of the change citing this record id (itd-N or iss-N) in the releases since the last update; writes nothing") enumFlag(cmd.Flags(), &answer, "answer", "", "record the person's reply to the offer, ", afterupdate.Answers(), ", once for this repository and release; run it only with their reply") cmd.Flags().BoolVar(&seen, "seen", false, "record that the person read the news where no offer was made; run it only after they were shown it") @@ -162,7 +179,8 @@ func updateNewsSessionStart(w io.Writer, cwd string, det ahoy.DetectionResult) [ // updateNewsRefusal turns core's refusals into exit 2, naming that nothing // was written; any other error is returned as it is. func updateNewsRefusal(err error) error { - for _, refusal := range []error{afterupdate.ErrNotRelease, afterupdate.ErrNoOffer, afterupdate.ErrAlreadyAnswered, afterupdate.ErrBadAnswer} { + for _, refusal := range []error{afterupdate.ErrNotRelease, afterupdate.ErrNoOffer, afterupdate.ErrAlreadyAnswered, afterupdate.ErrBadAnswer, + afterupdate.ErrNotRecordID, afterupdate.ErrNoSuchChange} { if errors.Is(err, refusal) { return &exitError{Code: 2, Msg: "abcd update news: " + err.Error() + "; nothing was written"} } @@ -176,3 +194,28 @@ func printUpdateNewsLines(w io.Writer, lines []string) { fmt.Fprintln(w, termsafe.Sanitize(l)) } } + +// printNewsView writes the full summary or one change: off a terminal its +// plain lines, sanitised as every news line is; at one, the drawing for a +// person, in colour unless NO_COLOR or the terminal says otherwise, fitted to +// the window. The drawing masks every changelog line before it composes its +// own styling, so its lines are written as drawn. +func printNewsView(w io.Writer, plain []string, draw func(afterupdate.Style) []string) { + if !bannerTTY(w) { + printUpdateNewsLines(w, plain) + return + } + var f *os.File + if file, ok := streamOf(w).(*os.File); ok { + f = file + } + cols, _ := term.Size(f, os.Getenv) + st := afterupdate.Style{ + Colour: term.ResolveColorMode(os.Getenv, false) != term.Mono, + Width: cols, + ASCII: !term.UTF8Locale(os.Getenv), + } + for _, l := range draw(st) { + fmt.Fprintln(w, l) + } +} diff --git a/internal/surface/cli/update_news_test.go b/internal/surface/cli/update_news_test.go index 3f26553c71..221f5fedbb 100644 --- a/internal/surface/cli/update_news_test.go +++ b/internal/surface/cli/update_news_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "os" "path/filepath" "regexp" @@ -13,6 +14,8 @@ import ( "github.com/intentdriven/abcd/internal/abcdhome" "github.com/intentdriven/abcd/internal/core" + "github.com/intentdriven/abcd/internal/core/releasedigest" + "github.com/intentdriven/abcd/internal/textwidth" ) // afterUpdateRepo is Alice's repository at the CLI: a git repository with one @@ -288,3 +291,92 @@ func TestUpdateRefusesAWordThatIsNeitherATagNorASubverb(t *testing.T) { t.Fatalf("a mistyped sub-verb constructed the updater %d times", calls) } } + +// aliceChangeID is a record a change of v0.15.0 cites in the binary's digest. +func aliceChangeID(t *testing.T) string { + t.Helper() + sum, err := releasedigest.Range("", "v0.15.0") + if err != nil || len(sum.Releases) == 0 || len(sum.Releases[0].Entries) == 0 { + t.Fatalf("the digest describes no v0.15.0: %+v, %v", sum, err) + } + return sum.Releases[0].Entries[0].Records[0].ID +} + +// TestUpdateNewsFullIsReadableOffATerminal: off a terminal --full keeps the +// person's structure (a summary, then the changes by area, one line each) +// with no colour and no markdown printed raw, and names the way to read one +// change whole; at a terminal the same lines are drawn with colour. +func TestUpdateNewsFullIsReadableOffATerminal(t *testing.T) { + afterUpdateRepo(t) + plain, stderr, code := runUpdateNews("--full") + if code != 0 { + t.Fatalf("--full exit %d, stderr %q", code, stderr) + } + if strings.Contains(plain, "\x1b") || strings.Contains(plain, "**") { + t.Fatalf("--full off a terminal carries colour or raw markdown:\n%s", plain) + } + if !strings.Contains(plain, "\n New (") && !strings.Contains(plain, "\n Fixed (") { + t.Fatalf("--full is not grouped by area:\n%s", plain) + } + if !strings.Contains(plain, "\nThe whole text of one change: abcd update news --change \n") { + t.Fatalf("--full does not name the way to read one change whole:\n%s", plain) + } + for _, l := range strings.Split(plain, "\n") { + if strings.HasPrefix(l, " ") && !regexp.MustCompile(`\((itd|iss)-[0-9]+( and [0-9]+ more)?\)\z`).MatchString(l) { + t.Errorf("a change line without its record id: %q", l) + } + } + + prev := bannerTTY + bannerTTY = func(io.Writer) bool { return true } + t.Cleanup(func() { bannerTTY = prev }) + t.Setenv("NO_COLOR", "") + t.Setenv("TERM", "xterm-256color") + t.Setenv("COLUMNS", "72") + coloured, _, code := runUpdateNews("--full") + if code != 0 || !strings.Contains(coloured, "\x1b[1mabcd v0.15.0") || strings.Contains(coloured, "**") { + t.Fatalf("--full at a terminal is not drawn with colour (exit %d):\n%q", code, coloured) + } + for _, l := range strings.Split(regexp.MustCompile("\x1b\\[[0-9;]*m").ReplaceAllString(coloured, ""), "\n") { + if strings.HasPrefix(l, " ") && textwidth.Columns(l) > 72 { + t.Errorf("a change line wider than the window: %q", l) + } + } +} + +// TestUpdateNewsChangeShowsOneChangeWhole: --change prints the whole text of +// the change citing the named record, and writes nothing; a word that is no +// record id is refused without being repeated, as is a mixed request. +func TestUpdateNewsChangeShowsOneChangeWhole(t *testing.T) { + repo, home, _ := afterUpdateRepo(t) + before := pathsUnder(t, home) + pathsUnder(t, repo) + id := aliceChangeID(t) + out, stderr, code := runUpdateNews("--change", id) + if code != 0 || !strings.HasPrefix(out, "abcd v0.15.0: "+id+" (") { + t.Fatalf("--change %s: exit %d, stderr %q:\n%s", id, code, stderr, out) + } + jsonOut, _, code := runUpdateNews("--change", id, "--json") + var c struct { + ID string `json:"id"` + Lines []string `json:"lines"` + } + if code != 0 || json.Unmarshal([]byte(jsonOut), &c) != nil || c.ID != id || strings.Join(c.Lines, "\n")+"\n" != out { + t.Fatalf("--change --json does not carry the change: %s", jsonOut) + } + for _, args := range [][]string{ + {"--change", "nope-planted"}, + {"--change", "iss-1", "--seen"}, + {"--change", "iss-1", "--answer", "yes"}, + } { + _, stderr, code := runUpdateNews(args...) + if code != 2 || !strings.Contains(stderr, "abcd update news: ") || strings.Contains(stderr, "planted") { + t.Errorf("%v: exit %d, stderr %q; want the verb's usage error, the value not repeated", args, code, stderr) + } + } + if _, stderr, code := runUpdateNews("--change", "iss-1"); code != 2 || !strings.Contains(stderr, "iss-1") { + t.Errorf("a record no change cites: exit %d, stderr %q", code, stderr) + } + if after := pathsUnder(t, home) + pathsUnder(t, repo); after != before { + t.Fatalf("--change wrote:\n%s", after) + } +}