Skip to content

Instantly share code, notes, and snippets.

@davehague
Last active February 6, 2025 16:10
Show Gist options
  • Save davehague/19117e9f15fa023f6f6b4b1c0a4fd734 to your computer and use it in GitHub Desktop.
Save davehague/19117e9f15fa023f6f6b4b1c0a4fd734 to your computer and use it in GitHub Desktop.
Print a nicely formatted file tree

Often I'll find it helpful to give a LLM context of my file structure for coding projects, so I co-wrote this script to only grab the relevant files and output them in a nicely formatted tree.

It ignores common directories in a VS code (Nuxt and Vue) project and in a Pycharm (Python) project. It also only grabs files with approved extensions.

Powershell

function Print-Tree {
    param (
        [string]$Path,
        [string]$Indent = ""
    )

    $excluded = @('.nuxt', 'node_modules', '.venv', 'venv', '.idea', '__pycache__')
    $extensions = @(".py", ".txt", ".md", ".ini", ".ts", ".json", ".vue", ".yaml", ".env")

    
    Get-ChildItem -Path $Path | Where-Object { $_.Name -notin $excluded } | ForEach-Object {
        if ($_.PSIsContainer) {
            Write-Output "$Indent|-- $($_.Name)"
            Print-Tree -Path $_.FullName -Indent "$Indent|   "
        } else {                                           # Use this line for all extensions
        # } elseif ($extensions -contains $_.Extension) {  # Use this line to only include whitelisted extensions

            Write-Output "$Indent|-- $($_.Name)"
        }
    }
}

# Call the function with the initial path
Print-Tree -Path "C:\Users\david\source\davehague-site"

Bash

#!/bin/bash

print_tree() {
    local path="$1"
    local indent="$2"
    local excluded=("node_modules" ".nuxt" ".venv" "venv" ".idea" "__pycache__")
    local extensions=("py" "txt" "md" "ini" "ts" "json" "vue" "yaml" "env")

    for item in "$path"/*; do
        local name=$(basename "$item")
        if [[ -d "$item" ]]; then
            if [[ ! " ${excluded[@]} " =~ " $name " ]]; then
                echo "${indent}|-- $name"
                print_tree "$item" "${indent}|   "
            fi
        elif [[ -f "$item" ]]; then
            local ext="${name##*.}"
            # Uncomment the next line to only show whitelisted extensions
            # if [[ " ${extensions[@]} " =~ " $ext " ]]; then
            echo "${indent}|-- $name"
            # fi
        fi
    done
}

# Run the function with the given directory
print_tree "${1:-.}" ""

It's been really helpful to have this script to give the LLM extra context about my project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment