Documentation

Overview

CopyTree revolutionizes how developers share codebases with AI, turning complex projects into optimized, AI-ready formats effortlessly. Compatible with Claude, ChatGPT, Grok, and Gemini through standardized output formats, with built-in AI features exclusively powered by Gemini integration. CopyTree solves the fundamental challenge of sharing complete code context with AI assistants.

Core Purpose

CopyTree addresses a critical workflow gap in AI-assisted development: how to efficiently share an entire codebase with an AI that has a limited context window. Rather than manually copying and pasting files, CopyTree automates this process with intelligent file selection, transformation, and formatting.

Architecture

CopyTree employs a sophisticated pipeline architecture that processes files through 16 distinct stages:

FileDiscovery ExternalSource ProfileFilter GitFilter AlwaysInclude
NPM/Composer Deduplicate Sort FileLoading Transform
CharLimit Limit OutputFormatting StreamingOutput
ComposerStage Result

Key Architectural Components

Pipeline System

Event-driven, sequential processing with error recovery

Service Layer

AI integration (Gemini), caching, git operations

Transformer System

16+ pluggable file transformers

Profile Engine

YAML-based configuration templates

Installation

Prerequisites

System Requirements

Don't worry—CopyTree plays nice with your existing setup.

  • Node.js: Version 18.0.0 or higher (check with node --version)
  • npm: Version 8.0.0 or higher (comes with Node.js)
  • Git: For repository operations (optional)
  • Pandoc: For advanced document transformers (optional)

Installation Methods

Install globally for system-wide access. This is the recommended approach for most users.

Install

bash
npm install -g copytree

Verify

bash
copytree --version

Environment Setup

Create a .env file in your home directory or project root:

.env
# AI Configuration (required for AI features)
GEMINI_API_KEY=your-api-key-here

# Optional: Performance tuning
COPYTREE_MAX_FILE_SIZE=configurable  # Set size limit
COPYTREE_MAX_TOTAL_SIZE=configurable # Set total limit
COPYTREE_MAX_CONCURRENCY=5

# Optional: Cache settings
CACHE_ENABLED=true
CACHE_FILE_PATH=~/.copytree/cache

Getting a Gemini API Key

  1. 1. Visit Google AI Studio
  2. 2. Sign in with your Google account
  3. 3. Click "Create API Key"
  4. 4. Copy the key and add it to your .env file

Verification

After installation, verify that CopyTree is properly configured:

bash
# Run setup wizard
copytree install:copytree

# Validate configuration
copytree config:validate

# List available profiles
copytree profile:list

Success!

If all commands run without errors, CopyTree is ready to use. You can now start copying your codebase!

Common Installation Issues

Permission denied error

If you encounter permission errors during global installation:

bash
# Option 1: Use npm's global directory
npm config set prefix ~/.npm-global
export PATH=~/.npm-global/bin:$PATH
npm install -g copytree

# Option 2: Use sudo (not recommended)
sudo npm install -g copytree

Node version too old

Update Node.js using nvm (Node Version Manager):

bash
# Install nvm (if not already installed)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Install latest Node.js
nvm install node
nvm use node

Quick Start

Get up and running with CopyTree. These examples show the most common use cases.

Getting Started

01

Install CopyTree

Get started with a simple npm install command

bash
npm install -g copytree
02

Copy Your Codebase

Run copytree in your project directory to copy it to your clipboard

bash
copytree
03

Paste & Plan

Your codebase is now copied to clipboard in AI-ready format. Simply paste it into Claude, ChatGPT, Grok, or any AI assistant to start building amazing things.

More Examples

Copy specific directory

Point CopyTree to any directory on your system.

bash
copytree /path/to/my-project

Copy GitHub repository

Directly copy any public GitHub repository without cloning it first.

bash
copytree https://github.com/facebook/react

Use custom profile

Apply a custom profile tailored to your project.

bash
copytree --profile mycustom

Focus on modified files

Only copy files with uncommitted changes - perfect for debugging recent issues.

bash
copytree --modified

Common Workflows

Debugging recent changes

Focus on modified files to identify issues.

bash
copytree --modified

Code review preparation

Compare changes between branches for thorough reviews.

bash
copytree --changed main --output review.xml

Documentation generation

Create reference documentation from your codebase.

bash
copytree --profile docs-custom --as-reference

Project overview

Get a visual directory structure with git status.

bash
copytree --only-tree --with-git-status

What Happens Next?

1

CopyTree analyzes your project

Detects framework, identifies relevant files, respects .gitignore

2

Files are processed and transformed

Applies appropriate transformers for PDFs, images, and code files

3

Output is formatted and copied

XML/JSON output is automatically copied to your clipboard

4

Paste into your AI assistant

Share with Claude, ChatGPT, or any LLM for instant context

Pro Tips

  • 💡 Use --dry-run to preview what will be copied before execution
  • 💡 Combine filters for precise control: --filter "src/**" "!**/*.test.js"
  • 💡 Save frequently used commands as shell aliases for easy access
  • 💡 Use --output to save results for team sharing or documentation

Usage

Basic Usage

The simplest form copies the current directory:

bash
copytree

Output is automatically copied to your clipboard, ready to paste into your AI assistant.

Command Syntax

bash
copytree [path] [options]

[path] - Optional path to directory or GitHub URL (defaults to current directory)

[options] - Command-line options to customize behavior

Key Options

These patterns embody CopyTree's philosophy: Build smarter, not harder.

OptionShortDescriptionWhen to Use
--profile-pUse custom profile (overrides default)--profile mycustom
--filter-fAdditional patterns--filter "*.test.js"
--output-oSave to file--output context.xml
--formatOutput format--format json
--modified-mGit modified files only--modified
--changed-cFiles changed since ref--changed main
--dry-runPreview without copying--dry-run
--head-lLimit file count--head 100
--char-limit-CCharacter limit--char-limit 50000
--only-treeDirectory tree only--only-tree
--no-cacheDisable AI caching--no-cache

Output Formats

CopyTree supports three output formats, each optimized for different use cases:

Structured format ideal for AI consumption with clear hierarchy.

xml
<project>
  <file path="src/index.js">
    <content>// File content here
console.log('Hello, World!');</content>
  </file>
  <file path="src/utils.js">
    <content>export function formatDate(date) {
  return new Date(date).toLocaleDateString();
}</content>
  </file>
</project>

Filtering Examples

Include only JavaScript files

bash
copytree --filter "**/*.js"

Exclude test files

bash
copytree --filter "!**/*.test.js"

Multiple filters

bash
copytree --filter "src/**" "!**/*.spec.js"

Always include specific files

bash
copytree --always "README.md" "package.json"

Git Integration Examples

Only modified files (uncommitted changes)

bash
copytree --modified

Files changed since last commit

bash
copytree --changed HEAD~1

Files changed between branches

bash
copytree --changed main..feature-branch

Modified files with context

bash
copytree --modified --with-git-status

Advanced Usage Patterns

Combine multiple options for precise control

This example shows how to copy only TypeScript files from the src directory that have been modified, with a character limit to stay within AI context windows.

bash
copytree --filter "src/**/*.ts" --modified --char-limit 100000 --format json

Create a comprehensive project snapshot

Perfect for creating documentation or sharing project structure with team members.

bash
copytree --profile docs-custom --as-reference --output project-snapshot.xml --with-stats

Debug production issues with focused context

When debugging production issues, focus on modified files in critical directories.

bash
copytree --filter "src/api/**" "src/services/**" --modified --format json

Configuration

CopyTree uses a flexible configuration system that allows you to customize behavior at multiple levels.

Configuration Hierarchy

CopyTree uses a multi-level configuration system with the following priority (highest to lowest):

1
Command-line arguments Highest priority
2
Project .copytreerc file Project-specific settings
3
Home directory .copytreerc User defaults
4
Environment variables System-wide settings
5
Built-in defaults Lowest priority

Configuration File (.copytreerc)

Create a .copytreerc file in your project root or home directory. # Customize filters to match your project's 'forest' of files.

