Repository: farouqaldori/aiformat Branch: main Commit: a11bdb6f53c6 Files: 9 Total size: 18.3 KB Directory structure: gitextract_0fe2y8sq/ ├── .editorconfig ├── .gitignore ├── LICENSE ├── package.json ├── readme.md ├── source/ │ ├── app.tsx │ ├── cli.tsx │ └── utils/ │ └── generateOutput.ts └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yml] indent_style = space indent_size = 2 ================================================ FILE: .gitignore ================================================ .DS_Store node_modules dist ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2024 farouqaldori Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: package.json ================================================ { "name": "aiformat", "version": "0.0.5", "license": "MIT", "bin": "dist/cli.js", "type": "module", "engines": { "node": ">=16" }, "repository": { "type": "git", "url": "https://github.com/farouqaldori/aiformat.git" }, "scripts": { "build": "tsc", "dev": "tsc --watch", "test": "prettier --check . && xo && ava" }, "files": [ "dist" ], "dependencies": { "clipboardy": "^4.0.0", "figures": "^6.1.0", "ink": "^4.1.0", "meow": "^11.0.0", "react": "^18.2.0" }, "devDependencies": { "@sindresorhus/tsconfig": "^3.0.1", "@types/react": "^18.0.32", "@vdemedes/prettier-config": "^2.0.1", "ava": "^5.2.0", "chalk": "^5.2.0", "eslint-config-xo-react": "^0.27.0", "eslint-plugin-react": "^7.32.2", "eslint-plugin-react-hooks": "^4.6.0", "ink-testing-library": "^3.0.0", "prettier": "^2.8.7", "ts-node": "^10.9.1", "typescript": "^5.0.3", "xo": "^0.53.1" }, "ava": { "extensions": { "ts": "module", "tsx": "module" }, "nodeArguments": [ "--loader=ts-node/esm" ] }, "xo": { "extends": "xo-react", "prettier": true, "rules": { "react/prop-types": "off" } }, "prettier": "@vdemedes/prettier-config" } ================================================ FILE: readme.md ================================================ # aiformat https://github.com/farouqaldori/aiformat/assets/16778033/2dd13fc7-5859-4169-893a-4bfe99bd8f0a aiformat is a simple tool you can use from the command line. It helps you select files and folders and change them into a format that AI assistants like Claude can understand. This way, you can share code snippets and project structures faster and easier directly from the console, without having to copy and paste them manually. This cli tool is built using [Ink](https://github.com/vadimdemedes/ink). ## Updates ### **Mar 18 2024:** Folder navigation support * Added searching inside deeply nested files. * Added the ability to expand/collapse folders with the `Tab` key. * Added emojis to differentiate between folders (🗂️) and files (📄). * Full code re-write, including ID based navigation. ## Features - Interactively select files and folders from the current directory - Filter files and folders using a search query - Navigate through the list using arrow keys - Select/deselect items using left/right arrow keys - Convert selected files and folders into a format compatible with Claude - Automatically copy the formatted output to the clipboard ## Install To install aiformat, make sure you have Node.js installed on your system. Then, run the following command: ```bash $ npm install --global aiformat ``` ## Usage To use aiformat, navigate to the directory containing the files and folders you want to share with Claude. Then, run the following command: ```bash aiformat ``` The CLI will display a list of files and folders in the current directory. You can navigate through the list using the up and down arrow keys. To select or deselect an item, use the left or right arrow keys. You can also filter the list by typing a search query. The list will update in real-time as you type. Once you have selected the desired files and folders, press Enter. The CLI will format the selected items into a structure that Claude can understand and automatically copy the output to your clipboard. ## Example ```bash $ cd /path/to/your/project $ aiformat ``` ![aiformat example](https://i.imgur.com/Vx1EYLn.png) Navigate through the list, select the desired files and folders, and press Enter. The formatted output will be copied to your clipboard, ready to be pasted into your conversation with your AI assistant. The output is optimized for usage with Claude, by wrapping files with XML tags. Example prompt: ``` { "name": "aiformat", "version": "0.0.1", "license": "MIT", ... } import React, { FC, useState, useEffect } from 'react'; const App: FC = () => { return ( ... ); }; export default App; #!/usr/bin/env node import React from 'react'; import App from './app.js'; render(); // Add this part manually Modify the files above and update the version from 0.0.1 to 0.0.2 ``` ## Local Development To start developing aiformat locally, follow these steps: 1. Clone the repository: ```bash git clone https://github.com/farouqaldori/aiformat.git ``` 2. Change to the project directory: ```bash cd aiformat ``` 3. Install the dependencies: ```bash npm install ``` 4. Build the project: ```bash npm run build ``` 5. Link the package globally: ```bash npm link ``` 6. Now you can use the `aiformat` command globally to test your local changes. ## Contributing If you find any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request on the [GitHub repository](https://github.com/farouqaldori/aiformat). ## License This project is licensed under the [MIT License](LICENSE). ================================================ FILE: source/app.tsx ================================================ import React, { FC, ReactNode, useEffect, useState } from 'react'; import { Box, Text, useInput } from 'ink'; import fs from 'fs'; import path from 'path'; import { outputXml } from './utils/generateOutput.js'; import clipboard from 'clipboardy'; interface Item { id: string; name: string; isDirectory: boolean; children: Item[]; path: string; isExpanded: boolean; level: number; } const generateId = (itemPath: string): string => { return itemPath; }; // Clear console process.stdout.write('\x1Bc'); const App: FC = () => { const [excludedFolders] = useState(['node_modules', '.git', 'dist', 'build', 'coverage', 'public']); const [currentItemId, setCurrentItemId] = useState(null); const [items, setItems] = useState([]); const [selectedItems, setSelectedItems] = useState([]); const [searchQuery, setSearchQuery] = useState(''); const [message, setMessage] = useState(null) useInput((input, key) => { if (key.return) { copyContentsOfFilesAndFolders(); return; } if (input) { setSearchQuery((prev) => prev + input); } if (key.backspace || key.delete) { setSearchQuery((prev) => prev.slice(0, -1)); } if (key.downArrow) { navigateToNextItem(); } if (key.upArrow) { navigateToPreviousItem(); } if (key.tab) { toggleFolderExpansion(); } if (key.leftArrow || key.rightArrow) { toggleSelection(); } }); const copyContentsOfFilesAndFolders = () => { const files = outputXml(selectedItems); clipboard.writeSync(files.content); setMessage( ✨ Successfully copied {files.fileCount} file{files.fileCount > 1 && "s"} to clipboard ); setTimeout(() => { process.exit(0); }, 300); }; const toggleSelection = () => { if (!currentItemId) { return; } const currentItem = findItemById(currentItemId, items); if (!currentItem) { return; } if (currentItem.isDirectory) { const itemsInFolder = getItemsFromFolder(currentItem); const allItemsInFolderAreSelected = itemsInFolder.every((item) => selectedItems.includes(item)); if (allItemsInFolderAreSelected) { setSelectedItems(selectedItems.filter((item) => !itemsInFolder.find((i) => i.id === item.id))); } else { const newSelectedItems = selectedItems.filter((item) => !itemsInFolder.find((i) => i.id === item.id)); setSelectedItems([...newSelectedItems, ...itemsInFolder]); } } else { if (selectedItems.find((item) => item.id === currentItem.id)) { setSelectedItems(selectedItems.filter((item) => item.id !== currentItem.id)); } else { setSelectedItems([...selectedItems, currentItem]); } } } const getItemsFromFolder = (folder: Item): Item[] => { const items: Item[] = []; const traverseItems = (item: Item) => { items.push(item); if (item.isDirectory) { item.children.forEach(traverseItems); } }; traverseItems(folder); return items; } const loadFilesAndFolders = (dirPath: string, level: number = 0): Item[] => { const items: Item[] = []; const dirItems = fs.readdirSync(dirPath); const sortedItems = dirItems.sort((a, b) => { const aIsDir = fs.statSync(path.join(dirPath, a)).isDirectory(); const bIsDir = fs.statSync(path.join(dirPath, b)).isDirectory(); if (aIsDir && !bIsDir) return -1; if (!aIsDir && bIsDir) return 1; return a.localeCompare(b); }); for (const item of sortedItems) { const itemPath = path.join(dirPath, item); const isDirectory = fs.statSync(itemPath).isDirectory(); const id = generateId(itemPath); if (!excludedFolders.includes(item)) { const newItem: Item = { id, name: item, isDirectory, children: [], path: itemPath, isExpanded: false, level, }; if (isDirectory) { newItem.children = loadFilesAndFolders(itemPath, level + 1); } items.push(newItem); } } return items; }; useEffect(() => { const items = loadFilesAndFolders(process.cwd()); setItems(items); setCurrentItemId(items[0]?.id || null); }, []); const findItemByIdInFilteredItems = (itemId: string, items: Item[]): Item | undefined => { for (const item of items) { if (item.id === itemId) { return item; } if (item.isDirectory && item.isExpanded) { const foundItem = findItemByIdInFilteredItems(itemId, item.children); if (foundItem) { return foundItem; } } } return undefined; }; const findItemById = (itemId: string, items: Item[]): Item | undefined => { for (const item of items) { if (item.id === itemId) { return item; } if (item.isDirectory) { const foundItem = findItemById(itemId, item.children); if (foundItem) { return foundItem; } } } return undefined; }; const navigateToNextItem = () => { if (!currentItemId) { setCurrentItemId(expandedItems[0]?.id || null); return; } const currentItem = findItemByIdInFilteredItems(currentItemId, expandedItems); if (!currentItem) { return; } if (currentItem.isDirectory && currentItem.isExpanded && currentItem.children.length > 0) { setCurrentItemId(currentItem.children[0]?.id || null); } else { const flattenedItems = flattenItems(expandedItems); const currentIndex = flattenedItems.findIndex((item) => item.id === currentItemId); const nextIndex = (currentIndex + 1) % flattenedItems.length; setCurrentItemId(flattenedItems[nextIndex]?.id || null); } }; const navigateToPreviousItem = () => { if (!currentItemId) { return; } const flattenedItems = flattenItems(expandedItems); const currentIndex = flattenedItems.findIndex((item) => item.id === currentItemId); const previousIndex = (currentIndex - 1 + flattenedItems.length) % flattenedItems.length; setCurrentItemId(flattenedItems[previousIndex]?.id || null); }; const flattenItems = (items: Item[]): Item[] => { const flattenedItems: Item[] = []; const traverseItems = (items: Item[]) => { for (const item of items) { flattenedItems.push(item); if (item.isDirectory && item.isExpanded) { traverseItems(item.children); } } }; traverseItems(items); return flattenedItems; }; const toggleFolderExpansion = () => { if (!currentItemId) { return; } const currentItem = findItemById(currentItemId, items); if (currentItem && currentItem.isDirectory) { currentItem.isExpanded = !currentItem.isExpanded; } setItems(items.map((item) => { if (item.id === currentItem?.id) { return currentItem; } return item; })); }; const expandParentFolders = (item: Item, items: Item[]): Item[] => { return items.map((i) => { if (i.id === item.id) { return { ...i, isExpanded: true }; } if (i.isDirectory && item.path.startsWith(i.path)) { return { ...i, isExpanded: true, children: expandParentFolders(item, i.children) }; } return i; }); }; const searchItems = (items: Item[], query: string): Item[] => { return items.reduce((result, item) => { if (item.isDirectory) { const matchingChildren = searchItems(item.children, query); if (matchingChildren.length > 0) { const expandedItem = { ...item, isExpanded: true, children: matchingChildren }; result.push(expandedItem); } } else if (item.name.toLowerCase().includes(query.toLowerCase())) { result.push(item); } return result; }, [] as Item[]); }; const renderItems = (items: Item[], indentationLevel = 0): ReactNode[] => { return items.map((item) => ( selectedItem.id === item.id) ? 'cyan' : 'white'}> {selectedItems.find((selectedItem) => selectedItem.id === item.id) ? '[X]' : '[ ]'}{' '} {item.isDirectory ? '🗂️ ' : '📄 '} {item.name}{item.isDirectory && "/"} {item.isDirectory && item.isExpanded && item.children.length > 0 && renderItems(item.children, indentationLevel + 1)} )); }; const filteredItems = searchQuery ? searchItems(items, searchQuery) : items; const expandedItems = filteredItems.reduce((result, item) => { if (item.isDirectory && item.isExpanded) { return expandParentFolders(item, result); } return result; }, filteredItems); useEffect(() => { // Get the first file that is not a directory const firstFile = expandedItems[0]; if (firstFile && firstFile.isDirectory) { const itemsInFolder = getItemsFromFolder(firstFile); const firstItem = itemsInFolder.find((item) => !item.isDirectory); if (searchQuery === "") { setCurrentItemId(firstFile.id); } else { setCurrentItemId(firstItem?.id || null); } } else { if (firstFile) { setCurrentItemId(firstFile.id); } } }, [searchQuery]); return ( Select files and folders to include. Selected files: {selectedItems.length} Search query: {searchQuery ? searchQuery : None} {renderItems(expandedItems)} {expandedItems.length === 0 && No items found} Use Up / Down to navigate, and Left /{' '} Right to select Use Tab to expand/collapse, and{' '} Enter to copy selected files. {message && message} ); }; export default App; ================================================ FILE: source/cli.tsx ================================================ #!/usr/bin/env node import React from 'react'; import { render } from 'ink'; import App from './app.js'; // import meow from 'meow'; // This code is commented out in case we want to use it later to pass arguments to the CLI // const cli = meow( // ` // Usage // $ aiformat // Options // --name Your name // Examples // $ aiformat --name=Jane // Hello, Jane // `, // { // importMeta: import.meta, // flags: { // name: { // type: 'string', // }, // }, // }, // ); render(); ================================================ FILE: source/utils/generateOutput.ts ================================================ import fs from 'fs'; interface FileOrFolder { id: string; name: string; isDirectory: boolean; children: FileOrFolder[]; path: string; isExpanded: boolean; level: number; } const cleanupFileTree = (fileTree: FileOrFolder[]): FileOrFolder[] => { const idSet = new Set(); function traverse(node: FileOrFolder) { if (idSet.has(node.id)) { return null; } idSet.add(node.id); if (node.isDirectory) { node.children = node.children.map(traverse).filter(Boolean) as FileOrFolder[]; } return node; } return fileTree.map(traverse).filter(Boolean) as FileOrFolder[]; }; export const outputXml = (fileTree: FileOrFolder[]): { content: string; fileCount: number; } => { const cleanedFileTree = cleanupFileTree(fileTree); function generateXml(node: FileOrFolder, parentPath: string = ''): string { const currentPath = parentPath ? `${parentPath}/${node.name}` : node.name; if (node.isDirectory) { const childXml = node.children.map(child => generateXml(child, currentPath)).join('\n'); return `\n${childXml}\n`; } else { const fileContent = fs.readFileSync(node.path, 'utf8'); return `\n${fileContent}\n`; } } function countFiles(node: FileOrFolder): number { if (node.isDirectory) { return node.children.reduce((acc, child) => acc + countFiles(child), 0); } else { return 1; } } return { content: cleanedFileTree.map(node => generateXml(node)).join('\n\n'), fileCount: cleanedFileTree.reduce((acc, node) => acc + countFiles(node), 0), }; }; ================================================ FILE: tsconfig.json ================================================ { "extends": "@sindresorhus/tsconfig", "compilerOptions": { "outDir": "dist" }, "include": ["source"] }