Skip to content

fix: register and consume --json shorthand for custom-format shortcuts#1737

Merged
zhaojunlin0405 merged 11 commits into
mainfrom
fix/mail-triage-json-shorthand
Jul 8, 2026
Merged

fix: register and consume --json shorthand for custom-format shortcuts#1737
zhaojunlin0405 merged 11 commits into
mainfrom
fix/mail-triage-json-shorthand

Conversation

@zhaojunlin0405

@zhaojunlin0405 zhaojunlin0405 commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

--json (shorthand for --format json) was only registered when the framework injected the default format flag, so shortcuts declaring their own format flag — mail +triage, mail +watch, base +record-list — rejected it with unknown flag: --json. In addition, nothing ever consumed the flag's value: it appeared to work on other commands only because their format already defaults to json, and --format table --json silently ignored the shorthand.

This change decouples shorthand registration from default-format injection and adds an explicit consumption step:

  • ensureJSONShorthand registers --json when a command has a format flag whose Enum contains json and the json flag name is not already taken.
  • applyJSONShorthand folds the shorthand into the format flag itself before it is consumed, so both the cached format and per-command reads observe json. An explicitly passed --format always wins over the shorthand.
  • Commands declaring their own --json (event +subscribe's pretty-print switch, base +record-search / +record-get's request-body payload) are untouched on both the registration and consumption paths.

Behavior change: invalid --format values on the five affected commands now fail enum validation (exit 2, listing allowed values) instead of silently falling back to the default format (mail +triage) or erroring later inside Execute (the others).

Changes

  • shortcuts/common/runner.go: add shortcutDeclaresJSONFlag / shortcutFormatSupportsJSON / ensureJSONShorthand / applyJSONShorthand; decouple the --json registration from the default-format injection block; apply normalization in newRuntimeContext before the format value is cached
  • shortcuts/mail/mail_triage.go, shortcuts/mail/mail_watch.go, shortcuts/base/record_list.go: add Enum metadata to the existing format flag declarations (one line each; defaults unchanged)
  • skills/lark-mail/references/lark-mail-watch.md: correct the --format row (default data, values json/data) so the docs match the added Enum. The --json shorthand is deliberately left undocumented — it stays a silent fallback (typing --json no longer errors), while the skill docs keep steering agents to --format json
  • New tests: shortcuts/common/runner_json_shorthand_test.go (registration matrix + normalization precedence), shortcuts/mail/mail_json_shorthand_test.go, shortcuts/base/record_json_shorthand_test.go

Test Plan

  • go test ./shortcuts/...: registration matrix (5 cases), normalization precedence (6 cases), mail behavior (help / dry-run equivalence / explicit-table precedence / enum error, 6 cases), base registration + request-body regression (3 cases) — all green
  • go build ./... and incremental golangci-lint clean
  • Sandbox E2E: 11/11 scenarios pass, covering dry-run byte equivalence between --json and --format json, explicit --format table --json precedence via the jq mutual-exclusion probe, enum validation errors on all five commands, and record-search / record-get request-body --json regression anchors

Related Issues

  • Fixes unknown flag: --json on mail +triage; the same registration gap on mail +watch and base +record-list is fixed by the shared rule
  • Follow-up (tracked separately, pre-existing and unchanged by this PR): mail +triage --jq is accepted but silently ignored because the command's custom output path bypasses the common jq filter

Summary by CodeRabbit

  • New Features

    • Added a --json shorthand for several record and mail commands, with help text showing when it’s available.
    • Improved format options so supported output modes are clearly listed and validated.
  • Bug Fixes

    • Prevented --json from overriding commands that already use --json for other input types.
    • Ensured --format takes precedence when both format options are provided.
    • Kept default output behavior unchanged when no format flags are set.
  • Documentation

    • Updated mail help/reference details to reflect the latest output mode defaults and descriptions.

@zhaojunlin0405 zhaojunlin0405 added bug Something isn't working domain/base PR touches the base domain domain/mail PR touches the mail domain labels Jul 3, 2026
@CLAassistant

CLAassistant commented Jul 3, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions Bot added the size/L Large or sensitive change across domains or core paths label Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR centralizes --json shorthand handling for --format flags in the shortcut runner, adding helper functions to detect existing json flags and format enum support, and conditionally registers/applies the shorthand safely. It constrains format flags with explicit enums for base record and mail shortcuts, adds corresponding tests, and updates mail-watch reference documentation.

Changes

--json shorthand and format enum updates

Layer / File(s) Summary
Runner shorthand wiring
shortcuts/common/runner.go
Adds shortcutDeclaresJSONFlag, shortcutFormatSupportsJSON, ensureJSONShorthand, applyJSONShorthand helpers; registers --json shorthand safely and applies it before caching RuntimeContext.Format.
Runner shorthand tests
shortcuts/common/runner_json_shorthand_test.go
Adds tests for shorthand registration conditions, precedence between --json/--format, and preservation of self-declared --json flags.
Base record format and shortcut tests
shortcuts/base/record_list.go, shortcuts/base/record_json_shorthand_test.go
Adds Enum constraint (markdown, json) to record-list format flag; tests verify --json shorthand registration and preserved --json semantics on record-search/record-get.
Mail format constraints and CLI tests
shortcuts/mail/mail_triage.go, shortcuts/mail/mail_watch.go, shortcuts/mail/mail_json_shorthand_test.go, skills/lark-mail/references/lark-mail-watch.md
Adds Enum constraints to mail triage/mail watch format flags; adds CLI tests for help text, JSON shorthand output, format precedence, and invalid format errors; updates reference doc defaults/description.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant CobraCommand
  participant runner.go
  participant RuntimeContext

  User->>CobraCommand: run shortcut with --json
  CobraCommand->>runner.go: registerShortcutFlagsWithContext
  runner.go->>runner.go: ensureJSONShorthand(cmd, s)
  runner.go-->>CobraCommand: --json registered if safe

  CobraCommand->>runner.go: newRuntimeContext(cmd, s)
  runner.go->>runner.go: applyJSONShorthand(cmd, s)
  alt --json set and no explicit --format
    runner.go->>runner.go: set format=json
  else explicit --format provided
    runner.go->>runner.go: keep user-specified format
  end
  runner.go->>RuntimeContext: cache Format value
  RuntimeContext-->>User: command executes with resolved format
Loading

Possibly related PRs

  • larksuite/cli#1104: Both PRs modify shortcuts/common/runner.go to add/register a --json flag as shorthand for --format json with conflict-avoidance logic.
  • larksuite/cli#1156: Both PRs modify how shortcut --format is registered/read from flags, with this PR building on that timing by applying --json shorthand before caching RuntimeContext.Format.
  • larksuite/cli#726: Both PRs touch the +record-list --format flag, with this PR further constraining it via an Enum.

Suggested labels: feature

Suggested reviewers: liangshuo-1, kongenpei

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: registering and consuming the --json shorthand for custom-format shortcuts.
Description check ✅ Passed The description follows the required template and covers summary, changes, test plan, and related issues with sufficient detail.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/mail-triage-json-shorthand

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@de384c02667e3d164751570ee6bf7562491c4ead

🧩 Skill update

npx skills add larksuite/cli#fix/mail-triage-json-shorthand -y -g

@codecov

codecov Bot commented Jul 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.66667% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.40%. Comparing base (d0cde9a) to head (de384c0).
⚠️ Report is 32 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/common/runner.go 86.20% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1737      +/-   ##
==========================================
- Coverage   74.51%   74.40%   -0.11%     
==========================================
  Files         852      860       +8     
  Lines       87655    89460    +1805     
==========================================
+ Hits        65312    66564    +1252     
- Misses      17315    17744     +429     
- Partials     5028     5152     +124     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
shortcuts/common/runner_json_shorthand_test.go (1)

29-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comment language consistency.

Test comments are in Chinese while the rest of the codebase (e.g. runner.go) documents in English, which may hinder readability for the broader contributor base.

Also applies to: 49-49, 61-61, 73-73, 110-110, 120-120, 130-130, 140-140, 150-150, 170-170, 187-187

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/common/runner_json_shorthand_test.go` around lines 29 - 30, The
test comments in runner_json_shorthand_test.go are written in Chinese while the
surrounding codebase documentation is in English, so update the affected comment
blocks to English for consistency and readability. Keep the existing test names
and behavior unchanged, and revise the inline comments near the JSON shorthand
tests so they clearly describe the cases in English across all referenced
occurrences.
shortcuts/mail/mail_watch.go (1)

102-102: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Manual format validation now redundant after adding Enum.

With Enum: []string{"json", "data"} on the format flag (Line 102), the framework will reject any other value before Execute runs — confirmed by TestMailTriageEnumRejectsUnknownFormat's dry-run test rejecting invalid values without reaching business logic. The switch/default error branch at Lines 188-192 is therefore dead code for real invocations.

Consider removing it (or documenting why it's kept as defense-in-depth) to avoid confusing future maintainers about where validation actually happens.

♻️ Proposed cleanup
 		outFormat := runtime.Str("format")
-		switch outFormat {
-		case "json", "data", "":
-		default:
-			return mailValidationParamError("--format", "invalid --format %q: must be json or data", outFormat)
-		}
 		msgFormat := runtime.Str("msg-format")

Also applies to: 188-192

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/mail/mail_watch.go` at line 102, The format validation in MailWatch
is now duplicated because the format flag already has an Enum on the flags
definition, so the framework rejects invalid values before execution reaches
business logic. Remove the unreachable default/error branch in MailWatch.Execute
that handles unknown format values, or keep it only if you add an explicit
comment explaining it as defense-in-depth; use the format flag definition and
the Execute switch on format as the symbols to locate the cleanup.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@shortcuts/mail/mail_json_shorthand_test.go`:
- Around line 80-92: The test in TestMailTriageEnumRejectsUnknownFormat
currently verifies only error message substrings; update it to assert typed
error metadata instead. Use errs.ProblemOf on the error returned by
runMountedMailShortcut to check the expected category/subtype/param for the
invalid --format value, and also verify cause preservation rather than relying
on strings.Contains checks on err.Error().

---

Nitpick comments:
In `@shortcuts/common/runner_json_shorthand_test.go`:
- Around line 29-30: The test comments in runner_json_shorthand_test.go are
written in Chinese while the surrounding codebase documentation is in English,
so update the affected comment blocks to English for consistency and
readability. Keep the existing test names and behavior unchanged, and revise the
inline comments near the JSON shorthand tests so they clearly describe the cases
in English across all referenced occurrences.

In `@shortcuts/mail/mail_watch.go`:
- Line 102: The format validation in MailWatch is now duplicated because the
format flag already has an Enum on the flags definition, so the framework
rejects invalid values before execution reaches business logic. Remove the
unreachable default/error branch in MailWatch.Execute that handles unknown
format values, or keep it only if you add an explicit comment explaining it as
defense-in-depth; use the format flag definition and the Execute switch on
format as the symbols to locate the cleanup.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 49f57623-1d3b-40eb-b5ca-f7fdf145065e

📥 Commits

Reviewing files that changed from the base of the PR and between a1506cd and eb56913.

📒 Files selected for processing (10)
  • shortcuts/base/record_json_shorthand_test.go
  • shortcuts/base/record_list.go
  • shortcuts/common/runner.go
  • shortcuts/common/runner_json_shorthand_test.go
  • shortcuts/mail/mail_json_shorthand_test.go
  • shortcuts/mail/mail_triage.go
  • shortcuts/mail/mail_watch.go
  • skills/lark-base/references/lark-base-data-query.md
  • skills/lark-mail/references/lark-mail-triage.md
  • skills/lark-mail/references/lark-mail-watch.md

Comment thread shortcuts/mail/mail_json_shorthand_test.go

@bubbmon233 bubbmon233 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

只看 mail 这块,有一个文档不一致需要修一下:mail +watch 的 skill 文档里还写着 --format 默认是 table,支持 table / json / data,但代码现在实际是默认 data,并且 Enum 只允许 json / data。这次 PR 加了 enum 校验后,用户照文档传 --format table 会直接失败。

建议把 skills/lark-mail/references/lark-mail-watch.md 里的参数说明改成类似:--format <mode> 默认 data,输出样式:json / data

@zhaojunlin0405

Copy link
Copy Markdown
Collaborator Author

@bubbmon233 Good catch — fixed in 16ba718.

The skills/lark-mail/references/lark-mail-watch.md --format row now matches the code: default data, allowed values json / data (dropped the stale table). As you noted, this PR's new enum turned a following-the-doc --format table from a silent no-op into a hard validation error, so the doc had to be corrected. mail +triage keeps table as a real default/value, so its doc is left unchanged.

@zhaojunlin0405 zhaojunlin0405 merged commit c04da47 into main Jul 8, 2026
51 checks passed
@zhaojunlin0405 zhaojunlin0405 deleted the fix/mail-triage-json-shorthand branch July 8, 2026 13:32
zhicong666-bytedance added a commit that referenced this pull request Jul 9, 2026
Source-Branch: features/F-lark-cli-vc-meeting-query-dual-scope-20260709
Source-Commit: c04da47
Source-Subject: fix: register and consume --json shorthand for custom-format shortcuts (#1737)
Repo: larksuite-cli-github
Synced-By: houzhicong
Timestamp: 20260709_042711Z
@liangshuo-1 liangshuo-1 mentioned this pull request Jul 9, 2026
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working domain/base PR touches the base domain domain/mail PR touches the mail domain size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants