Buckets:
# pdd/construct_paths.py
from __future__ import annotations
import sys
import os
import glob
from pathlib import Path
from typing import Dict, Tuple, Any, Optional, List, Callable
import fnmatch
import logging
import warnings
import click
import yaml
from rich.theme import Theme
from .cli_theme import get_console
from .get_extension import get_extension
from .get_language import get_language
from .generate_output_paths import EXAMPLES_DIR, generate_output_paths
def _resolve_default_examples_dir(project_root: Optional[Path] = None) -> str:
"""Return the default examples-dir name when no `.pddrc` configures one.
Returns :data:`EXAMPLES_DIR` (canonical default). Only falls back to
``"context"`` when the project root has no ``examples/`` directory AND a
``context/`` directory containing at least one ``*_example.*`` file — i.e.
actual evidence of a legacy examples layout, not just any context content
(PRDs, schemas, docs are NOT a legacy-examples signal). This prevents the
original mismatch from staying alive on greenfield projects (#616).
"""
root = project_root or Path.cwd()
examples = root / EXAMPLES_DIR
legacy = root / "context"
if examples.exists() or not legacy.is_dir():
return EXAMPLES_DIR
try:
if next(legacy.rglob("*_example.*"), None) is not None:
return "context"
except OSError:
pass
return EXAMPLES_DIR
def _default_examples_project_root(pddrc_path: Optional[Path]) -> Path:
"""Return the base directory used for implicit examples-dir detection."""
return pddrc_path.parent if pddrc_path else Path.cwd()
# Assume generate_output_paths raises ValueError on unknown command
# Add csv import for the new helper function
import csv
console = get_console(theme=Theme({"info": "cyan", "warning": "yellow", "error": "bold red"}))
def _extract_prefix_from_prompts_dir(prompts_dir: str) -> str:
"""Extract the path suffix after the 'prompts' segment in a prompts_dir value.
Splits on '/' and finds the exact 'prompts' segment, then returns everything
after it. Returns empty string when prompts_dir is exactly 'prompts' or ends
at a 'prompts' segment. Falls back to returning the full normalized path when
no exact 'prompts' segment exists.
Examples:
"prompts" -> ""
"prompts/frontend" -> "frontend"
"extensions/github_pdd_app/prompts/frontend" -> "frontend"
"extensions/app/prompts" -> ""
"""
normalized = prompts_dir.rstrip('/')
parts = normalized.split('/')
try:
idx = parts.index('prompts')
except ValueError:
return normalized
return '/'.join(parts[idx + 1:])
# Shared mapping of language → file extension used across the codebase.
BUILTIN_EXT_MAP = {
'python': '.py', 'javascript': '.js', 'typescript': '.ts', 'java': '.java',
'cpp': '.cpp', 'c': '.c', 'go': '.go', 'ruby': '.rb', 'rust': '.rs',
'kotlin': '.kt', 'swift': '.swift', 'csharp': '.cs', 'php': '.php',
'scala': '.scala', 'r': '.r', 'lua': '.lua', 'perl': '.pl', 'bash': '.sh',
'shell': '.sh', 'powershell': '.ps1', 'sql': '.sql', 'html': '.html', 'css': '.css',
'prompt': '.prompt', 'makefile': '',
# Frontend framework variants
'typescriptreact': '.tsx', 'javascriptreact': '.jsx',
'svelte': '.svelte', 'vue': '.vue',
# Common data/config formats
'json': '.json', 'jsonl': '.jsonl', 'yaml': '.yaml', 'yml': '.yml', 'toml': '.toml', 'ini': '.ini',
'markdown': '.md',
}
# Configuration loading functions
def _find_pddrc_file(start_path: Optional[Path] = None) -> Optional[Path]:
"""Find .pddrc file by searching upward from the given path."""
if start_path is None:
start_path = Path.cwd()
# Search upward through parent directories
for path in [start_path] + list(start_path.parents):
pddrc_file = path / ".pddrc"
if pddrc_file.is_file():
return pddrc_file
return None
def _find_nearest_pddrc_for_file(
file_path: Path,
stop_at: Optional[Path] = None,
) -> Tuple[Optional[Path], Optional[Path]]:
"""Find the nearest .pddrc to a file, searching upward from its directory.
Returns (pddrc_path, effective_root) where effective_root is the
directory containing the .pddrc. Returns (None, None) if not found.
"""
start = file_path.parent if file_path.is_file() else file_path
stop_at_resolved = stop_at.resolve() if stop_at else None
for path in [start] + list(start.parents):
pddrc_file = path / ".pddrc"
if pddrc_file.is_file():
return pddrc_file, path
if stop_at_resolved and path.resolve() == stop_at_resolved:
break
return None, None
# Schema for .pddrc validation — see issue #1198.
# Unknown keys at any level emit a UserWarning rather than being silently ignored.
_PDDRC_ROOT_KEYS = {"version", "contexts", "checkup", "ci"}
_PDDRC_CHECKUP_KEYS = {"prompt_gate"}
_PDDRC_CI_KEYS = {"external_setup_fail_open", "manual_trigger_comment", "manual_triggers"}
_PDDRC_CONTEXT_KEYS = {"paths", "defaults"}
_PDDRC_DEFAULTS_KEYS = {
"generate_output_path",
"test_output_path",
"example_output_path",
"prompts_dir",
"default_language",
"target_coverage",
"strength",
"temperature",
"budget",
"max_attempts",
"compressed_context",
"outputs",
"auto_deps_csv_path",
"context_compression",
"compress_examples",
"compress_test_context",
"compression_fallback",
"test_token_budget",
"test_ranking_weights",
"test_dedup_threshold",
}
def _warn_unknown_pddrc_key(key: str, path: str) -> None:
"""Emit the standard unknown-key warning for .pddrc (issue #1198)."""
warnings.warn(
f"WARNING: .pddrc contains unknown key '{key}' at path '{path}', ignored. "
f"Run 'pdd setup' to regenerate.",
UserWarning,
stacklevel=3,
)
def _validate_pddrc_keys(config: Dict[str, Any]) -> None:
"""Validate that .pddrc contains only known keys.
Emits a UserWarning for each unknown key at the root, context, or
defaults levels. Does not raise; unknown keys are ignored but reported
so users can catch typos and stale config (issue #1198).
"""
# Root level
for key in config.keys():
if key not in _PDDRC_ROOT_KEYS:
_warn_unknown_pddrc_key(key, key)
checkup = config.get("checkup", {})
if isinstance(checkup, dict):
for key in checkup.keys():
if key not in _PDDRC_CHECKUP_KEYS:
_warn_unknown_pddrc_key(key, f"checkup.{key}")
ci_config = config.get("ci", {})
if isinstance(ci_config, dict):
for key in ci_config.keys():
if key not in _PDDRC_CI_KEYS:
_warn_unknown_pddrc_key(key, f"ci.{key}")
contexts = config.get("contexts", {})
if not isinstance(contexts, dict):
return
for ctx_name, ctx_config in contexts.items():
if not isinstance(ctx_config, dict):
continue
# Context level
for key in ctx_config.keys():
if key not in _PDDRC_CONTEXT_KEYS:
_warn_unknown_pddrc_key(key, f"contexts.{ctx_name}.{key}")
# Defaults level
defaults = ctx_config.get("defaults", {})
if isinstance(defaults, dict):
for key in defaults.keys():
if key not in _PDDRC_DEFAULTS_KEYS:
_warn_unknown_pddrc_key(
key, f"contexts.{ctx_name}.defaults.{key}"
)
def _load_pddrc_config(pddrc_path: Path) -> Dict[str, Any]:
"""Load and parse .pddrc configuration file."""
try:
with open(pddrc_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
if not isinstance(config, dict):
raise ValueError(f"Invalid .pddrc format: expected dictionary at root level")
# Validate basic structure
if 'contexts' not in config:
raise ValueError(f"Invalid .pddrc format: missing 'contexts' section")
_validate_pddrc_keys(config)
return config
except yaml.YAMLError as e:
raise ValueError(f"YAML syntax error in .pddrc: {e}")
except Exception as e:
raise ValueError(f"Error loading .pddrc: {e}")
def list_available_contexts(start_path: Optional[Path] = None) -> list[str]:
"""Return sorted context names from the nearest .pddrc.
- Searches upward from `start_path` (or CWD) for a `.pddrc` file.
- If found, loads and validates it, then returns sorted context names.
- If no `.pddrc` exists, returns ["default"].
- Propagates ValueError for malformed `.pddrc` to allow callers to render
helpful errors.
"""
pddrc = _find_pddrc_file(start_path)
if not pddrc:
return ["default"]
config = _load_pddrc_config(pddrc)
contexts = config.get("contexts", {})
names = sorted(contexts.keys()) if isinstance(contexts, dict) else []
return names or ["default"]
def _match_path_to_contexts(
path_str: str,
contexts: Dict[str, Any],
use_specificity: bool = False,
is_absolute: bool = False
) -> Optional[str]:
"""
Core pattern matching logic - matches a path against context patterns.
Args:
path_str: Path to match (can be relative or absolute)
contexts: The contexts dict from .pddrc config
use_specificity: If True, return most specific match; else first match
is_absolute: If True, use absolute path matching with "*/" prefix
Returns:
Context name or None
"""
matches = []
for context_name, context_config in contexts.items():
if context_name == 'default':
continue
for path_pattern in context_config.get('paths', []):
pattern_base = path_pattern.rstrip('/**').rstrip('/*')
# Check for match - handle both absolute and relative paths
matched = False
if is_absolute:
# For absolute paths (CWD-based detection), use existing logic
if fnmatch.fnmatch(path_str, f"*/{path_pattern}") or \
fnmatch.fnmatch(path_str, path_pattern) or \
path_str.endswith(f"/{pattern_base}"):
matched = True
else:
# For relative paths (file-based detection)
if fnmatch.fnmatch(path_str, path_pattern) or \
path_str.startswith(pattern_base + '/') or \
path_str.startswith(pattern_base):
matched = True
if matched:
if not use_specificity:
return context_name # First match wins
matches.append((context_name, len(pattern_base)))
if matches:
matches.sort(key=lambda x: x[1], reverse=True)
return matches[0][0]
return 'default' if 'default' in contexts else None
def _detect_context_from_basename(
basename: str,
config: Dict[str, Any],
pddrc_path: Optional[Path] = None,
) -> Optional[str]:
"""Detect context by matching a sync basename against prompts_dir prefixes or paths patterns.
When a context's ``prompts_dir`` ends at a ``prompts`` segment with a parent
(e.g. ``extensions/app/prompts``), the extracted prefix is empty — ``pdd sync``
basenames for that context are naturally relative to the extension's
``prompts_dir``. Such contexts are skipped by prefix-matching and typically
also by path-pattern matching; when no syntactic match succeeds the filesystem
is checked for the expected prompt file (Issue #1165).
Args:
pddrc_path: Path to the ``.pddrc`` whose ``config`` was loaded. Used to
resolve relative ``prompts_dir`` paths during the filesystem fallback.
When omitted, falls back to ``_find_pddrc_file()`` (cwd-based search).
"""
if not basename:
return None
contexts = config.get('contexts', {})
matches = []
# Contexts whose prompts_dir is nested (e.g. extensions/app/prompts) and
# produces an empty prefix — deferred for filesystem disambiguation.
nested_candidates: list = []
for context_name, context_config in contexts.items():
if context_name == 'default':
continue
defaults = context_config.get('defaults', {})
prompts_dir = defaults.get('prompts_dir', '')
if prompts_dir:
prefix = _extract_prefix_from_prompts_dir(prompts_dir)
if prefix and (basename == prefix or basename.startswith(prefix + '/')):
matches.append((context_name, len(prefix)))
continue
# Empty prefix with a nested prompts_dir (parent segments before
# "prompts") — defer to filesystem disambiguation below.
if not prefix:
parts = prompts_dir.rstrip('/').split('/')
if len(parts) > 1 and parts[-1] == 'prompts':
nested_candidates.append((context_name, prompts_dir))
for path_pattern in context_config.get('paths', []):
pattern_base = path_pattern.rstrip('/**').rstrip('/*')
if fnmatch.fnmatch(basename, path_pattern) or \
basename.startswith(pattern_base + '/') or \
basename == pattern_base:
matches.append((context_name, len(pattern_base)))
# Filesystem disambiguation for nested prompts_dir contexts whose basename
# didn't match syntactically. Uses a direct glob (not rglob) to avoid
# walking deep trees.
if not matches and nested_candidates:
resolved_pddrc = pddrc_path or _find_pddrc_file()
if resolved_pddrc:
pddrc_parent = resolved_pddrc.parent
if '/' in basename:
dir_part, name_part = basename.rsplit('/', 1)
else:
dir_part, name_part = '', basename
for context_name, prompts_dir in nested_candidates:
candidate_dir = pddrc_parent / prompts_dir
if dir_part:
candidate_dir = candidate_dir / dir_part
if candidate_dir.is_dir() and \
any(candidate_dir.glob(f"{glob.escape(name_part)}_*.prompt")):
matches.append((context_name, len(prompts_dir)))
if not matches:
return None
matches.sort(key=lambda item: item[1], reverse=True)
return matches[0][0]
def _get_relative_basename(input_path: str, pattern: str) -> str:
"""
Compute basename relative to the matched pattern base.
This is critical for Issue #237: when a context pattern like
'frontend/components/**' matches 'frontend/components/marketplace/AssetCard',
we need to return 'marketplace/AssetCard' (relative to pattern base),
not the full path which would cause double-pathing in output.
Args:
input_path: The full input path (e.g., 'frontend/components/marketplace/AssetCard')
pattern: The matching pattern (e.g., 'frontend/components/**')
Returns:
Path relative to the pattern base (e.g., 'marketplace/AssetCard')
Examples:
>>> _get_relative_basename('frontend/components/marketplace/AssetCard', 'frontend/components/**')
'marketplace/AssetCard'
>>> _get_relative_basename('backend/utils/credit_helpers', 'backend/utils/**')
'credit_helpers'
>>> _get_relative_basename('unknown/path', 'other/**')
'unknown/path' # No match, return as-is
"""
# Strip glob patterns to get the base directory
pattern_base = pattern.rstrip('/**').rstrip('/*').rstrip('*')
# Remove trailing slash from pattern base if present
pattern_base = pattern_base.rstrip('/')
# Check if input path starts with pattern base
if input_path.startswith(pattern_base + '/'):
# Return the portion after pattern_base/
return input_path[len(pattern_base) + 1:]
elif input_path.startswith(pattern_base) and len(input_path) > len(pattern_base):
# Handle case where pattern_base has no trailing content
remainder = input_path[len(pattern_base):]
if remainder.startswith('/'):
return remainder[1:]
return remainder
elif input_path == pattern_base:
# Exact match - return just the last component
return input_path.split('/')[-1] if '/' in input_path else input_path
# No match - return as-is (fallback for default context)
return input_path
def _detect_context(current_dir: Path, config: Dict[str, Any], context_override: Optional[str] = None) -> Optional[str]:
"""Detect the appropriate context based on current directory path."""
if context_override:
# Validate that the override context exists
contexts = config.get('contexts', {})
if context_override not in contexts:
available = list(contexts.keys())
raise ValueError(f"Unknown context '{context_override}'. Available contexts: {available}")
return context_override
contexts = config.get('contexts', {})
return _match_path_to_contexts(str(current_dir), contexts, use_specificity=False, is_absolute=True)
def detect_context_for_file(file_path: str, repo_root: Optional[str] = None) -> Tuple[Optional[str], Dict[str, Any]]:
"""
Detect the appropriate context for a file path based on .pddrc configuration.
This function finds the most specific matching context by comparing pattern lengths.
For example, 'backend/functions/utils/**' is more specific than 'backend/**'.
Args:
file_path: Path to the file (can be absolute or relative)
repo_root: Optional repository root path. If not provided, will be detected.
Returns:
Tuple of (context_name, context_config_defaults) or (None, {}) if no match.
"""
# Find repo root if not provided
if repo_root is None:
pddrc_path = _find_pddrc_file(Path(file_path).parent)
if pddrc_path:
repo_root = str(pddrc_path.parent)
else:
try:
import git
repo = git.Repo(file_path, search_parent_directories=True)
repo_root = repo.working_tree_dir
except:
repo_root = os.getcwd()
# Make file_path relative to repo_root for matching
file_path_abs = os.path.abspath(file_path)
repo_root_abs = os.path.abspath(repo_root)
if file_path_abs.startswith(repo_root_abs):
relative_path = os.path.relpath(file_path_abs, repo_root_abs)
else:
relative_path = file_path
# Find and load .pddrc — when repo_root was explicitly provided, prefer
# the .pddrc at that location (the caller already resolved the nearest one).
# Only fall back to searching from the file when repo_root was auto-detected.
pddrc_path = None
repo_root_pddrc = Path(repo_root) / ".pddrc"
if repo_root_pddrc.is_file():
pddrc_path = repo_root_pddrc
if not pddrc_path:
pddrc_path = _find_pddrc_file(Path(file_path).parent)
# If the .pddrc lives in a directory different from repo_root, recalculate
# repo_root_abs and relative_path so context matching works correctly
if pddrc_path:
pddrc_root_abs = os.path.abspath(str(pddrc_path.parent))
if file_path_abs.startswith(pddrc_root_abs + os.sep) or file_path_abs == pddrc_root_abs:
repo_root_abs = pddrc_root_abs
relative_path = os.path.relpath(file_path_abs, repo_root_abs)
if not pddrc_path:
return None, {}
try:
config = _load_pddrc_config(pddrc_path)
except ValueError:
return None, {}
contexts = config.get('contexts', {})
# First, try to match against prompts_dir for each context
# This allows prompt files to be detected even when paths pattern only matches code files
prompts_dir_matches = []
for context_name, context_config in contexts.items():
if context_name == 'default':
continue
prompts_dir = context_config.get('defaults', {}).get('prompts_dir', '')
if prompts_dir:
prompts_dir_normalized = prompts_dir.rstrip('/')
if relative_path.startswith(prompts_dir_normalized + '/') or relative_path == prompts_dir_normalized:
# Track match with specificity (length of prompts_dir)
prompts_dir_matches.append((context_name, len(prompts_dir_normalized)))
# Return most specific prompts_dir match if any
if prompts_dir_matches:
prompts_dir_matches.sort(key=lambda x: x[1], reverse=True)
matched_context = prompts_dir_matches[0][0]
return matched_context, _get_context_config(config, matched_context)
# Fall back to existing paths pattern matching
context_name = _match_path_to_contexts(relative_path, contexts, use_specificity=True, is_absolute=False)
return context_name, _get_context_config(config, context_name)
def _get_context_config(config: Dict[str, Any], context_name: Optional[str]) -> Dict[str, Any]:
"""Get configuration settings for the specified context."""
if not context_name:
return {}
contexts = config.get('contexts', {})
context_config = contexts.get(context_name, {})
return context_config.get('defaults', {})
def _resolve_config_hierarchy(
cli_options: Dict[str, Any],
context_config: Dict[str, Any],
env_vars: Dict[str, str]
) -> Dict[str, Any]:
"""Apply configuration hierarchy: CLI > context > environment > defaults."""
resolved = {}
# Configuration keys to resolve
config_keys = {
'generate_output_path': 'PDD_GENERATE_OUTPUT_PATH',
'test_output_path': 'PDD_TEST_OUTPUT_PATH',
'example_output_path': 'PDD_EXAMPLE_OUTPUT_PATH',
'prompts_dir': 'PDD_PROMPTS_DIR',
'default_language': 'PDD_DEFAULT_LANGUAGE',
'target_coverage': 'PDD_TEST_COVERAGE_TARGET',
'strength': None,
'temperature': None,
'budget': None,
'max_attempts': None,
'auto_deps_csv_path': 'PDD_AUTO_DEPS_CSV_PATH',
'context_compression': 'PDD_CONTEXT_COMPRESSION',
'compress_examples': 'PDD_COMPRESS_EXAMPLES',
'compress_test_context': 'PDD_COMPRESS_TEST_CONTEXT',
'compression_fallback': 'PDD_COMPRESSION_FALLBACK',
'test_token_budget': 'PDD_TEST_TOKEN_BUDGET',
'test_ranking_weights': 'PDD_TEST_RANKING_WEIGHTS',
'test_dedup_threshold': 'PDD_TEST_DEDUP_THRESHOLD',
}
for config_key, env_var in config_keys.items():
# 1. CLI options (highest priority)
if config_key in cli_options and cli_options[config_key] is not None:
resolved[config_key] = cli_options[config_key]
# 2. Context configuration
elif config_key in context_config:
resolved[config_key] = context_config[config_key]
# 3. Environment variables
elif env_var and env_var in env_vars:
resolved[config_key] = env_vars[env_var]
# 4. Defaults are handled elsewhere
# Issue #237: Pass through 'outputs' config for template-based path generation
# This enables extensible project layouts (Next.js, Vue, Python, Go, etc.)
if 'outputs' in context_config:
resolved['outputs'] = context_config['outputs']
return resolved
# New helper for reporting effective config/context exactly as construct_paths would
def resolve_effective_config(
*,
cli_options: Optional[Dict[str, Any]] = None,
context_override: Optional[str] = None,
cwd: Optional[Path] = None,
prompt_file: Optional[str] = None,
basename_hint: Optional[str] = None,
quiet: bool = False,
) -> Tuple[Optional[str], Optional[Path], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
"""Resolve the effective configuration and context exactly as `construct_paths` would.
This is intended for commands like `pdd which` that need to report how PDD would
resolve context and config without performing path construction.
Resolution order mirrors `construct_paths`:
- Find nearest `.pddrc` (searching upward from `cwd` or CWD)
- Load `.pddrc`
- Detect context (override > prompt_file > basename_hint > cwd)
- Read context defaults
- Apply hierarchy (CLI > context > environment > defaults)
Returns:
(context, pddrc_path, context_config, resolved_config, original_context_config)
"""
cli_options = cli_options or {}
cwd = cwd or Path.cwd()
pddrc_path: Optional[Path] = None
pddrc_config: Dict[str, Any] = {}
context: Optional[str] = None
context_config: Dict[str, Any] = {}
original_context_config: Dict[str, Any] = {}
# Find and load .pddrc (if any)
pddrc_path = _find_pddrc_file(cwd)
if not pddrc_path:
# No .pddrc: context stays None; resolved config is CLI-only (env/defaults handled elsewhere)
env_vars = dict(os.environ)
resolved_config = _resolve_config_hierarchy(cli_options, {}, env_vars)
resolved_config["_matched_context"] = "none"
return None, None, {}, resolved_config, {}
pddrc_config = _load_pddrc_config(pddrc_path)
# Detect appropriate context
if context_override:
# Delegate validation to _detect_context to avoid duplicate validation logic
context = _detect_context(cwd, pddrc_config, context_override)
else:
# Prefer file-based detection when a prompt file is provided
if prompt_file and Path(prompt_file).exists():
detected_context, _ = detect_context_for_file(prompt_file)
if detected_context:
context = detected_context
else:
context = _detect_context(cwd, pddrc_config, None)
elif basename_hint:
detected_context = _detect_context_from_basename(basename_hint, pddrc_config, pddrc_path=pddrc_path)
if detected_context:
context = detected_context
else:
context = _detect_context(cwd, pddrc_config, None)
else:
context = _detect_context(cwd, pddrc_config, None)
context_config = _get_context_config(pddrc_config, context)
original_context_config = context_config.copy()
if (not quiet) and context:
console.print(f"[info]Using .pddrc context:[/info] {context}")
env_vars = dict(os.environ)
resolved_config = _resolve_config_hierarchy(cli_options, context_config, env_vars)
resolved_config["_matched_context"] = context or "default"
return context, pddrc_path, context_config, resolved_config, original_context_config
def get_tests_dir_from_config(start_path: Optional[Path] = None) -> Optional[Path]:
"""
Get the tests directory from .pddrc configuration.
Searches for .pddrc, detects the appropriate context, and returns the
configured test_output_path as a Path object.
Args:
start_path: Starting directory for .pddrc search. Defaults to CWD.
Returns:
Path to tests directory if configured, None otherwise.
"""
if start_path is None:
start_path = Path.cwd()
# Find and load .pddrc
pddrc_path = _find_pddrc_file(start_path)
if not pddrc_path:
return None
try:
config = _load_pddrc_config(pddrc_path)
except ValueError:
return None
# Detect context and get its config
context_name = _detect_context(start_path, config)
context_config = _get_context_config(config, context_name)
# Check context config first, then env var
test_output_path = context_config.get('test_output_path')
if not test_output_path:
test_output_path = os.environ.get('PDD_TEST_OUTPUT_PATH')
if test_output_path:
return Path(test_output_path)
return None
def _read_file(path: Path) -> str:
"""Read a text file safely and return its contents."""
try:
return path.read_text(encoding="utf-8")
except Exception as exc: # pragma: no cover
# Error is raised in the main function after this fails
console.print(f"[error]Could not read {path}: {exc}", style="error")
raise
def _ensure_error_file(path: Path, quiet: bool) -> None:
"""Create an empty error log file if it doesn't exist."""
if not path.exists():
if not quiet:
# Use console.print from the main module scope
# Print without Rich tags for easier testing
console.print(f"Warning: Error file '{path.resolve()}' does not exist. Creating an empty file.", style="warning")
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.touch()
except Exception as exc: # pragma: no cover
console.print(f"[error]Could not create error file {path}: {exc}", style="error")
raise
def _candidate_prompt_path(input_files: Dict[str, Path]) -> Path | None:
"""Return the path most likely to be the prompt file, if any."""
# Prioritize specific keys known to hold the primary prompt
for key in (
"prompt_file", # generate, test, fix, crash, trace, verify, auto-deps
"input_prompt", # split
"input_prompt_file", # update, change (non-csv), bug
"prompt1", # conflicts
# Less common / potentially ambiguous keys last
"change_prompt_file", # change (specific case handled in _extract_basename)
):
if key in input_files:
return input_files[key]
# Fallback: first file with a .prompt extension if no specific key matches
for p in input_files.values():
if p.suffix == ".prompt":
return p
# Final fallback: Return the first file path available (e.g. for pdd update <code_file>)
if input_files:
return next(iter(input_files.values()))
return None
# New helper function to check if a language is known
def _is_known_language(language_name: str) -> bool:
"""Return True if the language is recognized.
Resolve only through the package-bundled protected language registry.
"""
language_name_lower = (language_name or "").lower()
if not language_name_lower:
return False
from pdd.sync_core.language import LanguageRegistry, LanguageRegistryError
try:
LanguageRegistry.bundled().resolve_alias(language_name_lower)
except LanguageRegistryError:
return False
return True
# Languages that only produce a code output (no test/example).
# Config, data, markup, and non-executable formats.
_CODE_ONLY_LANGUAGES = {
'json', 'jsonl', 'yaml', 'yml', 'toml', 'ini', 'csv',
'xml', 'html', 'css', 'scss', 'sass', 'less',
'markdown', 'latex', 'log', 'restructuredtext', 'text',
'sql', 'graphql', 'protobuf',
'makefile', 'dockerfile',
'terraform', 'hcl', 'nix', 'starlark',
'glsl', 'wgsl',
'prisma',
}
def get_language_outputs(language_name: str) -> set[str]:
"""Return the set of expected output types for a given language.
Executable/programmable languages produce {'code', 'test', 'example'}.
Config/data/markup languages produce {'code'} only.
Unknown languages default to {'code', 'test', 'example'}.
Uses the ``outputs`` column from ``language_format.csv`` when available,
falling back to the built-in ``_CODE_ONLY_LANGUAGES`` set.
"""
language_lower = (language_name or '').lower()
if not language_lower:
return {'code', 'test', 'example'}
# Try CSV first (has an 'outputs' column after Step 2)
pdd_path_str = os.getenv('PDD_PATH')
if pdd_path_str:
csv_file_path = Path(pdd_path_str) / 'data' / 'language_format.csv'
if csv_file_path.is_file():
try:
with open(csv_file_path, mode='r', encoding='utf-8', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row.get('language', '').lower() == language_lower:
outputs_val = row.get('outputs', '').strip()
if outputs_val:
return set(outputs_val.split('|'))
# Column exists but empty – fall through to built-in
break
except csv.Error:
pass
# Built-in fallback
if language_lower in _CODE_ONLY_LANGUAGES:
return {'code'}
if _is_known_language(language_lower):
return {'code', 'test', 'example'}
# Unknown language – assume full outputs
return {'code', 'test', 'example'}
def _strip_language_suffix(path_like: os.PathLike[str]) -> str:
"""
Remove trailing '_<language>' from a filename stem if it matches a known language.
"""
p = Path(path_like)
stem = p.stem # removes last extension (e.g., '.prompt', '.py')
if "_" not in stem:
return stem
parts = stem.split("_")
candidate_lang = parts[-1]
if _is_known_language(candidate_lang):
# Do not strip '_prompt' from a non-.prompt file (e.g., 'test_prompt.txt')
if candidate_lang == 'prompt' and p.suffix != '.prompt':
return stem
return "_".join(parts[:-1])
return stem
def _strip_language_suffix_with_subdir(
prompt_path: Path,
prompts_dir: Optional[str] = None,
) -> str:
"""Strip language suffix from a prompt path, preserving subdirectory components.
For nested prompts like ``prompts/commands/fix_python.prompt``, the
subdirectory relative to the configured prompts root is part of the
basename. When ``prompts_dir`` is supplied (typically from .pddrc), its
path segments are used as the anchor so a configured prompts root of
e.g. ``prompts/backend`` is treated as the root rather than the literal
``prompts`` segment. Falls back to the literal ``prompts/`` anchor when
``prompts_dir`` is not supplied or doesn't match the path.
"""
stripped_name = _strip_language_suffix(prompt_path)
parts = prompt_path.parts
if prompts_dir:
normalized = str(prompts_dir).replace('\\', '/').rstrip('/')
dir_parts = tuple(p for p in normalized.split('/') if p and p != '.')
if dir_parts:
for start in range(len(parts) - len(dir_parts), -1, -1):
if start < 0:
break
if tuple(parts[start:start + len(dir_parts)]) == dir_parts:
anchor_end = start + len(dir_parts)
subdir_parts = parts[anchor_end:-1]
if subdir_parts:
return str(Path(*subdir_parts) / stripped_name)
return stripped_name
# Fall back to anchoring on the literal "prompts" segment
try:
prompts_idx = len(parts) - 1 - list(reversed(parts)).index("prompts")
except ValueError:
# No "prompts" directory in path — check for subdirectory parent
# that isn't a filesystem root (e.g. "commands/fix_python.prompt")
parent = prompt_path.parent
if parent != Path(".") and not parent.is_absolute():
return str(parent / stripped_name)
return stripped_name
# Everything between prompts/ and the filename is the subdir prefix
subdir_parts = parts[prompts_idx + 1 : -1]
if subdir_parts:
return str(Path(*subdir_parts) / stripped_name)
return stripped_name
def _extract_basename(
command: str,
input_file_paths: Dict[str, Path],
prompts_dir: Optional[str] = None,
) -> str:
"""
Deduce the project basename according to the rules explained in *Step A*.
"""
# Handle 'fix' command specifically to create a unique basename per test file
if command == "fix":
prompt_path = _candidate_prompt_path(input_file_paths)
if not prompt_path:
raise ValueError("Could not determine prompt file for 'fix' command.")
prompt_basename = _strip_language_suffix_with_subdir(prompt_path, prompts_dir)
unit_test_path = input_file_paths.get("unit_test_file")
if not unit_test_path:
# Fallback to just the prompt basename if no unit test file is provided
# This might happen in some edge cases, but 'fix' command structure requires it
return prompt_basename
# Use the stem of the unit test file to make the basename unique
test_basename = Path(unit_test_path).stem
return f"{prompt_basename}_{test_basename}"
# Handle conflicts first due to its unique structure
if command == "conflicts":
key1 = "prompt1"
key2 = "prompt2"
# Ensure keys exist before proceeding
if key1 in input_file_paths and key2 in input_file_paths:
p1 = Path(input_file_paths[key1])
p2 = Path(input_file_paths[key2])
base1 = _strip_language_suffix(p1)
base2 = _strip_language_suffix(p2)
# Combine basenames, ensure order for consistency (sorted)
return "_".join(sorted([base1, base2]))
# else: Fall through might occur if keys missing, handled by general logic/fallback
# Special‑case commands that choose a non‑prompt file for the basename
elif command == "detect":
key = "change_file"
if key in input_file_paths:
# Basename is from change_file, no language suffix stripping needed usually
return Path(input_file_paths[key]).stem
elif command == "change":
# If change_prompt_file is given, use its stem (no language strip needed per convention)
if "change_prompt_file" in input_file_paths:
return Path(input_file_paths["change_prompt_file"]).stem
# If --csv is used or change_prompt_file is absent, fall through to general logic
pass
# General case: Use the primary prompt file
prompt_path = _candidate_prompt_path(input_file_paths)
if prompt_path:
return _strip_language_suffix_with_subdir(prompt_path, prompts_dir)
# Fallback: If no prompt found (e.g., command only takes code files?),
# use the first input file's stem. This requires input_file_paths not to be empty.
# This fallback is reached only if input_file_paths is not empty (checked earlier)
first_path = next(iter(input_file_paths.values()))
# Should we strip language here too? Let's be consistent.
return _strip_language_suffix(first_path)
def _determine_language(
command_options: Dict[str, Any], # Keep original type hint
input_file_paths: Dict[str, Path],
command: str = "", # New parameter for the command name
) -> str:
"""
Apply the language discovery strategy.
Priority: Explicit option > Code/Test file extension > Prompt filename suffix.
For 'detect' command, default to 'prompt' as it typically doesn't need a language.
"""
# Diagnostic check for None (should be handled by caller, but for safety)
command_options = command_options or {}
# 1 – explicit option
explicit_lang = command_options.get("language")
if explicit_lang:
lang_lower = explicit_lang.lower()
# Optional: Validate known language? Let's assume valid for now.
return lang_lower
# 2 – infer from extension of any code/test file (excluding .prompt)
# Iterate through values, ensuring consistent order if needed (e.g., sort keys)
# For now, rely on dict order (Python 3.7+)
for key, p in input_file_paths.items():
path_obj = Path(p)
ext = path_obj.suffix
# Prioritize non-prompt code files
if ext and ext != ".prompt":
try:
language = get_language(ext)
if language:
return language.lower()
except ValueError:
# Fallback: load language CSV file directly when PDD_PATH is not set
try:
import csv
import os
# Try to find the CSV file relative to this script
script_dir = os.path.dirname(os.path.abspath(__file__))
csv_path = os.path.join(script_dir, 'data', 'language_format.csv')
if os.path.exists(csv_path):
with open(csv_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row['extension'].lower() == ext.lower():
return row['language'].lower()
except (FileNotFoundError, csv.Error):
pass
# Handle files without extension like Makefile
elif not ext and path_obj.is_file(): # Check it's actually a file
try:
language = get_language(path_obj.name) # Check name (e.g., 'Makefile')
if language:
return language.lower()
except ValueError:
# Fallback: load language CSV file directly for files without extension
try:
import csv
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
csv_path = os.path.join(script_dir, 'data', 'language_format.csv')
if os.path.exists(csv_path):
with open(csv_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Check if the filename matches (for files without extension)
if not row['extension'] and path_obj.name.lower() == row['language'].lower():
return row['language'].lower()
except (FileNotFoundError, csv.Error):
pass
# 3 – parse from prompt filename suffix
prompt_path = _candidate_prompt_path(input_file_paths)
if prompt_path and prompt_path.suffix == ".prompt":
stem = prompt_path.stem
if "_" in stem:
parts = stem.split("_")
if len(parts) >= 2:
token = parts[-1]
# Check if the token is a known language using the new helper
if _is_known_language(token):
return token.lower()
# 4 - Special handling for detect command - default to prompt for LLM prompts
if command == "detect" and "change_file" in input_file_paths:
return "prompt"
# 5 - If no language determined, raise error
raise ValueError("Could not determine language from input files or options.")
def _paths_exist(paths: Dict[str, Path]) -> bool: # Value type is Path
"""Return True if any of the given paths is an existing file."""
# Check specifically for files, not directories
return any(p.is_file() for p in paths.values())
def construct_paths(
input_file_paths: Dict[str, str],
force: bool,
quiet: bool,
command: str,
command_options: Optional[Dict[str, Any]], # Allow None
create_error_file: bool = True, # Added parameter to control error file creation
context_override: Optional[str] = None, # Added parameter for context override
confirm_callback: Optional[Callable[[str, str], bool]] = None, # Callback for interactive confirmation
path_resolution_mode: Optional[str] = None, # "cwd" or "config_base" - if None, use command default
) -> Tuple[Dict[str, Any], Dict[str, str], Dict[str, str], str]:
"""
High‑level orchestrator that loads inputs, determines basename/language,
computes output locations, and verifies overwrite rules.
Supports .pddrc configuration with context-aware settings and configuration hierarchy:
CLI options > .pddrc context > environment variables > defaults
Returns
-------
(resolved_config, input_strings, output_file_paths, language)
"""
command_options = command_options or {} # Ensure command_options is a dict
# ------------- Load .pddrc configuration -----------------
pddrc_config = {}
pddrc_path: Optional[Path] = None
context = None
context_config = {}
original_context_config = {} # Keep track of original context config for sync discovery
try:
# Issue #1211: when invoked from a parent directory, prefer the .pddrc
# nearest the input prompt file — but only when that .pddrc is a
# descendant of the CWD-based one (i.e., a subproject within the same
# project tree). When the prompt comes from an unrelated tree (e.g. a
# fixture file), use the CWD-based .pddrc.
cwd_pddrc = _find_pddrc_file()
prompt_pddrc = None
if input_file_paths:
prompt_file_hint = input_file_paths.get("prompt_file")
if prompt_file_hint:
# _find_pddrc_file walks [start] + start.parents, so passing the
# prompt path directly resolves the same .pddrc whether the hint
# is a file or a directory — no explicit exists()/is_file() needed.
prompt_pddrc = _find_pddrc_file(Path(prompt_file_hint))
# Tracks whether we selected a subproject .pddrc that lives BELOW the run
# CWD. In that case relative output dirs must anchor at the subproject
# (config_base), not the CWD — otherwise sync/fix write outside it (#1211).
subproject_pddrc_below_cwd = False
if prompt_pddrc is None:
pddrc_path = cwd_pddrc
elif cwd_pddrc is None:
pddrc_path = prompt_pddrc
subproject_pddrc_below_cwd = True
else:
try:
prompt_pddrc.parent.resolve().relative_to(cwd_pddrc.parent.resolve())
pddrc_path = prompt_pddrc # descendant — more specific subproject
subproject_pddrc_below_cwd = prompt_pddrc != cwd_pddrc
except ValueError:
pddrc_path = cwd_pddrc # unrelated tree — keep local .pddrc
if pddrc_path:
pddrc_config = _load_pddrc_config(pddrc_path)
# Detect appropriate context
# Priority: context_override > file-based detection > CWD-based detection
if context_override:
# Delegate validation to _detect_context to avoid duplicate validation logic
context = _detect_context(Path.cwd(), pddrc_config, context_override)
else:
# Try file-based detection when prompt file is provided
prompt_file_str = input_file_paths.get('prompt_file') if input_file_paths else None
if prompt_file_str and Path(prompt_file_str).exists():
detected_context, _ = detect_context_for_file(prompt_file_str)
if detected_context:
context = detected_context
else:
context = _detect_context(Path.cwd(), pddrc_config, None)
else:
basename_hint = command_options.get("basename")
if basename_hint:
detected_context = _detect_context_from_basename(basename_hint, pddrc_config, pddrc_path=pddrc_path)
if detected_context:
context = detected_context
else:
context = _detect_context(Path.cwd(), pddrc_config, None)
else:
context = _detect_context(Path.cwd(), pddrc_config, None)
# Get context-specific configuration
context_config = _get_context_config(pddrc_config, context)
original_context_config = context_config.copy() # Store original before modifications
if not quiet and context:
console.print(f"[info]Using .pddrc context:[/info] {context}")
# Apply configuration hierarchy
env_vars = dict(os.environ)
resolved_config = _resolve_config_hierarchy(command_options, context_config, env_vars)
# Issue #237: Track matched context for debugging
resolved_config['_matched_context'] = context or 'default'
# Update command_options with resolved configuration for internal use
# Exclude internal metadata keys (prefixed with _) from command_options
for key, value in resolved_config.items():
if key.startswith('_'):
continue # Skip internal metadata like _matched_context
if key not in command_options or command_options[key] is None:
command_options[key] = value
# Also update context_config with resolved environment variables for generate_output_paths
# This ensures environment variables are available when context config doesn't override them
for key, value in resolved_config.items():
if (key.endswith('_output_path') or key == 'auto_deps_csv_path') and key not in context_config:
context_config[key] = value
from .config_resolution import apply_compression_env, effective_compression_config
apply_compression_env(effective_compression_config(resolved_config))
except Exception as e:
error_msg = f"Configuration error: {e}"
console.print(f"[error]{error_msg}[/error]", style="error")
if not quiet:
console.print("[warning]Continuing with default configuration...[/warning]", style="warning")
# Initialize resolved_config on error to avoid downstream issues
resolved_config = command_options.copy()
# ------------- Handle sync discovery mode ----------------
if command == "sync" and not input_file_paths:
basename = command_options.get("basename")
if not basename:
raise ValueError("Basename must be provided in command_options for sync discovery mode.")
# For discovery, we only need directory paths (via .parent) — the language
# and extension values here are irrelevant and never used for file output.
try:
output_paths_str = generate_output_paths(
command="sync",
output_locations={},
basename=basename,
language="python",
file_extension=".py",
context_config=context_config,
config_base_dir=str(pddrc_path.parent) if pddrc_path else None,
path_resolution_mode="cwd", # Sync resolves paths relative to CWD
)
# Infer base directories from a sample output path
gen_path = Path(output_paths_str.get("generate_output_path", "src"))
# Only infer prompts_dir if it wasn't provided via CLI/.pddrc/env
if not resolved_config.get("prompts_dir"):
# First, check current working directory for prompt files matching the basename pattern
current_dir = Path.cwd()
prompt_pattern = f"{glob.escape(basename)}_*.prompt"
if list(current_dir.glob(prompt_pattern)):
# Found prompt files in current working directory
resolved_config["prompts_dir"] = str(current_dir)
resolved_config["code_dir"] = str(current_dir)
if not quiet:
console.print(f"[info]Found prompt files in current directory:[/info] {current_dir}")
else:
# Fall back to context-aware logic
# Use original_context_config to avoid checking augmented config with env vars
if original_context_config and (
'prompts_dir' in original_context_config or
any(key.endswith('_output_path') for key in original_context_config)
):
# For configured contexts, use prompts_dir from config if provided,
# otherwise default to "prompts" at the same level as output dirs
resolved_config["prompts_dir"] = original_context_config.get("prompts_dir", "prompts")
resolved_config["code_dir"] = str(gen_path.parent)
else:
# For default contexts, maintain relative relationship
# e.g., if code goes to "pi.py", prompts should be at "prompts/" (siblings)
resolved_config["prompts_dir"] = str(gen_path.parent / "prompts")
resolved_config["code_dir"] = str(gen_path.parent)
# Ensure code_dir is always set (even if prompts_dir was already configured via CLI/env)
if "code_dir" not in resolved_config:
resolved_config["code_dir"] = str(gen_path.parent)
resolved_config["tests_dir"] = str(Path(output_paths_str.get("test_output_path", "tests")).parent)
# Determine examples_dir for auto-deps scanning
# NOTE: outputs.example.path is for OUTPUT only (where to write examples),
# NOT for determining scan scope. Using it caused CSV row deletion issues.
# Do NOT use output_paths_str since generate_output_paths always returns absolute paths.
example_path_str = None
if original_context_config:
example_path_str = original_context_config.get("example_output_path")
# Default via the SSOT helper (handles greenfield + legacy context/).
if not example_path_str:
example_path_str = _resolve_default_examples_dir(
_default_examples_project_root(pddrc_path)
)
# Extract ROOT directory (first component) for scan scope
# e.g., "context/commands/" -> "context", "examples/foo.py" -> "examples"
# Fix for Issue #332: Using full subdirectory path caused CSV truncation
example_path = Path(example_path_str)
parts = example_path.parts
if parts and parts[0] not in ('/', '.', '..'):
resolved_config["examples_dir"] = parts[0]
else:
resolved_config["examples_dir"] = _resolve_default_examples_dir(
_default_examples_project_root(pddrc_path)
)
except Exception as e:
console.print(f"[error]Failed to determine initial paths for sync: {e}", style="error")
raise
# Return early for discovery mode
return resolved_config, {}, {}, ""
if not input_file_paths:
raise ValueError("No input files provided")
# ------------- normalise & resolve Paths -----------------
input_paths: Dict[str, Path] = {}
for key, path_str in input_file_paths.items():
try:
path = Path(path_str).expanduser()
# Resolve non-error files strictly first, but be more lenient for sync command
if key != "error_file":
# For sync command, be more tolerant of non-existent files since we're just determining paths
if command == "sync":
input_paths[key] = path.resolve()
else:
# Let FileNotFoundError propagate naturally if path doesn't exist
resolved_path = path.resolve(strict=True)
input_paths[key] = resolved_path
else:
# Resolve error file non-strictly, existence checked later
input_paths[key] = path.resolve()
except FileNotFoundError as e:
# Re-raise standard FileNotFoundError, tests will check path within it
raise e
except Exception as exc: # Catch other potential path errors like permission issues
console.print(f"[error]Invalid path provided for {key}: '{path_str}' - {exc}", style="error")
raise # Re-raise other exceptions
# ------------- Step 1: load input files ------------------
input_strings: Dict[str, str] = {}
for key, path in input_paths.items():
if key == "error_file":
if create_error_file:
_ensure_error_file(path, quiet) # Pass quiet flag
# Ensure path exists before trying to read
if not path.exists():
# _ensure_error_file should have created it, but check again
# If it still doesn't exist, something went wrong
raise FileNotFoundError(f"Error file '{path}' could not be created or found.")
else:
# When create_error_file is False, error out if the file doesn't exist
if not path.exists():
raise FileNotFoundError(f"Error file '{path}' does not exist.")
# Check existence again, especially for error_file which might have been created
if not path.exists():
# For sync command, be more tolerant of non-existent files since we're just determining paths
if command == "sync":
# Skip reading content for non-existent files in sync mode
continue
else:
# This case should ideally be caught by resolve(strict=True) earlier for non-error files
# Raise standard FileNotFoundError
raise FileNotFoundError(f"{path}")
if path.is_file(): # Read only if it's a file
try:
input_strings[key] = _read_file(path)
except Exception as exc:
# Re-raise exceptions during reading
raise IOError(f"Failed to read input file '{path}' (key='{key}'): {exc}") from exc
elif path.is_dir():
# Decide how to handle directories if they are passed unexpectedly
if not quiet:
console.print(f"[warning]Warning: Input path '{path}' for key '{key}' is a directory, not reading content.", style="warning")
# Store the path string or skip? Let's skip for input_strings.
# input_strings[key] = "" # Or None? Or skip? Skipping seems best.
# Handle other path types? (symlinks are resolved by resolve())
# ------------- Step 2: basename --------------------------
try:
# For sync, example, and test commands, prefer the basename from command_options if provided.
# This preserves subdirectory paths like 'core/cloud' which would otherwise
# be lost when extracting from the prompt file path.
if command in ("sync", "example", "test") and command_options.get("basename"):
basename = command_options["basename"]
else:
basename = _extract_basename(
command,
input_paths,
prompts_dir=resolved_config.get("prompts_dir"),
)
except ValueError as exc:
# Check if it's the specific error from the initial check (now done at start)
# This try/except might not be needed if initial check is robust
# Let's keep it simple for now and let initial check handle empty inputs
console.print(f"[error]Unable to extract basename: {exc}", style="error")
raise ValueError(f"Failed to determine basename: {exc}") from exc
except Exception as exc: # Catch other exceptions like potential StopIteration
console.print(f"[error]Unexpected error during basename extraction: {exc}", style="error")
raise ValueError(f"Failed to determine basename: {exc}") from exc
# ------------- Step 3: language & extension --------------
try:
# Pass the potentially updated command_options
language = _determine_language(command_options, input_paths, command)
# Add validation to ensure language is never None
if language is None:
# Try to extract language from the prompt filename suffix before
# falling back to Python. This prevents TypeScript/TSX modules
# (e.g. *_typescriptreact.prompt) from being mis-classified as
# Python when _determine_language fails to detect the language.
prompt_path = _candidate_prompt_path(input_paths)
if prompt_path and prompt_path.suffix == ".prompt":
stem = prompt_path.stem
if "_" in stem:
suffix_token = stem.rsplit("_", 1)[-1]
if _is_known_language(suffix_token):
language = suffix_token.lower()
# Final default when no prompt suffix could be extracted
if language is None:
language = 'python'
# Log the issue for debugging
if not quiet:
console.print(
f"[warning]Warning: Could not determine language for '{command}' command. "
f"Defaulting to '{language}'. Pass --language explicitly or ensure prompt "
f"filename ends with _<language>.prompt[/warning]",
style="warning"
)
except ValueError as e:
console.print(f"[error]{e}", style="error")
raise # Re-raise the ValueError from _determine_language
# Final safety check before calling get_extension
if not language or not isinstance(language, str):
language = 'python' # Absolute fallback
if not quiet:
console.print(
f"[warning]Warning: Invalid language value. Using default: {language}[/warning]",
style="warning"
)
# Try to get extension from CSV; fallback to built-in mapping if PDD_PATH/CSV unavailable
try:
file_extension = get_extension(language) # Pass determined language
if not file_extension and (language or '').lower() != 'prompt':
raise ValueError('empty extension')
except Exception:
# Offline fallback: read the same bundled language_format.csv that sync's
# get_extension uses, so generation's written extension stays aligned with
# the path sync expects when PDD_PATH is unset (issue #551). Only resort to
# BUILTIN_EXT_MAP for languages the bundled CSV does not list.
from pdd.language_extensions import bundled_extension
_bundled = bundled_extension(language)
if _bundled is not None:
file_extension = f".{_bundled}" if _bundled else ''
else:
file_extension = BUILTIN_EXT_MAP.get(language.lower(), f".{language.lower()}" if language else '')
# Handle --format option for commands that support it (e.g., example)
format_option = command_options.get("format")
if format_option and command == "example":
format_lower = format_option.lower()
if format_lower == "md":
file_extension = ".md"
elif format_lower == "code":
# Keep the language-based extension (file_extension already set above)
pass
else:
# This should not happen due to click.Choice validation, but handle it anyway
raise click.UsageError(f"Unknown format '{format_option}'. Valid values: code, md")
# ------------- Step 3b: build output paths ---------------
# Filter user‑provided output_* locations from CLI options
output_location_opts = {
k: v for k, v in command_options.items()
if (
k.startswith("output")
or (command == "auto-deps" and k == "csv")
) and v is not None # Ensure value is not None
}
# Determine input file directory for default output path generation
# Only apply for commands that generate/update files based on specific input files
# Commands like sync, generate, test, example have their own directory management
commands_using_input_dir = {'fix', 'crash', 'verify', 'split', 'change', 'update'}
input_file_dir: Optional[str] = None
input_file_dirs: Dict[str, Optional[str]] = {}
if input_paths and command in commands_using_input_dir:
try:
# For fix/crash/verify commands, use specific file directories for each output
if command in {'fix', 'crash', 'verify'}:
# Map output keys to their corresponding input file keys
input_key_map = {
'fix': {'output_code': 'code_file', 'output_test': 'unit_test_file', 'output_results': 'code_file'},
'crash': {'output': 'code_file', 'output_program': 'program_file'},
'verify': {'output_code': 'code_file', 'output_program': 'verification_program', 'output_results': 'code_file'},
}
for output_key, input_key in input_key_map.get(command, {}).items():
if input_key in input_paths:
input_file_dirs[output_key] = str(input_paths[input_key].parent)
# Set default input_file_dir to code_file directory as fallback
if 'code_file' in input_paths:
input_file_dir = str(input_paths['code_file'].parent)
else:
first_input_path = next(iter(input_paths.values()))
input_file_dir = str(first_input_path.parent)
else:
# For other commands, use first input path
first_input_path = next(iter(input_paths.values()))
input_file_dir = str(first_input_path.parent)
except (StopIteration, AttributeError):
# If no input paths or path doesn't have parent, use None (falls back to CWD)
pass
try:
# generate_output_paths might return Dict[str, str] or Dict[str, Path]
# Let's assume it returns Dict[str, str] based on verification error,
# and convert them to Path objects here.
# Determine path resolution mode:
# - If explicitly provided, use it
# - Otherwise: sync uses "cwd", other commands use "config_base"
effective_path_resolution_mode = path_resolution_mode
if effective_path_resolution_mode is None:
effective_path_resolution_mode = "cwd" if command == "sync" else "config_base"
# Issue #1211: when the selected .pddrc is a subproject below the run CWD,
# "cwd" resolution would root relative output dirs at the parent CWD and
# write outside the subproject. Anchor them at the subproject .pddrc dir.
if effective_path_resolution_mode == "cwd" and subproject_pddrc_below_cwd:
effective_path_resolution_mode = "config_base"
output_paths_str: Dict[str, str] = generate_output_paths(
command=command,
output_locations=output_location_opts,
basename=basename,
language=language,
file_extension=file_extension,
context_config=context_config,
input_file_dir=input_file_dir,
input_file_dirs=input_file_dirs,
config_base_dir=str(pddrc_path.parent) if pddrc_path else None,
path_resolution_mode=effective_path_resolution_mode,
)
# Convert to Path objects for internal use
output_paths_resolved: Dict[str, Path] = {k: Path(v) for k, v in output_paths_str.items()}
except ValueError as e: # Catch ValueError if generate_output_paths raises it
console.print(f"[error]Error generating output paths: {e}", style="error")
raise # Re-raise the ValueError
# ------------- Step 4: overwrite confirmation ------------
# Initialize existing_files before the conditional to avoid UnboundLocalError
existing_files: Dict[str, Path] = {}
if command in ["test", "bug"] and not force:
# For test/bug commands without --force, create numbered files instead of overwriting
for key, path in output_paths_resolved.items():
if path.is_file():
base, ext = os.path.splitext(path)
i = 1
new_path = Path(f"{base}_{i}{ext}")
while new_path.exists():
i += 1
new_path = Path(f"{base}_{i}{ext}")
output_paths_resolved[key] = new_path
else:
# Check if any output *file* exists (operate on Path objects)
for k, p_obj in output_paths_resolved.items():
if p_obj.is_file():
existing_files[k] = p_obj # Store the Path object
if existing_files and not force:
paths_list = "\n".join(f" • {p.resolve()}" for p in existing_files.values())
if not quiet:
# Use the Path objects stored in existing_files for resolve()
# Print without Rich tags for easier testing
console.print(
f"Warning: The following output files already exist and may be overwritten:\n{paths_list}",
style="warning"
)
# Use confirm_callback if provided (for TUI environments), otherwise use click.confirm
if confirm_callback is not None:
# Use the provided callback for confirmation (e.g., from Textual TUI)
confirm_message = f"The following files will be overwritten:\n{paths_list}\n\nOverwrite existing files?"
if not confirm_callback(confirm_message, "Overwrite Confirmation"):
raise click.Abort()
else:
# Use click.confirm for CLI interaction
try:
if not click.confirm(
click.style("Overwrite existing files?", fg="yellow"), default=True, show_default=True
):
click.secho("Operation cancelled.", fg="red", err=True)
raise click.Abort()
except click.Abort:
raise # Let Abort propagate to be handled by PDDCLI.invoke()
except Exception as e: # Catch potential errors during confirm (like EOFError in non-interactive)
if 'EOF' in str(e) or 'end-of-file' in str(e).lower():
# Non-interactive environment, default to not overwriting
click.secho("Non-interactive environment detected. Use --force to overwrite existing files.", fg="yellow", err=True)
else:
click.secho(f"Confirmation failed: {e}. Aborting.", fg="red", err=True)
raise click.Abort()
# ------------- Final reporting ---------------------------
if not quiet:
console.print("[info]Input files:[/info]")
# Print resolved input paths
for k, p in input_paths.items():
console.print(f" [info]{k:<15}[/info] {p.resolve()}") # Use resolve() for consistent absolute paths
console.print("[info]Output files:[/info]")
# Print resolved output paths (using the Path objects)
for k, p in output_paths_resolved.items():
console.print(f" [info]{k:<15}[/info] {p.resolve()}") # Use resolve()
console.print(f"[info]Detected language:[/info] {language}")
console.print(f"[info]Basename:[/info] {basename}")
# Return output paths as strings, using the original dict from generate_output_paths
# if it returned strings, or convert the Path dict back.
# Since we converted to Path, convert back now.
output_file_paths_str_return = {k: str(v) for k, v in output_paths_resolved.items()}
# Add resolved paths to the config that gets returned
resolved_config.update(output_file_paths_str_return)
# Only infer prompts_dir if it wasn't provided via CLI/.pddrc/env.
gen_path = Path(resolved_config.get("generate_output_path", "src"))
if not resolved_config.get("prompts_dir"):
resolved_config["prompts_dir"] = str(next(iter(input_paths.values())).parent)
resolved_config["code_dir"] = str(gen_path.parent)
resolved_config["tests_dir"] = str(Path(resolved_config.get("test_output_path", "tests")).parent)
# Determine examples_dir for auto-deps scanning
# NOTE: outputs.example.path is for OUTPUT only (where to write examples),
# NOT for determining scan scope. Using it caused CSV row deletion issues.
# Do NOT use resolved_config since generate_output_paths sets it to absolute paths.
example_path_str = None
if original_context_config:
example_path_str = original_context_config.get("example_output_path")
# Issue #616: single source of truth via _resolve_default_examples_dir.
if not example_path_str:
example_path_str = _resolve_default_examples_dir(
_default_examples_project_root(pddrc_path)
)
# Extract ROOT directory (first component) for scan scope
# e.g., "context/commands/" -> "context", "examples/foo.py" -> "examples"
# Fix for Issue #332: Using full subdirectory path caused CSV truncation
example_path = Path(example_path_str)
parts = example_path.parts
if parts and parts[0] not in ('/', '.', '..'):
resolved_config["examples_dir"] = parts[0]
else:
resolved_config["examples_dir"] = _resolve_default_examples_dir(
_default_examples_project_root(pddrc_path)
)
return resolved_config, input_strings, output_file_paths_str_return, language
# pdd/construct_paths.py
from __future__ import annotations
import sys
import os
import glob
from pathlib import Path
from typing import Dict, Tuple, Any, Optional, List, Callable
import fnmatch
import logging
import warnings
import click
import yaml
from rich.theme import Theme
from .cli_theme import get_console
from .get_extension import get_extension
from .get_language import get_language
from .generate_output_paths import EXAMPLES_DIR, generate_output_paths
def _resolve_default_examples_dir(project_root: Optional[Path] = None) -> str:
"""Return the default examples-dir name when no `.pddrc` configures one.
Returns :data:`EXAMPLES_DIR` (canonical default). Only falls back to
``"context"`` when the project root has no ``examples/`` directory AND a
``context/`` directory containing at least one ``*_example.*`` file — i.e.
actual evidence of a legacy examples layout, not just any context content
(PRDs, schemas, docs are NOT a legacy-examples signal). This prevents the
original mismatch from staying alive on greenfield projects (#616).
"""
root = project_root or Path.cwd()
examples = root / EXAMPLES_DIR
legacy = root / "context"
if examples.exists() or not legacy.is_dir():
return EXAMPLES_DIR
try:
if next(legacy.rglob("*_example.*"), None) is not None:
return "context"
except OSError:
pass
return EXAMPLES_DIR
def _default_examples_project_root(pddrc_path: Optional[Path]) -> Path:
"""Return the base directory used for implicit examples-dir detection."""
return pddrc_path.parent if pddrc_path else Path.cwd()
# Assume generate_output_paths raises ValueError on unknown command
# Add csv import for the new helper function
import csv
console = get_console(theme=Theme({"info": "cyan", "warning": "yellow", "error": "bold red"}))
def _extract_prefix_from_prompts_dir(prompts_dir: str) -> str:
"""Extract the path suffix after the 'prompts' segment in a prompts_dir value.
Splits on '/' and finds the exact 'prompts' segment, then returns everything
after it. Returns empty string when prompts_dir is exactly 'prompts' or ends
at a 'prompts' segment. Falls back to returning the full normalized path when
no exact 'prompts' segment exists.
Examples:
"prompts" -> ""
"prompts/frontend" -> "frontend"
"extensions/github_pdd_app/prompts/frontend" -> "frontend"
"extensions/app/prompts" -> ""
"""
normalized = prompts_dir.rstrip('/')
parts = normalized.split('/')
try:
idx = parts.index('prompts')
except ValueError:
return normalized
return '/'.join(parts[idx + 1:])
# Shared mapping of language → file extension used across the codebase.
BUILTIN_EXT_MAP = {
'python': '.py', 'javascript': '.js', 'typescript': '.ts', 'java': '.java',
'cpp': '.cpp', 'c': '.c', 'go': '.go', 'ruby': '.rb', 'rust': '.rs',
'kotlin': '.kt', 'swift': '.swift', 'csharp': '.cs', 'php': '.php',
'scala': '.scala', 'r': '.r', 'lua': '.lua', 'perl': '.pl', 'bash': '.sh',
'shell': '.sh', 'powershell': '.ps1', 'sql': '.sql', 'html': '.html', 'css': '.css',
'prompt': '.prompt', 'makefile': '',
# Frontend framework variants
'typescriptreact': '.tsx', 'javascriptreact': '.jsx',
'svelte': '.svelte', 'vue': '.vue',
# Common data/config formats
'json': '.json', 'jsonl': '.jsonl', 'yaml': '.yaml', 'yml': '.yml', 'toml': '.toml', 'ini': '.ini',
'markdown': '.md',
}
# Configuration loading functions
def _find_pddrc_file(start_path: Optional[Path] = None) -> Optional[Path]:
"""Find .pddrc file by searching upward from the given path."""
if start_path is None:
start_path = Path.cwd()
Xet Storage Details
- Size:
- 73.4 kB
- Xet hash:
- 678a0a7e1e2dc96f5c3ba09056509cd7fd012facd1ed547c3ecca5bd489ccb25
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.