Skip to content

feat(common): emit typed validation errors from shared shortcut pre-checks#1242

Merged
evandance merged 1 commit into
mainfrom
feat/errs-common-infra
Jun 3, 2026
Merged

feat(common): emit typed validation errors from shared shortcut pre-checks#1242
evandance merged 1 commit into
mainfrom
feat/errs-common-infra

Conversation

@evandance

@evandance evandance commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

Shared pre-check failures that every shortcut emits — @file/stdin input resolution, enum validation, and unsupported --dry-run — now leave the CLI as typed errs.* validation envelopes carrying subtype: invalid_argument and the offending flag as param. Wire type, exit code, and message text are unchanged; the new fields are additive, so existing consumers and not-yet-migrated domains are unaffected.

The shared common layer also gains typed replacements for its legacy error-producing helpers — validation and flag-group checks, chat/user ID validation, "me" open-id resolution, safe-path checks, input-stat and save-error wrapping, and the API-result classifier — so business domains can adopt typed errors without rebuilding common plumbing. Legacy helpers keep their current behavior and stay available, marked deprecated. A path-scoped lint rule rejects any reference to a legacy helper on migrated paths; shortcuts/drive/ is the first locked path, and each domain adds itself to the list when it migrates.

Scope: this PR covers the shared validation/file/API-result helper layer and the shared pre-checks. Shared business helpers (UploadDriveMediaAll/Multipart, ParseDriveMediaUploadResponse, FetchDriveMeta*, ResolveSavePath, EnsureScopes) keep their current error behavior and are not part of this change.

