Skip to content

Instantly share code, notes, and snippets.

@Airbus5717
Created June 3, 2025 15:15
Show Gist options
  • Save Airbus5717/aa0a582b1faebf9e096d1169ac60adef to your computer and use it in GitHub Desktop.
Save Airbus5717/aa0a582b1faebf9e096d1169ac60adef to your computer and use it in GitHub Desktop.
NextJS project code files
def query_summary_code_base(project_path: str, max_file_size: int = 3000) -> str:
"""
Generate an intelligent prompt from a Next.js project, prioritizing relevant files
and providing structured context for AI assistance.
Args:
project_path (str): Path to the root of the Next.js project.
max_file_size (int): Maximum characters to read per file (default: 2000).
Returns:
str: A comprehensive prompt string optimized for Next.js development context.
"""
# Priority files - always include full content
priority_files = {
'package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',
'next.config.js', 'next.config.mjs', 'next.config.ts',
'tailwind.config.js', 'tailwind.config.ts',
'tsconfig.json', 'jsconfig.json',
'.env.local', '.env.example', '.env',
'middleware.js', 'middleware.ts',
'app/layout.tsx', 'app/layout.jsx', 'pages/_app.tsx', 'pages/_app.jsx',
'app/globals.css', 'styles/globals.css',
'README.md', 'CHANGELOG.md'
}
# Directories to completely ignore
ignore_dirs = {
'node_modules', '.next', '.git', 'dist', 'build', 'out',
'.vercel', '.netlify', 'coverage', '.nyc_output',
'.cache', 'tmp', 'temp'
}
# Static asset directories (list files but don't read content)
static_dirs = {'public', 'assets', 'static'}
# File extensions to prioritize for content reading
code_extensions = {
'.js', '.jsx', '.ts', '.tsx', # JavaScript/TypeScript
'.css', '.scss', '.sass', '.less', # Styles
'.json', '.yaml', '.yml', # Config
'.md', '.mdx', # Documentation
'.env', '.env.local', '.env.example', # Environment
'.graphql', '.gql', # GraphQL
'.sql', # Database
'.txt' # Text files
}
# File extensions to skip
skip_extensions = {
'.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.ico', # Images
'.woff', '.woff2', '.ttf', '.eot', '.otf', # Fonts
'.mp4', '.mp3', '.wav', '.avi', '.mov', # Media
'.pdf', '.zip', '.tar', '.gz', '.rar', # Archives
'.lock', '.log', '.cache' # System files
}
def should_read_content(file_path: str, rel_dir: str) -> bool:
"""Determine if file content should be read based on location and type."""
filename = os.path.basename(file_path)
file_ext = os.path.splitext(filename)[1].lower()
# Always read priority files
if any(filename == pf or file_path.endswith(pf) for pf in priority_files):
return True
# Skip static directories unless it's a priority file
if any(static_dir in rel_dir.split(os.sep) for static_dir in static_dirs):
return False
# Skip by extension
if file_ext in skip_extensions:
return False
# Read code files
if file_ext in code_extensions or not file_ext: # Include extensionless files
return True
return False
def get_file_priority(file_path: str) -> int:
"""Return priority score for file ordering (higher = more important)."""
filename = os.path.basename(file_path)
rel_path = file_path.lower()
# Highest priority: Core config files
if filename in priority_files:
return 100
# High priority: App structure files
if any(x in rel_path for x in ['app/layout', 'pages/_app', 'middleware']):
return 90
# High priority: Main pages and API routes
if '/app/' in rel_path or '/pages/' in rel_path:
if any(x in filename for x in ['page.', 'route.', 'layout.', 'loading.', 'error.']):
return 85
return 80
# Medium-high: Components and utilities
if any(x in rel_path for x in ['/components/', '/lib/', '/utils/', '/hooks/']):
return 70
# Medium: Styles and config
if any(x in rel_path for x in ['/styles/', '/css/']):
return 60
# Lower: Tests and docs
if any(x in rel_path for x in ['test', 'spec', '__tests__', 'docs']):
return 40
return 30
def extract_package_info(package_json_path: str) -> Dict:
"""Extract key information from package.json."""
try:
with open(package_json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return {
'name': data.get('name', 'Unknown'),
'version': data.get('version', 'Unknown'),
'nextjs_version': data.get('dependencies', {}).get('next', 'Unknown'),
'framework': 'Next.js',
'typescript': 'typescript' in data.get('dependencies', {}) or
'typescript' in data.get('devDependencies', {}),
'tailwind': 'tailwindcss' in data.get('dependencies', {}) or
'tailwindcss' in data.get('devDependencies', {}),
'key_deps': list(data.get('dependencies', {}).keys())[:10]
}
except:
return {'name': 'Unknown', 'framework': 'Next.js (assumed)'}
# Collect all files with metadata
all_files = []
project_info = None
for root, dirs, files in os.walk(project_path):
# Remove ignored directories
dirs[:] = [d for d in dirs if d not in ignore_dirs]
rel_dir = os.path.relpath(root, project_path)
if rel_dir == '.':
rel_dir = ''
for filename in files:
full_path = os.path.join(root, filename)
rel_path = os.path.join(rel_dir, filename) if rel_dir else filename
# Extract project info from package.json
if filename == 'package.json' and not project_info:
project_info = extract_package_info(full_path)
all_files.append({
'path': rel_path,
'full_path': full_path,
'priority': get_file_priority(rel_path),
'should_read': should_read_content(full_path, rel_dir),
'dir': rel_dir
})
# Sort files by priority and then alphabetically
all_files.sort(key=lambda x: (-x['priority'], x['path']))
# Build output sections
sections = []
# Project overview
if project_info:
overview = [
"=== PROJECT OVERVIEW ===",
f"Name: {project_info['name']}",
f"Framework: {project_info['framework']}",
f"Next.js Version: {project_info.get('nextjs_version', 'Unknown')}",
f"TypeScript: {'Yes' if project_info.get('typescript') else 'No'}",
f"Tailwind CSS: {'Yes' if project_info.get('tailwind') else 'No'}",
]
if project_info.get('key_deps'):
overview.append(f"Key Dependencies: {', '.join(project_info['key_deps'][:5])}")
sections.append('\n'.join(overview))
# Project structure
tree_lines = ["=== PROJECT STRUCTURE ==="]
current_dir = None
for file_info in all_files:
rel_path = file_info['path']
dir_name = os.path.dirname(rel_path) if os.path.dirname(rel_path) else '.'
filename = os.path.basename(rel_path)
if dir_name != current_dir:
depth = 0 if dir_name == '.' else dir_name.count(os.sep) + 1
indent = ' ' * depth
if dir_name != '.':
tree_lines.append(f"{indent}{os.path.basename(dir_name)}/")
current_dir = dir_name
file_depth = rel_path.count(os.sep)
file_indent = ' ' * (file_depth + 1)
# Add priority indicator
priority_indicator = "⭐" if file_info['priority'] >= 80 else ""
static_indicator = "📁" if not file_info['should_read'] else ""
tree_lines.append(f"{file_indent}{priority_indicator}{static_indicator}{filename}")
sections.append('\n'.join(tree_lines))
# File contents
content_lines = ["=== FILE CONTENTS ==="]
for file_info in all_files:
if not file_info['should_read']:
# Just show placeholder for static files
content_lines.extend([
f"\n--- {file_info['path']} ---",
"<static asset or binary file - content not shown>",
""
])
continue
try:
with open(file_info['full_path'], 'r', encoding='utf-8') as f:
content = f.read(max_file_size)
if len(content) == max_file_size:
# Check if we cut off mid-line
last_newline = content.rfind('\n')
if last_newline > max_file_size * 0.8: # If we're close to end
content = content[:last_newline]
content += "\n\n... [TRUNCATED - File continues beyond limit] ..."
content_lines.extend([
f"\n--- {file_info['path']} (Priority: {file_info['priority']}) ---",
content.rstrip(),
""
])
except (UnicodeDecodeError, OSError, PermissionError):
content_lines.extend([
f"\n--- {file_info['path']} ---",
"<unable to read file - may be binary or access denied>",
""
])
# Usage instructions
usage_section = [
"=== USAGE NOTES ===",
"This prompt contains a Next.js project structure with prioritized file contents.",
"⭐ = High priority files (core config, layouts, main pages)",
"📁 = Static assets (listed but content not shown)",
"Files are ordered by importance and relevance to development tasks.",
""
]
sections.append('\n'.join(content_lines))
sections.append('\n'.join(usage_section))
return '\n\n'.join(sections)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment