File Operations Commands

VritraAI provides powerful file operation commands with enhanced features like syntax highlighting, AI-powered editing, and rich formatting. This section covers all file-related commands for managing, viewing, editing, and comparing files and directories.

💡 Path Expansion: All file and directory commands in VritraAI automatically expand ~ to your home directory and environment variables ($VAR or ${VAR}) to their values. For example, ls ~/Documents and read_file $HOME/config.json work seamlessly.

Directory Listing

ls [options] [path]

Rich colored directory listing with enhanced formatting and file type detection. Provides a native-style implementation with colorful output and icons for better visual identification of files and directories.

Features:

  • Color-coded file types (directories, executables, archives, images, videos, audio, code files, documents, config files)
  • Automatic file type detection based on extensions
  • Icon indicators for different file categories
  • Long format listing with file permissions, size, and modification date
  • Hidden file support
  • Supports both relative and absolute paths
  • Automatic path expansion for ~ (home directory) and environment variables

Parameters:

  • options - (Optional) Command options
  • path - (Optional) Directory path to list. Defaults to current directory (.). Supports path expansion for ~ (home directory) and environment variables ($VAR or ${VAR})

Options:

  • -l - Long format listing (permissions, size, date)
  • -a - Show all files including hidden files (starting with .)
  • -la - Combined long format with all files

File Type Colors:

  • Directories: Bold blue
  • Executables: Bold green
  • Archives: Bold red
  • Images/Videos: Bold magenta
  • Audio: Bold cyan
  • Code files: Yellow/cyan (varies by language)
  • Documents: White/gray
  • Config files: Bold yellow

Examples:

# List current directory
ls

# Long format listing
ls -l

# Show all files including hidden
ls -a

# Combined long format with all files
ls -la

# List specific directory
ls /home/user/Documents

# List home directory (path expansion)
ls ~
ls ~/Documents

# List using environment variables
ls $HOME/projects
ls ${HOME}/Documents

# List with long format
ls -l src/

# List parent directory
ls ..

dir [options] [path]

Alias for ls command. Provides the same functionality with Windows-style naming for users familiar with Windows command prompt.

Note: This command is functionally identical to ls and accepts all the same options and parameters.

File Reading & Display

read_file <filename>

Read and display file contents with automatic syntax highlighting. Intelligently detects file type based on extension and applies appropriate syntax highlighting for better code readability. Uses Pygments library for professional code highlighting with the Monokai theme.

Features:

  • Automatic language detection from file extension
  • Syntax highlighting for 20+ programming languages
  • Clean, border-free output optimized for terminal viewing
  • UTF-8 encoding with fallback to Latin-1 for compatibility
  • Error recovery for file access issues
  • Supports both relative and absolute paths

Parameters:

  • filename - Path to the file to read (required)

Supported Languages:

Python, JavaScript, TypeScript, Java, C/C++, Go, Rust, PHP, Ruby, Swift, Kotlin, HTML, CSS, JSON, YAML, XML, Markdown, Shell scripts, and more. Falls back to plain text for unknown file types.

Examples:

# Read a Python file
read_file myfile.py

# Read a configuration file
read_file config.json

# Read a markdown file
read_file README.md

# Read with absolute path
read_file /home/user/project/app.py

# Read from parent directory
read_file ../config/settings.json

Note: If Pygments is not installed, the file will be displayed as plain text without syntax highlighting.

File Creation & Editing

create_file <filename> [prompt]

Generate files using AI with automatic content generation. If a prompt is provided, AI will generate the file content based on your description. The AI understands file extensions and generates appropriate code for the file type. Automatically cleans up AI responses to extract only the code content.

Features:

  • AI-powered file generation from natural language descriptions
  • Automatic code extraction from AI responses (removes markdown blocks, explanations)
  • File type awareness (generates appropriate code based on extension)
  • UTF-8 encoding for proper character support
  • Error handling for file creation failures
  • Requires AI to be enabled (API key configured)

Parameters:

  • filename - Name/path of the file to create (required)
  • prompt - (Optional) Natural language description of what the file should contain

How It Works:

  1. Analyzes the filename to determine file type
  2. Sends the prompt and filename to AI for content generation
  3. Extracts code from AI response (removes markdown, explanations, prefixes)
  4. Writes the cleaned content to the file
  5. Reports success or error

Examples:

# Create an empty file (requires prompt)
create_file new_script.py "a simple Python script"

# Create a Flask application
create_file app.py "a Flask web application with user authentication"

# Create utility functions
create_file utils.py "helper functions for file operations"

# Create a configuration file
create_file config.json "JSON configuration with database settings"

# Create a React component
create_file Button.jsx "a reusable button component with props"

Requirement: This command requires AI to be enabled. Make sure you have configured an API key using apikey command.

edit_file <filename> <instruction>

AI-powered file editing with advanced diff preview. Provide a natural language instruction and AI will modify the file accordingly. Shows a comprehensive diff preview with statistics before applying changes, allowing you to review and confirm modifications.

Features:

  • Natural language editing instructions
  • Advanced diff preview with statistics (additions, deletions, modifications)
  • File type awareness for context-aware editing
  • Change impact assessment (Low/Medium/High)
  • Syntax-highlighted diff output
  • Preview of final result (first 20 lines)
  • Confirmation prompt before applying changes
  • Automatic file creation if file doesn't exist
  • Error recovery for file access issues
  • Requires AI to be enabled (API key configured)

Parameters:

  • filename - Path to the file to edit (required)
  • instruction - Natural language description of changes to make (required)

Diff Preview Includes:

  • File information (path, language, modification timestamp)
  • Change statistics (additions, deletions, modifications, total lines, file size)
  • Impact level assessment
  • Unified diff with syntax highlighting
  • Preview of the final result

Examples:

# Add error handling
edit_file myfile.py "add error handling to the main function"

# Add configuration setting
edit_file config.json "add a new setting for debug mode"

# Refactor code
edit_file app.py "refactor the database connection to use connection pooling"

# Fix bug
edit_file utils.py "fix the null pointer exception in the parse function"

# Add feature
edit_file api.py "add a new endpoint for user profile updates"

# Update API endpoint
edit_file client.js "change the API endpoint from /api/v1 to /api/v2"

Tip: Be specific in your instructions. Instead of "fix it", say "fix the null pointer exception in the parse function". The AI understands context better with detailed instructions.

Requirement: This command requires AI to be enabled. Make sure you have configured an API key using apikey command.

Directory Operations

create_dir <dirname>

Create directories with automatic parent directory creation. Creates the specified directory and any necessary parent directories in the path. Safe to use even if the directory already exists (won't raise an error).

Features:

  • Creates nested directory structures automatically
  • Safe operation (doesn't fail if directory exists)
  • Supports relative and absolute paths
  • Home directory expansion (~)
  • Clear success/error messages

Parameters:

  • dirname - Directory name or path to create (required)

Examples:

# Create a single directory
create_dir myproject

# Create nested directories
create_dir src/components

# Create with absolute path
create_dir /home/user/projects/newapp

# Create in home directory
create_dir ~/Documents/new_folder

# Create multiple levels
create_dir project/src/utils/helpers

mkdir <dirname>

Alias for create_dir. Provides the same functionality for users familiar with Unix/Linux command-line conventions.

Note: This command is functionally identical to create_dir and accepts the same parameters.

tree [path] [max_depth]

Display directory tree structure in a visual, hierarchical format. Shows the directory structure with tree-like formatting, making it easy to understand the organization of files and folders.

Features:

  • Visual tree structure with Unicode box-drawing characters
  • Directory and file icons (📁 for directories, 📄 for files)
  • Configurable depth limit
  • Hides hidden files and directories (starting with .)
  • Sorted output (directories first, then files)
  • Permission error handling

Parameters:

  • path - (Optional) Directory path to display tree for. Defaults to current directory (.)
  • max_depth - (Optional) Maximum depth to traverse. Defaults to 3 levels

Examples:

# Show current directory tree (depth 3)
tree

# Show specific directory
tree src/

# Show with custom depth
tree . 5

# Show project structure
tree ~/projects/myapp 4

File Searching

search_file <pattern> <target>

Smart pattern matching that searches for text patterns within files and directories. Searches file contents (not just filenames) for the specified pattern and displays matching lines with file paths and line numbers. Automatically ignores common build and dependency directories.

Features:

  • Searches file contents, not just filenames
  • Shows file path, line number, and matching line content
  • Recursive directory search
  • Automatic ignore patterns (.git, node_modules, __pycache__, .env, venv, dist, build, etc.)
  • Gitignore-style pattern matching
  • Error recovery for permission issues
  • Works with both files and directories

Parameters:

  • pattern - Text pattern to search for (required)
  • target - File or directory to search in (required)

Ignored Patterns:

Automatically ignores: .git, node_modules, __pycache__, .env, venv, dist, build, .pytest_cache, .mypy_cache, .coverage, *.pyc, .DS_Store, Thumbs.db, .idea, .vscode, and more.

Examples:

# Search for pattern in current directory
search_file "TODO" .

# Search in specific directory
search_file "def main" src/

# Search in a single file
search_file "import" app.py

# Search for error handling
search_file "except" src/

# Search for configuration values
search_file "API_KEY" .

find_files <pattern> [dir]

Pattern-based file name searching using Unix shell-style wildcards (fnmatch). Searches for files whose names match the given pattern. More focused on filename matching rather than content searching. Supports wildcards like * and ?.

Features:

  • Unix shell-style wildcard pattern matching
  • Recursive directory search
  • Shows full file paths
  • Limits output to 20 results (shows count if more found)
  • Error handling for permission issues

Parameters:

  • pattern - Filename pattern with wildcards (required)
  • dir - (Optional) Directory to search in. Defaults to current directory (.)

Wildcard Patterns:

  • * - Matches any sequence of characters
  • ? - Matches any single character
  • [seq] - Matches any character in seq
  • [!seq] - Matches any character not in seq

Examples:

# Find all Python files
find_files "*.py"

# Find test files
find_files "test_*.py" src/

# Find configuration files
find_files "config.*" .

# Find files starting with uppercase
find_files "[A-Z]*.js" src/

# Find files with specific extension
find_files "*.json" config/

Note: This command searches for filenames, not file contents. Use search_file to search within file contents, or search_regex for regex-based content searching.

File Comparison

compare <file1> <file2>

Advanced file comparison with unified diff output and statistics. Shows differences between two files using the same advanced diff preview system as edit_file, including change statistics, syntax highlighting, and impact assessment.

Features:

  • Unified diff format with syntax highlighting
  • Change statistics (additions, deletions, modifications)
  • File size comparison
  • Impact level assessment
  • Preview of changes with line numbers
  • Error recovery for missing files
  • UTF-8 encoding support

Parameters:

  • file1 - Path to the first file (required)
  • file2 - Path to the second file (required)

Output Includes:

  • File information and language detection
  • Change statistics table
  • Unified diff with syntax highlighting
  • Preview of the result

Examples:

# Compare two versions of a file
compare old.py new.py

# Compare configuration files
compare config.json config.backup.json

# Compare with absolute paths
compare /path/to/file1.py /path/to/file2.py

# Compare different file versions
compare app_v1.js app_v2.js

diff <file1> <file2>

Alias for compare command. Provides the same advanced file comparison functionality for users familiar with Unix/Linux diff command.

Note: This command is functionally identical to compare and accepts the same parameters.

diff_dir <dir1> <dir2>

Directory tree diff and batch file comparison. Compares two directories by building indexes of all files and their SHA1 hashes, then shows differences in file structure and contents. Identifies files that exist in only one directory, files that differ, and files that are identical.

Features:

  • Recursive directory comparison
  • SHA1 hash-based file comparison
  • Identifies files only in dir1, only in dir2, and in both
  • Shows which files differ and which are identical
  • Tree-like overview of differences
  • Error recovery for missing directories
  • Handles permission errors gracefully

Parameters:

  • dir1 - Path to the first directory (required)
  • dir2 - Path to the second directory (required)

Output Categories:

  • Only in dir1: Files that exist only in the first directory
  • Only in dir2: Files that exist only in the second directory
  • Differ: Files that exist in both but have different content (different hashes)
  • Identical: Files that exist in both and have the same content (same hashes)

Examples:

# Compare two directory versions
diff_dir src/ src_backup/

# Compare project versions
diff_dir project_v1/ project_v2/

# Compare with absolute paths
diff_dir /path/to/dir1 /path/to/dir2

# Compare backup with current
diff_dir backup/2024-01-01/ current/

diff_semantic <file1> <file2>

AI-powered semantic code diff that understands the meaning and intent of changes, not just textual differences. Uses AI to analyze code changes and explain what was modified, why it might have been changed, and the impact of the changes. Particularly useful for understanding refactoring, bug fixes, and feature additions.

Features:

  • AI-powered semantic analysis of code changes
  • Explains what changed and why
  • Identifies refactoring, bug fixes, and feature additions
  • Language-aware analysis
  • Handles large files (truncates to 6000 characters per file)
  • Structured output with explanations
  • Requires AI to be enabled (API key configured)

Parameters:

  • file1 - Path to the first file (required)
  • file2 - Path to the second file (required)

AI Analysis Includes:

  • Summary of changes (what was modified)
  • Type of changes (refactoring, bug fix, feature addition, etc.)
  • Impact assessment
  • Potential issues or improvements
  • Context-aware explanations

Examples:

# Compare refactored code
diff_semantic old.py new.py

# Compare before and after bug fix
diff_semantic buggy.js fixed.js

# Compare feature additions
diff_semantic original.py enhanced.py

# Compare refactored components
diff_semantic refactored.jsx original.jsx

Requirement: This command requires AI to be enabled. Make sure you have configured an API key using apikey command.

File Utilities

hash <file> [algorithm]

Calculate cryptographic hash of a file using the specified algorithm. Useful for file integrity verification, duplicate detection, and security checks. Reads files in binary mode to ensure accurate hashing.

Features:

  • Multiple hash algorithms (MD5, SHA1, SHA256)
  • Binary file reading for accurate hashing
  • Hexadecimal hash output
  • Error handling for file access issues
  • Works with files of any size

Parameters:

  • file - Path to the file to hash (required)
  • algorithm - (Optional) Hash algorithm to use. Defaults to md5

Supported Algorithms:

  • md5 - MD5 hash (128-bit, fast, default)
  • sha1 - SHA-1 hash (160-bit, more secure than MD5)
  • sha256 - SHA-256 hash (256-bit, most secure, recommended for security)

Use Cases:

  • File integrity verification
  • Duplicate file detection
  • Security checksums
  • Version tracking

Examples:

# Calculate MD5 hash (default)
hash myfile.txt

# Calculate SHA-256 hash (most secure)
hash document.pdf sha256

# Calculate SHA-1 hash
hash script.py sha1

# Hash with absolute path
hash /path/to/file.zip sha256

validate <file>

File syntax validation for Python and JSON files. Checks if the file has valid syntax and reports any syntax errors with line numbers and error messages. Useful for catching syntax errors before running code or parsing configuration files.

Features:

  • Python syntax validation using ast module
  • JSON syntax validation with detailed error messages
  • Line number reporting for errors
  • Clear error messages
  • Error recovery for file access issues

Parameters:

  • file - Path to the file to validate (required)

Supported Formats:

  • Python (.py): Validates Python syntax using AST parsing
  • JSON (.json): Validates JSON syntax and structure

Validation Details:

  • Python: Parses the file as an AST and reports syntax errors with line numbers
  • JSON: Attempts to parse JSON and reports parsing errors with position information

Examples:

# Validate Python file
validate myfile.py

# Validate JSON configuration
validate config.json

# Validate script before running
validate script.py

# Validate with absolute path
validate /path/to/settings.json

format <file>

Automatic code formatting for Python, JavaScript, and TypeScript files. Formats code according to language-specific style guidelines and best practices. Uses external formatters (autopep8 for Python, black if available) to ensure consistent code style.

Features:

  • Automatic code formatting
  • Language-specific style guidelines
  • Consistent indentation and spacing
  • In-place file modification
  • Error handling for formatting failures

Parameters:

  • file - Path to the file to format (required)

Supported Formats:

  • Python (.py): Uses autopep8 or black for formatting (PEP 8 style guide)
  • JavaScript (.js): Uses external JavaScript formatter
  • TypeScript (.ts): Uses external TypeScript formatter

Formatting Standards:

  • Python: PEP 8 style guide (indentation, spacing, line length, etc.)
  • JavaScript/TypeScript: Standard formatting conventions

Examples:

# Format Python file
format myfile.py

# Format JavaScript file
format app.js

# Format TypeScript file
format component.ts

# Format with absolute path
format /path/to/script.py

Note: Formatting tools (autopep8, black) may need to be installed separately. The command will report if the required formatter is not available.

Best Practices

💡 Tips for File Operations:

  • Many file operations support both relative and absolute paths. Use ~ for home directory expansion.
  • Use read_file to preview files before editing with edit_file.
  • Always review the diff preview when using edit_file before confirming changes.
  • Use validate to check syntax before running Python scripts or parsing JSON files.
  • Use hash with SHA-256 for security-sensitive file verification.
  • Use diff_dir to compare project versions or backups.
  • Use tree to visualize directory structures before making changes.
  • File operations automatically ignore common build and dependency directories for better performance.