mirror of
https://github.com/larksuite/cli.git
synced 2026-08-03 08:32:46 +08:00
* refactor: add output emitter contract and differential harness Introduce a leaf Emitter in internal/output that composes the existing output primitives (content-safety scan, envelope, jq, format rendering, notice) behind a single command-scoped port. The emitter is unwired: no production caller is migrated, so CLI output stays byte-for-byte unchanged. A differential test harness drives the real legacy entry points (RuntimeContext.Out/OutRaw/OutFormat/..., WriteSuccessEnvelope and the pagination formatter) and asserts byte-identical stdout/stderr plus typed errors, locking behavior before later slices migrate callers. * refactor: tighten emitter API and cover pagination with real tests - split Emitter.Success/PartialFailure and drop EmitOptions.OK so a missing ok flag can no longer silently emit ok:false - give StreamPage its own StreamOptions (format + pretty) instead of reusing EmitOptions, making "jq needs aggregation" a compile-time fact - pin the Emitter jq-error contract (returns error, writes no stderr); the caller adapter re-emits the legacy stderr line on migration - add in-package tests driving the real apiPaginate/servicePaginate over a mock transport: multi-page aggregation, empty-result fallback, MarkRaw handling, and the business-error raw-response red line * test: use standard TestFactory harness for pagination tests Replace the hand-rolled RoundTripper + APIClient construction in the apiPaginate/servicePaginate tests with cmdutil.TestFactory and its httpmock.Registry, and isolate LARKSUITE_CLI_CONFIG_DIR to t.TempDir(), matching the repo's standard HTTP-mocked test convention. Assertions and coverage (multi-page aggregation, empty-result fallback, MarkRaw, and the business-error raw-response red line) are unchanged. * refactor: route success output through the single Emitter port Migrate the success-output surfaces onto internal/output's Emitter, byte-for-byte identical (proven by frozen golden diffs and the real paginate/HandleResponse tests): - RuntimeContext.Out/OutRaw/OutFormat/OutFormatRaw/OutPartialFailure now build an Emitter and call Success/PartialFailure; emit and outFormat are removed. An adapter maps the returned error back to the legacy outputErrOnce / jq-error stderr / exit-code behavior. - WriteSuccessEnvelope degrades to a thin Emitter.Success delegate; its 8 callers are unchanged. - apiPaginate/servicePaginate stream pages via Emitter.StreamPage; the aggregate and business-error raw-response branches are untouched. - HandleResponse routes its non-JSON structured-response branch through Emitter.Success. Frozen golden fixtures replace the runtime legacy oracles so the differential harness cannot go self-referential after migration. * fix: keep _notice on struct payloads in Emitter's unknown-format fallback printLegacyDataJSON now normalizes via toGeneric first (matching FormatValue), so a struct / named-map payload retains its injected _notice on the unknown-format -> JSON fallback rather than dropping it silently. Add a regression test that fails against the pre-fix path. * refactor: make the Emitter own write failures and stop mutating inputs Route every Emitter stdout path through a render-to-buffer-then-copy helper so a marshal/render failure leaves stdout empty and surfaces a typed internal error (with cause), and a stdout write failure is propagated instead of silently swallowed. Leaf writers gain error-returning Write* cores; the legacy Print*/FormatValue wrappers keep their exact behavior for unmigrated callers. - handleEmitterError now captures every error, not only the jq/safety branches; flip OutRaw's write-error test to assert propagation. - Clone the map before injecting _notice so a caller's payload is never mutated and an existing _notice is never overwritten. - Preserve jq's own typed error (validation/api) on a bad expression or runtime failure; only wrap genuine stdout write failures. - Split tests: normative emitter_contract_test.go vs frozen emitter_legacy_compat_test.go (base SHA recorded, self-update env vars removed). * fix: satisfy license-header and forbidigo lint on the emitter changes - Move the base-SHA note below the copyright header in the renamed legacy-compat test so the license-header check sees a valid header at the top. - Route the leaf wrappers' marshal/format stderr messages through a single legacyStderrf helper (one //nolint:forbidigo) instead of bare os.Stderr, preserving exact legacy behavior for unmigrated direct callers while passing forbidigo; drop the now-unused os imports. * fix: stop legacy CSV wrappers reporting write failures to stderr Align FormatAsCSV/FormatAsCSVPaginated and FormatValue/FormatPage's CSV branch with the other leaf wrappers: report only marshal failures, swallow write failures. Previously they emitted a 'csv write error' for the (empty) line and the JSON-fallback write failures that the pre-refactor code ignored, and mislabeled a JSON write failure as a CSV one. Failure-path only; success output is unchanged (golden double-diff still byte-for-byte).
157 lines
4.0 KiB
Go
157 lines
4.0 KiB
Go
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package output
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
)
|
|
|
|
const maxColWidth = 100
|
|
|
|
// FormatAsTable formats data as a table and writes it to w.
|
|
// - []interface{} (array of objects) → header + separator + rows
|
|
// - map[string]interface{} (single object) → key-value two-column table
|
|
// - empty array → "(empty)"
|
|
func FormatAsTable(w io.Writer, data interface{}) {
|
|
if err := WriteTable(w, data); isOutputMarshalError(err) {
|
|
legacyStderrf("json marshal error: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// WriteTable formats data as a table and returns marshal or write errors.
|
|
func WriteTable(w io.Writer, data interface{}) error {
|
|
return WriteTablePaginated(w, data, true)
|
|
}
|
|
|
|
// FormatAsTablePaginated formats data as a table with pagination awareness.
|
|
// When isFirstPage is true, outputs the header; otherwise only data rows.
|
|
func FormatAsTablePaginated(w io.Writer, data interface{}, isFirstPage bool) {
|
|
if err := WriteTablePaginated(w, data, isFirstPage); isOutputMarshalError(err) {
|
|
legacyStderrf("json marshal error: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// WriteTablePaginated formats data as a table and returns marshal or write errors.
|
|
func WriteTablePaginated(w io.Writer, data interface{}, isFirstPage bool) error {
|
|
rows, cols, isList := prepareRows(data)
|
|
if cols == nil {
|
|
if isList {
|
|
_, err := fmt.Fprintln(w, "(empty)")
|
|
return err
|
|
} else {
|
|
// Not a list and not an object — print as JSON fallback
|
|
return WriteJSON(w, data)
|
|
}
|
|
}
|
|
|
|
if len(rows) == 0 {
|
|
if isFirstPage {
|
|
_, err := fmt.Fprintln(w, "(empty)")
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
if !isList {
|
|
// Single object: key-value two-column format
|
|
return formatKeyValueTable(w, rows[0], cols)
|
|
}
|
|
|
|
// Calculate column widths (clamped to maxColWidth)
|
|
widths := computeColumnWidths(rows, cols)
|
|
|
|
if isFirstPage {
|
|
if err := writeHeader(w, cols, widths); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
for _, row := range rows {
|
|
if err := writeRow(w, row, cols, widths); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// formatKeyValueTable renders a single object as a two-column key-value table.
|
|
func formatKeyValueTable(w io.Writer, row map[string]string, cols []string) error {
|
|
maxKeyWidth := 0
|
|
for _, col := range cols {
|
|
kw := stringWidth(col)
|
|
if kw > maxKeyWidth {
|
|
maxKeyWidth = kw
|
|
}
|
|
}
|
|
|
|
for _, col := range cols {
|
|
val := row[col]
|
|
val = truncateToWidth(val, maxColWidth)
|
|
if _, err := fmt.Fprintf(w, "%s %s\n", padToWidth(col, maxKeyWidth), val); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// computeColumnWidths returns display widths for each column, clamped to maxColWidth.
|
|
func computeColumnWidths(rows []map[string]string, cols []string) []int {
|
|
widths := make([]int, len(cols))
|
|
for i, col := range cols {
|
|
widths[i] = stringWidth(col)
|
|
}
|
|
for _, row := range rows {
|
|
for i, col := range cols {
|
|
cw := stringWidth(row[col])
|
|
if cw > widths[i] {
|
|
widths[i] = cw
|
|
}
|
|
}
|
|
}
|
|
// Clamp to max
|
|
for i := range widths {
|
|
if widths[i] > maxColWidth {
|
|
widths[i] = maxColWidth
|
|
}
|
|
}
|
|
return widths
|
|
}
|
|
|
|
// writeHeader writes the header row and separator line.
|
|
func writeHeader(w io.Writer, cols []string, widths []int) error {
|
|
var header []string
|
|
var sep []string
|
|
for i, col := range cols {
|
|
header = append(header, padToWidth(col, widths[i]))
|
|
sep = append(sep, strings.Repeat("─", widths[i]))
|
|
}
|
|
if _, err := fmt.Fprintln(w, strings.Join(header, " ")); err != nil {
|
|
return err
|
|
}
|
|
_, err := fmt.Fprintln(w, strings.Join(sep, " "))
|
|
return err
|
|
}
|
|
|
|
// writeRow writes a single data row.
|
|
func writeRow(w io.Writer, row map[string]string, cols []string, widths []int) error {
|
|
var cells []string
|
|
for i, col := range cols {
|
|
val := truncateToWidth(row[col], widths[i])
|
|
cells = append(cells, padToWidth(val, widths[i]))
|
|
}
|
|
_, err := fmt.Fprintln(w, strings.Join(cells, " "))
|
|
return err
|
|
}
|
|
|
|
// padToWidth pads a string with spaces to reach the target display width.
|
|
func padToWidth(s string, targetWidth int) string {
|
|
sw := stringWidth(s)
|
|
if sw >= targetWidth {
|
|
return s
|
|
}
|
|
return s + strings.Repeat(" ", targetWidth-sw)
|
|
}
|