Skip to content

fix: centralize resource URL parsing#1812

Open
fangshuyu-768 wants to merge 1 commit into
mainfrom
fix/unify-resource-url-wiki-resolve
Open

fix: centralize resource URL parsing#1812
fangshuyu-768 wants to merge 1 commit into
mainfrom
fix/unify-resource-url-wiki-resolve

Conversation

@fangshuyu-768

@fangshuyu-768 fangshuyu-768 commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • route docs, drive comment, and drive permission URL parsing through common.ParseResourceURL instead of ad-hoc substring extraction
  • add a shared path-segment helper and cover query/fragment hijack regressions
  • preflight wiki node resolution scopes for docs media/resource, drive comments, and base URL resolve before calling wiki get_node

Tests

  • go test ./shortcuts/common ./shortcuts/doc ./shortcuts/drive ./shortcuts/base
  • go run -C lint . ..
  • go test ./shortcuts/... (fails only in shortcuts/apps TempDir cleanup: unlinkat .../.git: directory not empty; all other shortcut packages passed)

Summary by CodeRabbit

  • New Features

    • Added support for recognizing spreadsheet links in both /sheets/ and /spreadsheets/ formats.
    • Improved resource link handling for document, comment, and permission workflows.
  • Bug Fixes

    • Fixed URL parsing so query strings and fragments no longer change the detected document type or token.
    • Added stricter validation for unsupported resource types and permission target types.
    • Improved access handling by requesting required permissions only when needed for wiki-based actions.

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

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR centralizes resource URL parsing by adding a PathSegmentAfterPrefix helper used by ParseResourceURL and firstPathSegmentAfter, adds a /spreadsheets/ sheet alias, and introduces conditional wiki:node:retrieve scope enforcement across base, doc, and drive shortcuts. Document/comment/permission reference parsing now relies on common.ParseResourceURL with stricter type validation, replacing manual marker-based token extraction.

Changes

URL Parsing Refactor and Wiki Scope Enforcement

Layer / File(s) Summary
Shared resource URL parsing helper
shortcuts/common/resource_url.go, shortcuts/common/resource_url_test.go
Adds exported PathSegmentAfterPrefix, refactors ParseResourceURL to use it, adds /spreadsheets/ sheet alias, and adds tests covering the alias and non-hijacking cases.
Base wiki scope enforcement and token extraction
shortcuts/base/base_resolve.go
resolveWikiBaseURL now calls runtime.EnsureScopes for wiki:node:retrieve; firstPathSegmentAfter delegates to common.PathSegmentAfterPrefix.
Doc media insert and resource cover conditional scopes
shortcuts/doc/doc_media_insert.go, shortcuts/doc/doc_resource_cover.go
Adds ConditionalScopes for wiki:node:retrieve to DocMediaInsert, DocResourceDownload, DocResourceUpdate, DocResourceDelete, and enforces the scope before wiki node lookups.
Document reference parsing via ParseResourceURL
shortcuts/doc/helpers.go, shortcuts/doc/helpers_test.go
parseDocumentRef now uses common.ParseResourceURL with a type switch, removing extractDocumentToken; adds non-hijacking test cases.
Drive add-comment reference parsing and scope enforcement
shortcuts/drive/drive_add_comment.go, shortcuts/drive/drive_add_comment_test.go
Adds ConditionalScopes to DriveAddComment, rewrites parseCommentDocRef via common.ParseResourceURL with bitable→base mapping, adds runtime.EnsureScopes in resolveCommentTarget, removes extractURLToken and its test.
Drive apply-permission URL inference and type validation
shortcuts/drive/drive_apply_permission.go, shortcuts/drive/drive_apply_permission_test.go
Removes permApplyURLMarkers, rewrites resolvePermApplyTarget to use common.ParseResourceURL, adds isPermApplyType validation, and adds corresponding tests.

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

Possibly related PRs

  • larksuite/cli#360: Depends on parseDocumentRef/ParseResourceURL for target resolution, directly affected by this refactor.
  • larksuite/cli#588: Introduced resolvePermApplyTarget's original URL→type inference logic now rewritten in this PR.
  • larksuite/cli#1043: Modifies the same parseCommentDocRef/wiki resolution functions in drive_add_comment.go.

Suggested reviewers: SunPeiYang996, kongenpei

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 reflects the main change: centralizing resource URL parsing.
Description check ✅ Passed The description covers the summary and verification, with only minor template mismatches and a missing explicit Related Issues section.
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.
✨ 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/unify-resource-url-wiki-resolve

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.

@codecov

codecov Bot commented Jul 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.61538% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.43%. Comparing base (c04da47) to head (f437118).

Files with missing lines Patch % Lines
shortcuts/drive/drive_add_comment.go 63.63% 3 Missing and 1 partial ⚠️
shortcuts/base/base_resolve.go 50.00% 1 Missing and 1 partial ⚠️
shortcuts/doc/doc_media_insert.go 0.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1812      +/-   ##
==========================================
- Coverage   74.44%   74.43%   -0.01%     
==========================================
  Files         860      860              
  Lines       89855    89840      -15     
==========================================
- Hits        66891    66872      -19     
- Misses      17780    17783       +3     
- Partials     5184     5185       +1     

☔ 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.

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#fix/unify-resource-url-wiki-resolve -y -g

@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: 2

🤖 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/drive/drive_add_comment.go`:
- Around line 575-577: Add test coverage for the new wiki-scope pre-flight in
the wiki comment resolution flow. Update the add-comment tests around
resolve-comment-target/wiki-resolution to exercise the
`runtime.EnsureScopes([]string{"wiki:node:retrieve"})` branch and assert the
missing-scope failure path returns the expected error. Use the existing
`resolvedCommentTarget` and wiki-resolution helpers in `drive_add_comment.go` so
the test targets this exact check.

In `@shortcuts/drive/drive_apply_permission_test.go`:
- Around line 90-96: Update TestResolvePermApplyTarget_UnsupportedURLType to
assert the returned error as *errs.ValidationError from resolvePermApplyTarget,
then verify Subtype equals errs.SubtypeInvalidArgument and Param equals "--type"
instead of relying on strings.Contains; use the ValidationError fields directly
to validate the typed error behavior.
🪄 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: d1d58cdb-162b-42ba-b09a-0da33c5af5d5

📥 Commits

Reviewing files that changed from the base of the PR and between c04da47 and f437118.

📒 Files selected for processing (11)
  • shortcuts/base/base_resolve.go
  • shortcuts/common/resource_url.go
  • shortcuts/common/resource_url_test.go
  • shortcuts/doc/doc_media_insert.go
  • shortcuts/doc/doc_resource_cover.go
  • shortcuts/doc/helpers.go
  • shortcuts/doc/helpers_test.go
  • shortcuts/drive/drive_add_comment.go
  • shortcuts/drive/drive_add_comment_test.go
  • shortcuts/drive/drive_apply_permission.go
  • shortcuts/drive/drive_apply_permission_test.go

Comment on lines +575 to +577
if err := runtime.EnsureScopes([]string{"wiki:node:retrieve"}); err != nil {
return resolvedCommentTarget{}, err
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for existing test coverage of the wiki scope enforcement path.
rg -nP -C3 'EnsureScopes|wiki:node:retrieve' shortcuts/drive/

Repository: larksuite/cli

Length of output: 5639


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find tests related to drive_add_comment and scope enforcement.
rg -n --glob '*_test.go' 'drive_add_comment|EnsureScopes|wiki:node:retrieve|wiki resolution|Resolving wiki node' shortcuts/drive/

# Show test file names in the drive shortcut area.
git ls-files 'shortcuts/drive/*_test.go'

# Inspect the add-comment test file(s) if present.
for f in $(git ls-files 'shortcuts/drive/*_test.go' | rg 'add_comment|comment'); do
  echo "===== $f ====="
  wc -l "$f"
  sed -n '1,260p' "$f"
done

Repository: larksuite/cli

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Enumerate drive shortcut tests and inspect the relevant ones for comment/wiki coverage.
git ls-files 'shortcuts/drive/*_test.go'

# Search all drive tests for add-comment, wiki resolution, or scope-enforcement coverage.
rg -n -C 2 'drive_add_comment|Resolving wiki node|wiki:node:retrieve|EnsureScopes|missing_scope|conditional scope|ConditionalScopes' shortcuts/drive/*_test.go

# If there is a dedicated add-comment test file, show it.
for f in $(git ls-files 'shortcuts/drive/*_test.go' | rg 'add_comment|comment'); do
  echo "===== $f ====="
  wc -l "$f"
  sed -n '1,260p' "$f"
done

Repository: larksuite/cli

Length of output: 8479


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the wiki-related tests inside the add-comment test file.
rg -n -C 4 'wiki|EnsureScopes|missing_scope|scope|Resolve.*wiki|resolve.*wiki|comment target|resolvedCommentTarget' shortcuts/drive/drive_add_comment_test.go

# Show the surrounding sections for any wiki-related matches.
for n in $(rg -n 'wiki|EnsureScopes|missing_scope|scope' shortcuts/drive/drive_add_comment_test.go | cut -d: -f1 | head -n 20); do
  start=$((n-20))
  end=$((n+40))
  echo "===== lines ${start}-${end} ====="
  sed -n "${start},${end}p" shortcuts/drive/drive_add_comment_test.go
done

Repository: larksuite/cli

Length of output: 50369


Add a test for the wiki-scope pre-flight. The new runtime.EnsureScopes([]string{"wiki:node:retrieve"}) check in the wiki-resolution path still needs coverage for the missing-scope failure; the current add-comment tests cover URL parsing and successful wiki resolution, but not this branch.

🤖 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/drive/drive_add_comment.go` around lines 575 - 577, Add test
coverage for the new wiki-scope pre-flight in the wiki comment resolution flow.
Update the add-comment tests around resolve-comment-target/wiki-resolution to
exercise the `runtime.EnsureScopes([]string{"wiki:node:retrieve"})` branch and
assert the missing-scope failure path returns the expected error. Use the
existing `resolvedCommentTarget` and wiki-resolution helpers in
`drive_add_comment.go` so the test targets this exact check.

Source: Coding guidelines

Comment on lines +90 to +96
func TestResolvePermApplyTarget_UnsupportedURLType(t *testing.T) {
t.Parallel()
_, _, err := resolvePermApplyTarget("https://example.feishu.cn/drive/folder/fldTok123", "")
if err == nil || !strings.Contains(err.Error(), "unsupported --type") {
t.Fatalf("expected unsupported type error, got: %v", err)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
ast-grep outline --items all --type struct --match 'ValidationError' $(fd -t f -e go . | rg -l 'ValidationError' | head -20) 2>/dev/null
rg -nP 'type ValidationError struct' -A 12 $(fd -e go)

Repository: larksuite/cli

Length of output: 992


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the test target and the error construction path.
rg -n "resolvePermApplyTarget|unsupported --type|SubtypeInvalidArgument|ValidationError|NewValidationError|WithParam|Param:" shortcuts/drive errs -S

# Show the relevant implementation snippets with line numbers.
for f in shortcuts/drive/drive_apply_permission.go shortcuts/drive/drive_apply_permission_test.go errs/types.go errs/*.go; do
  [ -f "$f" ] && { echo "===== $f ====="; sed -n '1,260p' "$f" | cat -n; }
done

Repository: larksuite/cli

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,120p' shortcuts/drive/drive_apply_permission.go | cat -n
printf '\n===== test =====\n'
sed -n '1,140p' shortcuts/drive/drive_apply_permission_test.go | cat -n
printf '\n===== validation error =====\n'
sed -n '1,100p' errs/types.go | cat -n

Repository: larksuite/cli

Length of output: 16127


Assert the typed validation error here
Match *errs.ValidationError and check Subtype == errs.SubtypeInvalidArgument plus Param == "--type" instead of strings.Contains(...); ValidationError exposes Param directly.

🤖 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/drive/drive_apply_permission_test.go` around lines 90 - 96, Update
TestResolvePermApplyTarget_UnsupportedURLType to assert the returned error as
*errs.ValidationError from resolvePermApplyTarget, then verify Subtype equals
errs.SubtypeInvalidArgument and Param equals "--type" instead of relying on
strings.Contains; use the ValidationError fields directly to validate the typed
error behavior.

Sources: Path instructions, Learnings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

1 participant