Changes

  • Shared pre-check failures (input flags, enum validation, dry-run support) return typed validation errors with the offending flag as paramshortcuts/common/runner.go.
  • Typed replacements preserving existing messages: ValidationErrorf, MutuallyExclusiveTyped/AtLeastOneTyped/ExactlyOneTyped, ValidatePageSizeTyped, ValidateChatIDTyped/ValidateUserIDTyped (flag name as a parameter so param reflects the caller's flag), ResolveOpenIDsTyped, ValidateSafePathTyped, RejectDangerousCharsTyped, WrapInputStatErrorTyped, WrapSaveErrorTypedshortcuts/common/.
  • Legacy helpers (including the API-result classifier HandleApiResult) carry deprecation notices pointing at their typed replacements; runtime behavior unchanged.
  • New errscontract rule no_legacy_common_helper_call: rejects any reference — direct calls and function-value references alike — to the 13 legacy helpers on migrated paths, with per-helper replacement suggestions; aliased and dot imports are covered — lint/errscontract/.
  • Replace the remaining legacy common ID-helper calls on the migrated drive path — shortcuts/drive/drive_search.go.
  • WrapSaveErrorTyped always emits the canonical internal wire type; call sites moving off WrapSaveErrorByCategory's custom categories (io, api_error) change their envelope type field when they migrate.

Test Plan

  • local full gate: gofmt -l ., go vet ./..., go build ./..., golangci-lint (--new-from-rev=origin/main, 0 issues), errscontract scan (go run -C lint . ..), unit tests (81 pkgs) + lint module tests, git diff --check, incremental deadcode clean
  • new unit coverage: every typed helper asserts *errs.ValidationError subtype + param (including flag-group params, safe-path symlink escape, save-error path/mkdir classification, me resolution); guard tests cover all 13 helpers plus aliased imports, dot imports, and function-value references; non-migrated paths pass
  • shared pre-check tests assert the typed param on stdin/file/enum/dry-run failures with messages unchanged
  • CI green on the current head, including live E2E

Related Issues

  • None

@coderabbitai

coderabbitai Bot commented Jun 3, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds typed validation/error helpers, migrates shortcut input/ID validators and IO wrappers to typed errors with params/causes, and enforces removal of legacy common.* helpers on migrated paths via a new AST lint rule and tests.

Changes

Typed Validation Error Enforcement and Migration

Layer / File(s) Summary
Lint rule enforcement
lint/errscontract/rule_no_legacy_common_helper_call.go, lint/errscontract/rules_test.go, lint/errscontract/scan.go
New AST lint CheckNoLegacyCommonHelperCall detects legacy common.* helper calls on migrated paths (handles aliased/dot imports and function-value references), reports REJECT violations with replacement suggestions, and is integrated into ScanRepo with tests for migrated/non-migrated/alias/dot-import cases.
Typed validation primitives
shortcuts/common/validate.go, shortcuts/common/common.go
Adds ValidationErrorf and typed validators (MutuallyExclusiveTyped, AtLeastOneTyped, ExactlyOneTyped, ValidatePageSizeTyped, ValidateSafePathTyped, RejectDangerousCharsTyped); adds deprecation docs for older APIs.
Chat/User ID normalization & open ID resolution
shortcuts/common/validate_ids.go, shortcuts/common/userids.go, shortcuts/common/userids_test.go
Centralizes normalizeChatID/normalizeUserID, adds ValidateChatIDTyped/ValidateUserIDTyped and ResolveOpenIDsTyped, marks legacy wrappers deprecated, and adds tests for me expansion and case-insensitive dedupe.
IO wrappers and runner input migration
shortcuts/common/runner.go, shortcuts/common/runner_input_test.go, shortcuts/common/runner_validation_test.go
Adds WrapInputStatErrorTyped and WrapSaveErrorTyped, deprecates untyped wrappers, and replaces many FlagErrorf calls with ValidationErrorf(...).WithParam(...)/.WithCause(...) in input/file/stdin/enum/dry-run validations; tests updated to assert validation params.
Drive search consumer update
shortcuts/drive/drive_search.go
validateDriveSearchIDs now calls typed ID validators for --creator-ids, --chat-ids, and --sharer-ids while preserving per-flag WithParam behavior.
Tests and helpers
shortcuts/common/validate_test.go, shortcuts/common/validate_ids.go
Adds assertValidationParam and numerous typed-validation tests for validators, IO wrappers, safe-path checks, and ResolveOpenIDsTyped; updates imports and assertions to verify typed error envelopes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • larksuite/cli#1205: Overlaps enforcement of legacy shortcuts/common helper migration (lint/forbid rules for legacy wrappers).
  • larksuite/cli#339: Related edits around WrapInputStatError/IO wrappers and migration to typed error forms.
  • larksuite/cli#648: Related work touching OpenID resolution and ResolveOpenIDs behavior.

Suggested labels

feature

Suggested reviewers

  • liangshuo-1
  • fangshuyu-768

Poem

🐰 A migration hops toward the light,
Typed errors tidy up the fight,
Lint keeps the old calls out of sight,
Validators sing parameters bright,
Tests cheer on the safer flight. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 49.28% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding typed validation errors to shared shortcut pre-checks in the common layer. It is concise, specific, and directly related to the primary focus of the changeset.
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.
Description check ✅ Passed The PR description comprehensively covers the motivation, scope, and changes with sufficient detail about the implementation and test verification.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 feat/errs-common-infra

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 and usage tips.

@github-actions github-actions Bot added domain/ccm PR touches the ccm domain size/L Large or sensitive change across domains or core paths labels Jun 3, 2026
@github-actions

github-actions Bot commented Jun 3, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#feat/errs-common-infra -y -g

@codecov

codecov Bot commented Jun 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.23288% with 42 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.27%. Comparing base (24ce3ec) to head (9268e4a).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/common/runner.go 62.22% 15 Missing and 2 partials ⚠️
shortcuts/common/validate.go 77.96% 9 Missing and 4 partials ⚠️
shortcuts/common/validate_ids.go 53.84% 12 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1242      +/-   ##
==========================================
+ Coverage   69.22%   69.27%   +0.04%     
==========================================
  Files         639      639              
  Lines       59798    59923     +125     
==========================================
+ Hits        41395    41510     +115     
  Misses      15058    15058              
- Partials     3345     3355      +10     

☔ View full report in Codecov by Sentry.
📢 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.

@evandance evandance force-pushed the feat/errs-common-infra branch from 82b85db to 22326f9 Compare June 3, 2026 07:57
@evandance evandance changed the title feat: add typed common error helpers feat(common): emit typed validation errors from shared shortcut pre-checks Jun 3, 2026
…hecks

Input pre-check failures shared by every shortcut — @file/stdin input
resolution, enum validation, and unsupported --dry-run — now leave the
CLI as typed validation envelopes naming the offending flag, so scripts
and AI agents can branch on `param` instead of parsing prose. Wire type,
exit code, and message text are unchanged; the new fields are additive.

The shared layer also gains typed replacements for its legacy
error-producing helpers, so each business domain can migrate to typed
errors without rebuilding common plumbing, and a path-scoped lint guard
keeps migrated domains from sliding back.

Changes:
- Shared pre-check failures (input flags, enum values, dry-run support)
  return typed validation errors carrying the offending flag as `param`.
- Every legacy error-producing helper in shortcuts/common has a typed
  replacement that preserves the existing message text: validation and
  flag-group checks, chat/user ID validation (callers name the flag so
  `param` is ground truth), "me" open-id resolution, safe-path checks,
  input-stat and save-error wrapping. Legacy helpers stay for
  not-yet-migrated domains, marked deprecated — including the legacy
  API-result classifier, whose typed route is runtime.CallAPITyped.
- A new errscontract rule rejects legacy common-helper calls on migrated
  paths, so a migrated domain cannot silently reintroduce legacy
  envelopes; drive is the first locked path and its last legacy
  ID-helper calls are replaced.
@evandance evandance force-pushed the feat/errs-common-infra branch from 22326f9 to 9268e4a Compare June 3, 2026 08:13
@evandance evandance merged commit b3fcf55 into main Jun 3, 2026
23 checks passed
@evandance evandance deleted the feat/errs-common-infra branch June 3, 2026 11:20
tuxedomm pushed a commit to zhumiaoxin/cli that referenced this pull request Jun 6, 2026
…hecks (larksuite#1242)

Input pre-check failures shared by every shortcut — @file/stdin input
resolution, enum validation, and unsupported --dry-run — now leave the
CLI as typed validation envelopes naming the offending flag, so scripts
and AI agents can branch on `param` instead of parsing prose. Wire type,
exit code, and message text are unchanged; the new fields are additive.

The shared layer also gains typed replacements for its legacy
error-producing helpers, so each business domain can migrate to typed
errors without rebuilding common plumbing, and a path-scoped lint guard
keeps migrated domains from sliding back.

Changes:
- Shared pre-check failures (input flags, enum values, dry-run support)
  return typed validation errors carrying the offending flag as `param`.
- Every legacy error-producing helper in shortcuts/common has a typed
  replacement that preserves the existing message text: validation and
  flag-group checks, chat/user ID validation (callers name the flag so
  `param` is ground truth), "me" open-id resolution, safe-path checks,
  input-stat and save-error wrapping. Legacy helpers stay for
  not-yet-migrated domains, marked deprecated — including the legacy
  API-result classifier, whose typed route is runtime.CallAPITyped.
- A new errscontract rule rejects legacy common-helper calls on migrated
  paths, so a migrated domain cannot silently reintroduce legacy
  envelopes; drive is the first locked path and its last legacy
  ID-helper calls are replaced.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/ccm PR touches the ccm 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.

2 participants