.copytreerc
{
  "profile": "laravel",
  "format": "xml",
  "transforms": {
    "enabled": true,
    "preferredTransformers": ["ai-summary", "pdf", "image-description"]
  },
  "filters": {
    "include": ["src/**", "app/**"],
    "exclude": ["**/*.test.js", "node_modules/**", "vendor/**"],
    "alwaysInclude": ["README.md", "package.json", "composer.json"]
  },
  "output": {
    "charLimit": 100000,
    "fileLimit": 500,
    "clipboard": true
  },
  "git": {
    "respectGitignore": true,
    "includeUntracked": false
  },
  "cache": {
    "enabled": true,
    "ttl": 86400
  }
}

Environment Variables

CopyTree uses these environment variables:

bash
# Required for AI features
export GEMINI_API_KEY=your-api-key-here

# Performance settings
export COPYTREE_MAX_FILE_SIZE=1048576
export COPYTREE_MAX_TOTAL_SIZE=10485760
export COPYTREE_MAX_CONCURRENCY=5

# Cache configuration
export CACHE_ENABLED=true
export CACHE_FILE_PATH=~/.copytree/cache

Profile-Specific Configuration

You can create custom profiles or override existing ones by creating a .copytree/profiles/ directory in your project:

.copytree/profiles/my-custom-profile.yaml
# .copytree/profiles/my-custom-profile.yaml
name: my-custom-profile
description: Custom profile for my specific project

include:
  - "src/**/*.js"
  - "lib/**/*.js"
  - "config/**"

exclude:
  - "**/*.test.js"
  - "**/*.spec.js"
  - "**/node_modules/**"
  - "**/coverage/**"

alwaysInclude:
  - "README.md"
  - "package.json"
  - ".env.example"

transforms:
  enabled: true
  preferredTransformers:
    - ai-summary
    - pdf
    - image-description

options:
  respectGitignore: true
  includeUntracked: false
  charLimit: 150000

Command Configuration Examples

View current configuration

bash
copytree config:show

Validate configuration

bash
copytree config:validate

Create default configuration file

bash
copytree config:init

Configuration Best Practices

  • Use project-specific .copytreerc files

    Keep configuration with your code for team consistency

  • Store API keys in environment variables

    Never commit sensitive information to version control

  • Override with command-line options

    Use CLI flags for one-off changes without modifying config files

  • Start with a profile, then customize

    Build on existing profiles rather than starting from scratch

Profiles

CopyTree uses a default profile as the baseline configuration, with easy custom profile creation for project-specific file selection and processing rules.

Default Profile

CopyTree ships with a versatile default profile that works for most projects:

ProfileDescription
defaultGeneral purpose profile that works for any project type

Using Profiles

Use default profile

bash
copytree  # Uses default profile automatically

Use custom profile

bash
copytree --profile mycustom

List available profiles

bash
copytree profile:list

Show profile details

bash
copytree profile:show mycustom

Profile Examples

Default Profile: Versatile baseline for any project

The default profile provides sensible defaults that work across different project types and frameworks.

yaml
include:
  - "**/*"
  
exclude:
  - "node_modules/**"
  - ".git/**"
  - "dist/**"
  - "build/**"
  - "**/*.log"
  - "**/.DS_Store"
  
alwaysInclude:
  - "README.md"
  - "package.json"
  - ".gitignore"

Creating Custom Profiles

Create custom profiles by adding YAML files to .copytree/profiles/ in your project:

.copytree/profiles/my-monorepo.yaml
# .copytree/profiles/my-monorepo.yaml
name: my-monorepo
description: Custom profile for our monorepo structure

# Base profile to extend from
extends: default

# File patterns to include
include:
  - "packages/*/src/**"
  - "apps/*/src/**"
  - "shared/**"

# File patterns to exclude  
exclude:
  - "**/node_modules/**"
  - "**/dist/**"
  - "**/build/**"
  - "**/*.test.*"
  - "**/__tests__/**"

# Files to always include regardless of filters
alwaysInclude:
  - "README.md"
  - "lerna.json"
  - "package.json"
  - "pnpm-workspace.yaml"

# Transformer configuration
transforms:
  enabled: true
  preferredTransformers:
    - ai-summary
    - pdf
    - image-description
  
# Additional options
options:
  respectGitignore: true
  includeUntracked: false
  charLimit: 200000
  fileLimit: 1000

Profile Inheritance

Profiles can extend other profiles to inherit and override settings:

How inheritance works:

  1. 1. The child profile starts with all settings from the parent profile
  2. 2. Arrays (include, exclude) are merged with parent values
  3. 3. Objects (options, transforms) are deep merged
  4. 4. Scalar values (strings, numbers) are overridden
yaml
# Extending the default profile for React projects
name: react-custom
extends: default
description: Custom React project configuration

# Add React-specific excludes
exclude:
  - "build/**"
  - "coverage/**"
  - "**/*.test.{js,jsx}"
  
# Add React-specific includes
include:
  - "src/**/*.{js,jsx,ts,tsx}"
  - "public/**"
  
# Override options
options:
  charLimit: 100000

Profile Best Practices

Start with built-in profiles

Use existing profiles as a foundation and customize as needed.

Keep profiles focused

Create specific profiles for different use cases rather than one complex profile.

Document your profiles

Add clear descriptions to help team members understand profile purposes.

Version control profiles

Commit custom profiles to ensure team consistency across environments.

Transformers

Transformers are plugins that process specific file types to extract meaningful content. They enable CopyTree to handle PDFs, images, and other non-text formats intelligently.

How Transformers Work

1. File Detection

CopyTree identifies file types based on extensions and content

2. Transformation

Appropriate transformer processes the file to extract content

3. AI-Ready Output

Content is formatted for optimal AI understanding

Available Transformers

AI-Powered: Leverage Gemini to summarize code, describe images, and more—turning raw files into insightful context.

ai-summary

Generates intelligent code summaries using Gemini AI

Files: .js, .py, .java, .php, .rb, .go, .rs, .swift
Example: Summarizes complex functions and classes into plain English
image-description

Describes images using vision models

Files: .jpg, .png, .gif, .webp
Example: Provides detailed descriptions of UI mockups and diagrams
svg-description

Analyzes and describes SVG graphics

Files: .svg
Example: Explains icons, logos, and vector illustrations
unit-test-summary

Analyzes test files and summarizes coverage

Files: *test.js, *.spec.ts, *_test.py
Example: Summarizes what functionality is being tested

Document Processing: Leverage Gemini to summarize code, describe images, and more—turning raw files into insightful context.

pdf

Extracts text content from PDF files

Files: .pdf
Example: Converts technical documentation PDFs to readable text
document-to-text

Converts various document formats to plain text

Files: .docx, .odt, .rtf
Example: Extracts content from Word documents and specifications
csv

Formats CSV data as readable tables

Files: .csv, .tsv
Example: Converts data files into markdown tables

Text Processing: Leverage Gemini to summarize code, describe images, and more—turning raw files into insightful context.

markdown

Strips or converts markdown formatting

Files: .md
Example: Cleans up README files for better AI parsing
html-stripper

Removes HTML tags and extracts text

Files: .html, .htm
Example: Extracts content from web pages and templates
first-lines

Extracts first N lines of large files

Files: Large text files
Example: Previews large log files or data dumps
markdown-link-stripper

Removes markdown links while keeping text

Files: .md
Example: Simplifies documentation for AI consumption

Core: Leverage Gemini to summarize code, describe images, and more—turning raw files into insightful context.

file-loader

Default file reading transformer

Files: All text files
Example: Standard text file loading
binary

Handles binary files with metadata

Files: Binary formats
Example: Shows file size and type for images, executables
file-summary

Creates basic summaries without AI

Files: All files
Example: File metadata and basic statistics

Using Transformers

Transformers are configured through profile files, not command-line flags. Enable or disable specific transformers in your profile configuration:

Profile Configuration

yaml
# profile.yml
transformers:
  pdf:
    enabled: true
    options:
      maxPages: 50
  ai-summary:
    enabled: true
    options:
      maxFileSize: 102400
  markdown:
    enabled: false

Using Profile with Transformers

bash
copytree --profile my-profile

Disable AI Caching

bash
copytree --no-cache

Useful when testing AI transformers with fresh results

Transformer Examples

The AI Summary transformer uses Gemini AI to create intelligent summaries of code files:

Original Code
javascript
export class UserAuthService {
  private tokenCache = new Map();
  
