Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 一時ファイルに選択したテキストを保存 #38

Merged
merged 3 commits into from
Dec 30, 2024

Conversation

nekowasabi
Copy link
Owner

@nekowasabi nekowasabi commented Dec 30, 2024

  • partial context to temp file.
  • /readonly tempfile

Summary by CodeRabbit

  • New Features

    • Added a new command addPartialReadonlyContext to the Aider plugin.
    • Introduced functionality to save selected text as a read-only context.
    • New command :AiderAddPartialReadonlyContext for users to add selected text in visual mode.
  • Improvements

    • Enhanced text selection and context management capabilities with specific line ranges.

Copy link
Contributor

coderabbitai bot commented Dec 30, 2024

Walkthrough

The pull request introduces new functionality to the Aider plugin for saving selected text from a buffer to a temporary file. A new function getPartialContextFilePath is added to bufferOperation.ts, allowing the extraction of a specific line range from the current file and creating a temporary file with that context. In main.ts, a corresponding command addPartialReadonlyContext is implemented, enabling users to add partial read-only context based on selected line numbers. Additionally, the README is updated to document the new command.

Changes

File Changes
denops/aider/bufferOperation.ts - Added getPartialContextFilePath function
- Updated import to include getCurrentFilePath
denops/aider/main.ts - Added addPartialReadonlyContext command
- Supports variable argument count and range selection
README.md - Added documentation for :AiderAddPartialReadonlyContext command

Sequence Diagram

sequenceDiagram
    participant User
    participant Vim
    participant Plugin
    participant TempFile
    
    User->>Vim: Select line range
    User->>Vim: Trigger addPartialReadonlyContext
    Vim->>Plugin: Call with start/end lines
    Plugin->>Plugin: Get current file path
    Plugin->>TempFile: Create temp file with context
    Plugin->>Vim: Return temp file path
Loading

Poem

🐰 A rabbit's tale of code so neat,
Lines selected, context complete!
Temp files dancing, swift and light,
Aider's magic takes its flight 🚀
Partial contexts, now in sight! 📄


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b0445e6 and b8f9d4f.

📒 Files selected for processing (2)
  • denops/aider/bufferOperation.ts (2 hunks)
  • denops/aider/main.ts (1 hunks)
🔇 Additional comments (2)
denops/aider/main.ts (1)

247-257: Ensure argument validation and consider user inputs carefully.

The new addPartialReadonlyContext command accepts two string parameters, start and end, which control line ranges in a buffer. Since these values are derived from user inputs or Vim's range, please confirm they are properly validated or sanitized to prevent potential off-by-one errors or malicious injection attempts. In addition, handle potential edge cases (like negative or zero-length ranges) to ensure robust behavior in all scenarios.

Would you like a script to scan the codebase for all usage sites or references to addPartialReadonlyContext to confirm no unhandled edge cases?

denops/aider/bufferOperation.ts (1)

8-8: Dependency import looks good.

Importing getCurrentFilePath ensures that the current file path can be retrieved for constructing the annotation. This addition appears consistent with the new logic. Just be mindful to handle exceptions if getCurrentFilePath fails or returns an unexpected result.

Comment on lines +433 to +461

/**
* 選択したテキストを一時ファイルに保存し、ファイルのパスを返します。
*
* @param {Denops} denops - Denopsインスタンス
* @param {string} start - 選択範囲の開始行
* @param {string} end - 選択範囲の終了行
* @retuns {Promise<string>} 一時ファイルのパス
*/
export async function getPartialContextFilePath(denops: Denops, start: string, end: string): Promise<string> {
const context = ensure(await denops.call("getline", start, end), is.ArrayOf(is.String));
const filePath = ensure(await getCurrentFilePath(denops), is.String);

const annotation = ensure([`// Path: ${filePath}`], is.ArrayOf(is.String));

annotation.push(`// Line: ${start}-${end}`);

context.unshift(...annotation);

// 一時ファイルに選択範囲を書き込む
const tempFile = ensure(await denops.call("tempname"), is.String);
await Deno.writeTextFile(tempFile, context.join("\n"));

// set filetype
const fileType = ensure(await fn.getbufvar(denops, "%", "&filetype"), is.String);
await denops.cmd(`setlocal filetype=${fileType}`);

return tempFile;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against potential file I/O issues and correct the documented tag.

  1. The function correctly writes the selected text and annotation to a temporary file, enabling partial read-only context. Consider:

    • Adding try/catch blocks around file I/O to handle unexpected disk failures or permission issues.
    • Verifying the line range is valid (e.g., non-empty result from getline).
  2. The JSDoc tag currently says @retuns. Consider updating it to @returns for clarity and consistency.

Here’s a proposed diff to address the JSDoc tag:

- * @retuns {Promise<string>} 一時ファイルのパス
+ * @returns {Promise<string>} 一時ファイルのパス

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
README.md (2)

135-135: Documentation added for the new command.

The new command :AiderAddPartialReadonlyContext is properly documented in the Usage section.

Consider enhancing the documentation with:

  1. A more detailed description explaining that the selected text is saved to a temporary file
  2. An example key mapping in both the vimscript and lua configuration sections
  3. A usage example showing how to use the command in visual mode

Here's a suggested expansion of the documentation:

-  - `:AiderAddPartialReadonlyContext` - Adds the selected text in visual mode as read-only context to Aider.
+  - `:AiderAddPartialReadonlyContext` - Adds the selected text in visual mode as read-only context to Aider by saving it to a temporary file. This is useful when you want to provide specific parts of a file as context without including the entire file.

And add these key mappings to the configuration sections:

" In vimscript section
" Add selected text as read-only context
vmap <leader>ac :AiderAddPartialReadonlyContext<CR>
-- In lua section
vim.api.nvim_set_keymap('v', '<leader>ac', ':AiderAddPartialReadonlyContext<CR>', { noremap = true, silent = true })

134-136: Consider reordering commands for better organization.

The new command :AiderAddPartialReadonlyContext is related to visual mode operations. Consider moving it next to the existing visual mode command :AiderVisualTextWithPrompt to maintain logical grouping of commands.

Suggested order:

  - `:AiderVisualTextWithPrompt` - Edit the selected text in visual mode in a floating window and send it to aider. In the floating window, send to aider with `<CR>` in normal mode, and close the floating window with `Q`. You can also backup prompt with `q`.
  - `:AiderAddPartialReadonlyContext` - Adds the selected text in visual mode as read-only context to Aider.
- `:AiderAddWeb` - Displays a prompt for the specified URL and adds it to the aider context.
🧰 Tools
🪛 LanguageTool

[grammar] ~134-~134: The word “backup” is a noun. The verb is spelled with a space.
Context: ... floating window with Q. You can also backup prompt with q. - `:AiderAddPartialRea...

(NOUN_VERB_CONFUSION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b8f9d4f and af86041.

📒 Files selected for processing (1)
  • README.md (1 hunks)

@nekowasabi nekowasabi merged commit 5187f60 into main Dec 30, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant