File Context Provider for AI Chats
This Python script helps you manually pass file context to AI chats using Markdown formatting. It accepts files and directories as command-line arguments, filters them based on Git repository ignore rules and custom patterns, and outputs the file names and contents in Markdown format.
Usage
python file_context_provider.py [-i <include_pattern>] [-e <exclude_pattern>] <file_or_directory>...
Code
import os
import sys
import argparse
import subprocess
import mimetypes
def is_git_repo(path):
"""Check if a path is inside a Git repository."""
try:
subprocess.check_output(['git', '-C', path, 'rev-parse', '--git-dir'], stderr=subprocess.STDOUT)
return True
except subprocess.CalledProcessError:
return False
def get_git_tracked_files(directory):
"""Get a list of tracked files in a Git repository."""
try:
output = subprocess.check_output(['git', '-C', directory, 'ls-files'], universal_newlines=True)
return output.splitlines()
except subprocess.CalledProcessError:
return []
def is_binary_file(file_path):
"""Check if a file is binary."""
mime_type = mimetypes.guess_type(file_path)[0]
return mime_type and not mime_type.startswith('text/')
def read_file_contents(file_path):
"""Read file contents, returning 'binary file' for binary files."""
if is_binary_file(file_path):
return 'binary file'
try:
with open(file_path, 'r', encoding='utf-8', errors='replace') as file:
return file.read()
except Exception as e:
print(f"Error reading {file_path}: {e}", file=sys.stderr)
return ''
def match_pattern(file_path, patterns):
"""Check if a file path matches any of the given patterns."""
import fnmatch
for pattern in patterns:
if fnmatch.fnmatch(file_path, pattern):
return True
return False
def process_file(file_path, include_patterns=None, exclude_patterns=None):
"""Process a single file, applying filters and printing Markdown output."""
relative_path = os.path.relpath(file_path)
if include_patterns and not match_pattern(relative_path, include_patterns):
return
if exclude_patterns and match_pattern(relative_path, exclude_patterns):
return
print(f"`{relative_path}`")
print("```")
print(read_file_contents(file_path))
print("```\n")
def traverse_directory(directory, include_patterns=None, exclude_patterns=None):
"""Traverse a directory, applying Git ignore rules and custom filters."""
if is_git_repo(directory):
tracked_files = get_git_tracked_files(directory)
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, directory)
if relative_path in tracked_files:
process_file(file_path, include_patterns, exclude_patterns)
else:
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
process_file(file_path, include_patterns, exclude_patterns)
def main():
parser = argparse.ArgumentParser(description='File Context Provider for AI Chats')
parser.add_argument('paths', nargs='+', help='files or directories to process')
parser.add_argument('-i', '--include', action='append', help='include files matching pattern (e.g., *.py)')
parser.add_argument('-e', '--exclude', action='append', help='exclude files matching pattern (e.g., *.tmp)')
args = parser.parse_args()
for path in args.paths:
if os.path.isfile(path):
process_file(path, args.include, args.exclude)
elif os.path.isdir(path):
traverse_directory(path, args.include, args.exclude)
else:
print(f"Error: {path} is not a file or directory", file=sys.stderr)
if __name__ == '__main__':
main()
Explanation
- The script uses
argparse to parse command-line arguments, including files/directories and optional include/exclude patterns.
- It checks if a directory is inside a Git repository using
git rev-parse --git-dir. If so, it only processes files tracked by Git (git ls-files).
- For each file, it:
- Checks if the file is binary using
mimetypes. If binary, it outputs "binary file".
- Applies include/exclude patterns using
fnmatch.
- Prints the file name enclosed in single backticks and its contents enclosed in triple backticks (constructed by concatenating three separate backtick characters to avoid Markdown formatting issues).
- The
traverse_directory function walks through directories, applying the above logic to each file.
Example Usage
# Process a single file
python file_context_provider.py example.txt
# Process a directory, respecting Git ignore rules
python file_context_provider.py my_project/
# Include only Python files
python file_context_provider.py -i *.py my_project/
# Exclude temporary files
python file_context_provider.py -e *.tmp my_project/
# Combine include and exclude patterns
python file_context_provider.py -i *.py -e *_test.py my_project/
Feel free to modify the script to suit your specific needs!