  async authenticate(email, password) {
    const hashedPassword = await bcrypt.hash(password, 10);
    const user = await db.users.findOne({ email });
    
    if (!user || !await bcrypt.compare(password, user.password)) {
      throw new AuthError('Invalid credentials');
    }
    
    const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET);
    this.tokenCache.set(user.id, token);
    
    return { user, token };
  }
}
AI Summary Output

UserAuthService Class Summary:

This service handles user authentication with the following features:
• Password hashing using bcrypt
• Database user lookup by email
• JWT token generation
• In-memory token caching
• Throws AuthError on invalid credentials

Key dependencies: bcrypt, jsonwebtoken, database connection

Creating Custom Transformers

You can create custom transformers by adding JavaScript files to the transformers directory:

.copytree/transformers/my-transformer.js
// .copytree/transformers/my-transformer.js
module.exports = {
  name: 'my-transformer',
  
  // File patterns this transformer handles
  patterns: ['*.myext', '*.custom'],
  
  // Priority (higher runs first)
  priority: 100,
  
  // Transform function
  async transform(file, content, options) {
    // Process the file content
    const processed = await myCustomProcessing(content);
    
    // Return transformed content
    return {
      content: processed,
      metadata: {
        transformer: 'my-transformer',
        processedAt: new Date().toISOString()
      }
    };
  },
  
  // Optional: Check if transformer should run
  shouldTransform(file, options) {
    // Custom logic to determine if transformer applies
    return file.size < 1000000; // Only files under 1MB
  }
};

Transformer Configuration

Configure transformer behavior in your .copytreerc file:

json
{
  "transforms": {
    "enabled": true,
    "preferredTransformers": [
      "ai-summary",
      "pdf",
      "image-description"
    ],
    "transformerOptions": {
      "ai-summary": {
        "maxLength": 500,
        "style": "technical"
      },
      "pdf": {
        "extractImages": false,
        "preserveFormatting": true
      },
      "first-lines": {
        "lineCount": 50
      }
    },
    "customTransformersPath": ".copytree/transformers"
  }
}

Commands Reference

Complete reference for all CopyTree commands and options.

Main Commands

CommandDescription
copytree [path]Copy files from path (default: current directory)
copytree --helpShow help and all available options
copytree --versionDisplay CopyTree version

Command Options

File Selection Options

--filter, -f <pattern>

Include/exclude files matching glob pattern

--always <files>

Always include specific files regardless of filters

--profile, -p <name>

Use a specific profile configuration

Git Integration Options

--modified, -m

Only include git modified files (uncommitted changes)

--changed, -c <ref>

Files changed since git reference (commit/branch)

--with-git-status

Include git status information in output

Output Options

--output, -o <file>

Save output to file instead of clipboard

--format <type>

Output format: xml (default), json, or tree

--only-tree

Only output directory tree structure

--no-clipboard

Don't copy output to clipboard

Limit Options

--head, -l <count>

Limit number of files to include

--char-limit, -C <chars>

Limit total output characters

--max-file-size <bytes>

Skip files larger than specified size

Transform Options

--no-transform

Disable all transformers

--transformers <list>

Use specific transformers (comma-separated)

--no-cache

Disable AI response caching

Other Options

--dry-run

Preview what will be copied without executing

--verbose, -v

Show detailed progress information

--quiet, -q

Suppress all output except errors

--as-reference

Add reference header for documentation

Profile Commands

Use this to switch profiles seamlessly.

CommandDescription
copytree profile:listList all available profiles
copytree profile:show <name>Show details of a specific profile
copytree profile:create <name>Create a new custom profile

Configuration Commands

CommandDescription
copytree config:showDisplay current configuration
copytree config:validateValidate configuration files
copytree config:initCreate default configuration file

Utility Commands

CommandDescription
copytree install:copytreeRun interactive setup wizard
copytree cache:clearClear the AI response cache
copytree self-updateUpdate CopyTree to latest version

Command Examples

Complex filtering

bash
copytree --filter "src/**/*.js" "!**/*.test.js" --always "README.md"

Git-focused copy

bash
copytree --changed main --with-git-status --format json

Limited output with AI

bash
copytree --head 50 --char-limit 100000 --format json

Preview with profile

bash
copytree --profile laravel --dry-run --verbose

Exit Codes

0 Success - operation completed without errors
1 General error - check error message for details
2 Invalid arguments or options
3 File or directory not found
4 Configuration error

Advanced Features

Unlock the full potential of CopyTree with these advanced features and techniques.

GitHub Repository Support

Harness git's power to focus AI on what matters—recent changes in your development journey.

Copy public repository

bash
copytree https://github.com/facebook/react

Copy specific branch

bash
copytree https://github.com/vercel/next.js --branch canary

Copy with authentication (private repos)

bash
GITHUB_TOKEN=your_token copytree https://github.com/org/private-repo

GitHub Integration Features

  • • Automatic sparse checkout for large repositories
  • • Respects repository .gitignore and .copytreerc
  • • Caches repository data for efficient subsequent runs
  • • Supports GitHub Enterprise with custom URLs

Streaming Large Files

CopyTree automatically streams large files to handle massive codebases efficiently:

Streaming Architecture

Automatic Detection: Large files are automatically streamed based on configurable threshold
Memory Efficient: Uses Node.js streams to process files in chunks
Progress Tracking: Real-time progress for large file operations
Configurable: Adjust streaming threshold via environment variables

AI Cache System

CopyTree implements intelligent caching for AI-powered transformers to reduce API calls:

bash
# Cache configuration in .copytreerc
{
  "cache": {
    "enabled": true,
    "ttl": 86400,              // 24 hours in seconds
    "maxSize": "auto",         // Configurable cache size limit
    "strategy": "lru",         // Least Recently Used eviction
    "location": "~/.copytree/cache"
  }
}

# Clear cache manually
copytree cache:clear

# Run without cache
copytree --no-cache

# Show cache statistics
copytree cache:stats

Performance Impact

Improved efficiency for repeated runs on same codebase

Cost Savings

Reduces AI API calls significantly

Smart Invalidation

Auto-invalidates when files change

Custom Pipeline Stages

Extend CopyTree's pipeline with custom processing stages:

.copytree/pipeline/my-stage.js
// .copytree/pipeline/my-stage.js
module.exports = {
  name: 'my-custom-stage',
  order: 550, // Runs after transform (500) but before output (600)
  
  async process(files, options, context) {
    // Add custom metadata to all files
    const processedFiles = await Promise.all(
      files.map(async (file) => {
        const metrics = await analyzeCode(file.content);
        
        return {
          ...file,
          metadata: {
            ...file.metadata,
            complexity: metrics.complexity,
            lines: metrics.lines,
            dependencies: metrics.dependencies
          }
        };
      })
    );
    
    // Emit event for monitoring
    context.emit('custom-stage:complete', {
      filesProcessed: processedFiles.length
    });
    
    return processedFiles;
  }
};

Scripting and Automation

Automate CopyTree workflows with scripts:

copytree-daily-summary.sh
#!/bin/bash
# copytree-daily-summary.sh

# Configuration
OUTPUT_DIR="./ai-contexts"
DATE=$(date +%Y-%m-%d)

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Generate different contexts for different purposes
echo "Generating code contexts..."

# 1. Modified files context
copytree --modified \
         --format xml \
         --output "$OUTPUT_DIR/daily-changes-$DATE.xml"

# 2. Full project snapshot
copytree --profile default \
         --char-limit 500000 \
         --output "$OUTPUT_DIR/project-snapshot-$DATE.xml"

# 3. Test coverage context
copytree --filter "**/*.test.*" "**/*.spec.*" \
         --transformers "unit-test-summary" \
         --output "$OUTPUT_DIR/test-coverage-$DATE.xml"

# 4. Architecture overview
copytree --only-tree \
         --with-stats \
         --output "$OUTPUT_DIR/architecture-$DATE.txt"

echo "✅ Generated contexts in $OUTPUT_DIR"

# Optional: Upload to cloud storage
# aws s3 sync "$OUTPUT_DIR" "s3://my-bucket/copytree-contexts/"

Performance Optimization

Performance Tips

File Selection
  • • Use specific filters to reduce file count
  • • Leverage --head to limit files processed
  • • Exclude large binary directories
  • • Use profiles for consistent filtering
Caching
  • • Keep cache enabled for AI transformers
  • • Set appropriate cache TTL values
  • • Clear cache periodically for freshness
  • • Use --no-cache for critical updates
Concurrency
  • • Adjust COPYTREE_MAX_CONCURRENCY
  • • Balance CPU and memory usage
  • • Monitor system resources
  • • Use --verbose to track bottlenecks
Output Size
  • • Use --char-limit for large projects
  • • Consider JSON for smaller output
  • • Disable unused transformers
  • • Stream large outputs to files

Environment Variables Reference

COPYTREE_DEBUG

Enable debug logging (true/false)

COPYTREE_COLORS

Enable/disable colored output

COPYTREE_TIMEOUT

Global timeout in milliseconds

COPYTREE_TEMP_DIR

Custom temporary directory path

COPYTREE_PARALLEL_JOBS

Number of parallel processing jobs

COPYTREE_MEMORY_LIMIT

Maximum memory usage in MB

Troubleshooting

Solutions to common issues and error messages you might encounter while using CopyTree.

Common Issues

Error: GEMINI_API_KEY not found

We've got you—here's how to resolve 'GEMINI_API_KEY not found' quickly.

Solution:
bash
# Option 1: Set in .env file
echo "GEMINI_API_KEY=your-api-key-here" >> ~/.env

# Option 2: Export in shell
export GEMINI_API_KEY="your-api-key-here"

# Option 3: Pass inline
GEMINI_API_KEY="your-api-key-here" copytree

# Option 4: Use simpler output format
copytree --format json

Error: Output exceeds clipboard limit

Some systems have clipboard size limitations that prevent copying large outputs.

Solution:
bash
# Save to file instead
copytree --output context.xml

# Limit output size
copytree --char-limit 50000

# Use head to limit files
copytree --head 100

# Disable clipboard and use stdout
copytree --no-clipboard > output.xml

Error: Permission denied

File permission issues when trying to read protected files or directories.

Solution:
bash
# Check file permissions
ls -la problem-directory/

# Run with appropriate user
sudo copytree  # Not recommended

# Exclude problematic directories
copytree --filter "!**/protected-dir/**"

# Change permissions if you own the files
chmod -R 644 project-directory/

Warning: Skipping large file

Files exceeding the size limit are automatically skipped to prevent memory issues.

Solution:
bash
# Increase file size limit
export COPYTREE_MAX_FILE_SIZE=configurable_size
copytree

# Use first-lines transformer for large files
copytree --transformers "first-lines" --transformer-options '{"lineCount": 100}'

# Force include specific large files
copytree --always "large-important-file.sql"

Performance Issues

Slow processing

Try these optimizations:

  • Use specific filters to reduce file count
  • Use JSON format for machine processing
  • Increase concurrency: COPYTREE_MAX_CONCURRENCY=10
  • Use cache for repeated runs

High memory usage

Reduce memory consumption:

  • Lower concurrency settings
  • Use --head to limit files
  • Enable streaming for large files
  • Set memory limit: COPYTREE_MEMORY_LIMIT=1024

Git-Related Issues

Not a git repository error

This occurs when using git-related options in a non-git directory.

bash
# Initialize git repository
git init

# Or use without git features
copytree --no-git

Invalid git reference

When using --changed with a non-existent branch or commit.

bash
# List available branches
git branch -a

# Use valid reference
copytree --changed origin/main

Debugging Tools

Built-in Debugging Options

copytree --verbose

Show detailed progress and operations

copytree --dry-run

Preview what will be processed without executing

COPYTREE_DEBUG=true copytree

Enable debug logging with stack traces

copytree config:validate

Check configuration for errors

copytree --stats

Show processing statistics after completion

Error Messages Reference

ENOENT

File or directory not found

Check path spelling and permissions

EACCES

Permission denied

Insufficient permissions to read file

ENOMEM

Out of memory

Reduce file count or increase system memory

ETIMEDOUT

Operation timed out

Increase timeout or check network connection

Getting Help

Support Resources

GitHub Issues

Report bugs and request features

Discussions

Ask questions and share tips

Documentation

You're already here!

FAQ

Check common questions first