kasfictionlive / multi-file-code-to-ai

Generate a prompt to your clipboard of multiple select files from your codebase
Apache License 2.0
4 stars 0 forks source link

Feature Request: Include All Files in a Folder #1

Open netraular opened 3 weeks ago

netraular commented 3 weeks ago

I would like to propose a new feature that allows users to include all files within a specified folder. This functionality would be particularly useful for managing files in a more efficient manner. For instance, users could specify patterns such as:

This enhancement would simplify the process of including multiple files at once, reducing the need for individual file inclusions.

Thank you for considering this request.

codeautopilot[bot] commented 3 weeks ago

Potential solution

To address the feature request of including all files within a specified folder using patterns, we need to update the codebase to support glob patterns. This will allow users to specify patterns like home/*.php or home/* to include multiple files at once. The solution involves updating the README.md to document the new feature and modifying the src/extension.ts to implement the pattern matching logic.

How to implement

Update README.md

We need to update the README.md file to explain the new functionality. This will help users understand how to use the new feature effectively.

Updated README.md

# multi-file-code-to-ai README

Select multiple files and convert them to a prompt for chatGPT, claude, or deepseek.

## Features

- Manage multiple file lists.
- Swap between different file lists.
- Automatically update prompt with selected files.
- Save the prompts with the workspace in version control.
- **New:** Include all files in a specified folder using patterns.

## How to use

1. Open the prompt explorer.
2. Click on the `+` button to create a new prompt, type a name and instructions.
3. Use the file explorer to copy the relative paths of the files you want to include in the prompt.
4. Paste the paths into the prompt under the `Files` section.
5. Click on the generate button on the prompt in the prompt explorer to generate the prompt.

### Including All Files in a Folder

You can now include all files within a specified folder by using patterns. This feature simplifies the process of including multiple files at once.

#### Examples:

- To include all PHP files in the `home` directory:
  ```yaml
  files:
    - home/*.php

Example prompt

  name: New prompt
  instruction: Example instructions
  files:
    - src/app.ts
    - src/server.ts
    - src/views/index.ts
    - home/*.php  # Example of including all PHP files in the home directory
    - home/*      # Example of including all files in the home directory

Versions

1.1.0

1.0.2

1.0.0

Modify src/extension.ts

To implement the feature that allows users to include all files within a specified folder using patterns, we need to modify the src/extension.ts file.

Step-by-Step Plan

  1. Update the Prompt Interface:

    • Ensure the Prompt interface can handle patterns for file inclusion.
  2. Modify the addNewPrompt Function:

    • Allow users to specify patterns when adding a new prompt.
  3. Implement Pattern Matching Logic:

    • Use glob patterns to match files in the specified directories.
  4. Update the generatePrompt Function:

    • Resolve the patterns to actual file paths before generating the prompt.

Implementation

1. Update the Prompt Interface

Ensure the Prompt interface can handle patterns for file inclusion:

interface Prompt {
    name: string;
    instruction: string;
    files: string[];
    patterns?: string[];
}

2. Modify the addNewPrompt Function

Allow users to specify patterns when adding a new prompt:

async function addNewPrompt(provider: PromptsProvider) {
    const name = await vscode.window.showInputBox({ prompt: 'Enter a name for the new prompt' });
    if (!name) return;

    const instruction = await vscode.window.showInputBox({ prompt: 'Enter the instruction for the prompt' });
    if (!instruction) return;

    const patternsInput = await vscode.window.showInputBox({ prompt: 'Enter file patterns (comma-separated, e.g., "home/*.php, home/*")' });
    const patterns = patternsInput ? patternsInput.split(',').map(p => p.trim()) : [];

    const newPrompt: Prompt = { name, instruction, files: [], patterns };
    prompts.push(newPrompt);
    await savePrompt(newPrompt);
    provider.refresh();
    editPrompt(name, provider);
}

3. Implement Pattern Matching Logic

Use glob patterns to match files in the specified directories:

import * as glob from 'glob';

function resolvePatterns(patterns: string[], rootPath: string): string[] {
    let matchedFiles: string[] = [];
    for (const pattern of patterns) {
        const files = glob.sync(pattern, { cwd: rootPath });
        matchedFiles = matchedFiles.concat(files);
    }
    return matchedFiles;
}

4. Update the generatePrompt Function

Resolve the patterns to actual file paths before generating the prompt:

async function generatePrompt(item: PromptItem) {
    const prompt = prompts.find(p => p.name === item.label);
    if (!prompt) return;

    const workspaceRoot = vscode.workspace.workspaceFolders?.[0].uri.fsPath || '';
    let generatedPrompt = `# ${prompt.name}\n\n## Instructions\n\n${prompt.instruction}\n\n## Files\n\n`;

    const files = resolvePatterns(prompt.patterns || [], workspaceRoot);

    for (const file of files) {
        generatedPrompt += `### ${file}\n\n`;
        try {
            const absolutePath = path.join(workspaceRoot, file);
            const content = fs.readFileSync(absolutePath, 'utf8');
            generatedPrompt += `\`\`\`\n${content}\n\`\`\`\n\n`;
        } catch (err) {
            console.error(`Error reading file ${file}: ${err}`);
            generatedPrompt += `Error reading file: ${err}\n\n`;
        }
    }

    generatedPrompt += "---\n\nEnd of prompt";

    vscode.env.clipboard.writeText(generatedPrompt);
    vscode.window.showInformationMessage('Prompt generated and copied to clipboard!');
}

Summary

By following these steps, we have updated the src/extension.ts file to include the new feature that allows users to specify patterns for including multiple files from a folder. This enhancement simplifies the process of managing and including multiple files at once.

Click here to create a Pull Request with the proposed solution

Files used for this task:

Changes on README.md To address the feature request for including all files in a folder, we need to update the `README.md` file to explain the new functionality. This will help users understand how to use the new feature effectively. Below is a concrete proposal for updating the `README.md` file: ### Updated README.md ```markdown # multi-file-code-to-ai README Select multiple files and convert them to a prompt for chatGPT, claude, or deepseek. ## Features - Manage multiple file lists. - Swap between different file lists. - Automatically update prompt with selected files. - Save the prompts with the workspace in version control. - **New:** Include all files in a specified folder using patterns. ## How to use 1. Open the prompt explorer. 2. Click on the `+` button to create a new prompt, type a name and instructions. 3. Use the file explorer to copy the relative paths of the files you want to include in the prompt. 4. Paste the paths into the prompt under the `Files` section. 5. Click on the generate button on the prompt in the prompt explorer to generate the prompt. ### Including All Files in a Folder You can now include all files within a specified folder by using patterns. This feature simplifies the process of including multiple files at once. #### Examples: - To include all PHP files in the `home` directory: ```yaml files: - home/*.php ``` - To include all files in the `home` directory: ```yaml files: - home/* ``` ## Example prompt ```yaml name: New prompt instruction: Example instructions files: - src/app.ts - src/server.ts - src/views/index.ts - home/*.php # Example of including all PHP files in the home directory - home/* # Example of including all files in the home directory ``` ## Versions ### 1.1.0 - Added the feature to include all files in a specified folder using patterns. - Updated the README with instructions on how to use the new feature. ### 1.0.2 - Updated the README with instructions on how to use the extension. ### 1.0.0 - Initial release ``` ### Summary of Changes: 1. **Features Section**: Added a bullet point to highlight the new feature. 2. **How to Use Section**: Added a new subsection explaining how to include all files in a folder using patterns. 3. **Example Prompt**: Updated the example prompt to demonstrate the new feature. 4. **Versions Section**: Added a new version entry to document the addition of the new feature. This update will ensure that users are well-informed about the new functionality and how to use it effectively.
Changes on src/extension.ts To implement the feature that allows users to include all files within a specified folder using patterns like `home/*.php` or `home/*`, we need to modify the `src/extension.ts` file. Here’s a step-by-step plan to achieve this: ### Step-by-Step Plan 1. **Update the `Prompt` Interface**: - Ensure the `Prompt` interface can handle patterns for file inclusion. 2. **Modify the `addNewPrompt` Function**: - Allow users to specify patterns when adding a new prompt. 3. **Implement Pattern Matching Logic**: - Use glob patterns to match files in the specified directories. 4. **Update the `generatePrompt` Function**: - Resolve the patterns to actual file paths before generating the prompt. ### Implementation #### 1. Update the `Prompt` Interface Ensure the `Prompt` interface can handle patterns for file inclusion: ```typescript interface Prompt { name: string; instruction: string; files: string[]; patterns?: string[]; // Add patterns property } ``` #### 2. Modify the `addNewPrompt` Function Allow users to specify patterns when adding a new prompt: ```typescript async function addNewPrompt(provider: PromptsProvider) { const name = await vscode.window.showInputBox({ prompt: 'Enter a name for the new prompt' }); if (!name) return; const instruction = await vscode.window.showInputBox({ prompt: 'Enter the instruction for the prompt' }); if (!instruction) return; const patternsInput = await vscode.window.showInputBox({ prompt: 'Enter file patterns (comma-separated, e.g., "home/*.php, home/*")' }); const patterns = patternsInput ? patternsInput.split(',').map(p => p.trim()) : []; const newPrompt: Prompt = { name, instruction, files: [], patterns }; prompts.push(newPrompt); await savePrompt(newPrompt); provider.refresh(); editPrompt(name, provider); } ``` #### 3. Implement Pattern Matching Logic Use glob patterns to match files in the specified directories: ```typescript import * as glob from 'glob'; // Function to resolve patterns to file paths function resolvePatterns(patterns: string[], rootPath: string): string[] { let matchedFiles: string[] = []; for (const pattern of patterns) { const files = glob.sync(pattern, { cwd: rootPath }); matchedFiles = matchedFiles.concat(files); } return matchedFiles; } ``` #### 4. Update the `generatePrompt` Function Resolve the patterns to actual file paths before generating the prompt: ```typescript async function generatePrompt(item: PromptItem) { const prompt = prompts.find(p => p.name === item.label); if (!prompt) return; const workspaceRoot = vscode.workspace.workspaceFolders?.[0].uri.fsPath || ''; let generatedPrompt = `# ${prompt.name}\n\n## Instructions\n\n${prompt.instruction}\n\n## Files\n\n`; // Resolve patterns to file paths const files = resolvePatterns(prompt.patterns || [], workspaceRoot); for (const file of files) { generatedPrompt += `### ${file}\n\n`; try { const absolutePath = path.join(workspaceRoot, file); const content = fs.readFileSync(absolutePath, 'utf8'); generatedPrompt += `\`\`\`\n${content}\n\`\`\`\n\n`; } catch (err) { console.error(`Error reading file ${file}: ${err}`); generatedPrompt += `Error reading file: ${err}\n\n`; } } generatedPrompt += "---\n\nEnd of prompt"; vscode.env.clipboard.writeText(generatedPrompt); vscode.window.showInformationMessage('Prompt generated and copied to clipboard!'); } ``` ### Summary By following these steps, we have updated the `src/extension.ts` file to include the new feature that allows users to specify patterns for including multiple files from a folder. This enhancement simplifies the process of managing and including multiple files at once.