|
| 1 | +"""Organization README generator - generates overview of multiple projects.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from typing import Dict, List, Optional |
| 5 | + |
| 6 | +from code2llm.api import AnalysisResult |
| 7 | + |
| 8 | +from ..config import Code2DocsConfig |
| 9 | +from ..analyzers.project_scanner import ProjectScanner |
| 10 | + |
| 11 | + |
| 12 | +class OrgReadmeGenerator: |
| 13 | + """Generate organization README with list of projects and brief descriptions.""" |
| 14 | + |
| 15 | + def __init__(self, config: Code2DocsConfig, org_path: str, org_name: str = ""): |
| 16 | + self.config = config |
| 17 | + self.org_path = Path(org_path).resolve() |
| 18 | + self.org_name = org_name or self.org_path.name |
| 19 | + self.scanner = ProjectScanner(config) |
| 20 | + |
| 21 | + def generate(self) -> str: |
| 22 | + """Generate organization README content.""" |
| 23 | + projects = self._discover_projects() |
| 24 | + |
| 25 | + lines = [ |
| 26 | + f"# {self.org_name}\n", |
| 27 | + f"Projects in the {self.org_name} organization.\n", |
| 28 | + f"**{len(projects)}** projects discovered.\n", |
| 29 | + "## Projects\n", |
| 30 | + ] |
| 31 | + |
| 32 | + for project_name, project_info in sorted(projects.items()): |
| 33 | + lines.append(self._render_project_section(project_name, project_info)) |
| 34 | + lines.append("") |
| 35 | + |
| 36 | + return "\n".join(lines) |
| 37 | + |
| 38 | + def _discover_projects(self) -> Dict[str, Dict]: |
| 39 | + """Discover all projects in organization directory.""" |
| 40 | + projects = {} |
| 41 | + |
| 42 | + for item in self.org_path.iterdir(): |
| 43 | + if not item.is_dir(): |
| 44 | + continue |
| 45 | + if item.name.startswith(".") or item.name.startswith("__"): |
| 46 | + continue |
| 47 | + |
| 48 | + project_info = self._analyze_project(item) |
| 49 | + if project_info: |
| 50 | + projects[item.name] = project_info |
| 51 | + |
| 52 | + return projects |
| 53 | + |
| 54 | + def _analyze_project(self, project_path: Path) -> Optional[Dict]: |
| 55 | + """Analyze a single project and return summary info.""" |
| 56 | + try: |
| 57 | + result = self.scanner.analyze(str(project_path)) |
| 58 | + |
| 59 | + # Extract description from first module docstring or pyproject.toml |
| 60 | + description = self._extract_description(project_path, result) |
| 61 | + |
| 62 | + # Count functions, classes, modules |
| 63 | + func_count = len(result.functions) |
| 64 | + class_count = len(result.classes) |
| 65 | + module_count = len(result.modules) |
| 66 | + |
| 67 | + # Get version from pyproject.toml if available |
| 68 | + version = self._get_version(project_path) |
| 69 | + |
| 70 | + # Get repo URL from git or config |
| 71 | + repo_url = self._get_repo_url(project_path) |
| 72 | + |
| 73 | + return { |
| 74 | + "name": project_path.name, |
| 75 | + "description": description, |
| 76 | + "version": version, |
| 77 | + "stats": { |
| 78 | + "functions": func_count, |
| 79 | + "classes": class_count, |
| 80 | + "modules": module_count, |
| 81 | + }, |
| 82 | + "repo_url": repo_url, |
| 83 | + "path": str(project_path), |
| 84 | + } |
| 85 | + except Exception: |
| 86 | + return None |
| 87 | + |
| 88 | + def _extract_description(self, project_path: Path, result: AnalysisResult) -> str: |
| 89 | + """Extract short description from project (max 5 lines).""" |
| 90 | + # Try pyproject.toml first |
| 91 | + try: |
| 92 | + import tomllib |
| 93 | + pyproject = project_path / "pyproject.toml" |
| 94 | + if pyproject.exists(): |
| 95 | + with open(pyproject, "rb") as f: |
| 96 | + data = tomllib.load(f) |
| 97 | + desc = data.get("project", {}).get("description", "") |
| 98 | + if desc: |
| 99 | + # Limit to ~5 lines worth of content |
| 100 | + return self._truncate_description(desc) |
| 101 | + except Exception: |
| 102 | + pass |
| 103 | + |
| 104 | + # Try first package docstring |
| 105 | + for mod in result.modules.values(): |
| 106 | + if mod.is_package and hasattr(mod, "docstring") and mod.docstring: |
| 107 | + return self._truncate_description(mod.docstring) |
| 108 | + |
| 109 | + # Try README.md first paragraph |
| 110 | + readme = project_path / "README.md" |
| 111 | + if readme.exists(): |
| 112 | + try: |
| 113 | + content = readme.read_text(encoding="utf-8") |
| 114 | + # Find first paragraph after title |
| 115 | + lines = content.split("\n") |
| 116 | + for i, line in enumerate(lines): |
| 117 | + if line.startswith("# "): |
| 118 | + # Get next non-empty lines |
| 119 | + desc_lines = [] |
| 120 | + for j in range(i + 1, min(i + 10, len(lines))): |
| 121 | + if lines[j].strip() and not lines[j].startswith("#"): |
| 122 | + desc_lines.append(lines[j].strip()) |
| 123 | + if len(desc_lines) >= 5: |
| 124 | + break |
| 125 | + if desc_lines: |
| 126 | + return " ".join(desc_lines) |
| 127 | + except Exception: |
| 128 | + pass |
| 129 | + |
| 130 | + return "No description available." |
| 131 | + |
| 132 | + def _truncate_description(self, desc: str, max_chars: int = 300) -> str: |
| 133 | + """Truncate description to ~5 lines of content.""" |
| 134 | + lines = desc.strip().split("\n") |
| 135 | + # Filter out empty lines and headers |
| 136 | + content_lines = [l.strip() for l in lines if l.strip() and not l.startswith("#")] |
| 137 | + |
| 138 | + result = [] |
| 139 | + char_count = 0 |
| 140 | + for line in content_lines[:5]: |
| 141 | + if char_count + len(line) > max_chars: |
| 142 | + remaining = max_chars - char_count |
| 143 | + if remaining > 20: |
| 144 | + result.append(line[:remaining] + "...") |
| 145 | + break |
| 146 | + result.append(line) |
| 147 | + char_count += len(line) |
| 148 | + |
| 149 | + return " ".join(result) if result else "No description available." |
| 150 | + |
| 151 | + def _get_version(self, project_path: Path) -> str: |
| 152 | + """Get version from pyproject.toml or VERSION file.""" |
| 153 | + try: |
| 154 | + import tomllib |
| 155 | + pyproject = project_path / "pyproject.toml" |
| 156 | + if pyproject.exists(): |
| 157 | + with open(pyproject, "rb") as f: |
| 158 | + data = tomllib.load(f) |
| 159 | + return data.get("project", {}).get("version", "") |
| 160 | + except Exception: |
| 161 | + pass |
| 162 | + |
| 163 | + version_file = project_path / "VERSION" |
| 164 | + if version_file.exists(): |
| 165 | + return version_file.read_text(encoding="utf-8").strip() |
| 166 | + |
| 167 | + return "" |
| 168 | + |
| 169 | + def _get_repo_url(self, project_path: Path) -> str: |
| 170 | + """Get repository URL from git or pyproject.toml.""" |
| 171 | + # Try pyproject.toml |
| 172 | + try: |
| 173 | + import tomllib |
| 174 | + pyproject = project_path / "pyproject.toml" |
| 175 | + if pyproject.exists(): |
| 176 | + with open(pyproject, "rb") as f: |
| 177 | + data = tomllib.load(f) |
| 178 | + urls = data.get("project", {}).get("urls", {}) |
| 179 | + if urls: |
| 180 | + return urls.get("Repository", urls.get("Homepage", "")) |
| 181 | + except Exception: |
| 182 | + pass |
| 183 | + |
| 184 | + # Try git remote |
| 185 | + try: |
| 186 | + import subprocess |
| 187 | + result = subprocess.run( |
| 188 | + ["git", "remote", "get-url", "origin"], |
| 189 | + cwd=str(project_path), |
| 190 | + capture_output=True, text=True, timeout=5, |
| 191 | + ) |
| 192 | + if result.returncode == 0: |
| 193 | + url = result.stdout.strip() |
| 194 | + # Convert SSH to HTTPS |
| 195 | + if url.startswith("git@"): |
| 196 | + url = url.replace(":", "/", 1).replace("git@", "https://", 1) |
| 197 | + return url.removesuffix(".git") |
| 198 | + except Exception: |
| 199 | + pass |
| 200 | + |
| 201 | + return "" |
| 202 | + |
| 203 | + def _render_project_section(self, name: str, info: Dict) -> str: |
| 204 | + """Render a single project section (5 lines max).""" |
| 205 | + lines = [f"### {name}"] |
| 206 | + |
| 207 | + # Line 1: Description |
| 208 | + lines.append(info["description"]) |
| 209 | + |
| 210 | + # Line 2: Stats |
| 211 | + stats = info["stats"] |
| 212 | + stats_line = f"📊 {stats['functions']} functions | {stats['classes']} classes | {stats['modules']} modules" |
| 213 | + if info["version"]: |
| 214 | + stats_line += f" | v{info['version']}" |
| 215 | + lines.append(stats_line) |
| 216 | + |
| 217 | + # Line 3: Repo link if available |
| 218 | + if info["repo_url"]: |
| 219 | + lines.append(f"🔗 [{info['repo_url']}]({info['repo_url']})") |
| 220 | + |
| 221 | + return "\n".join(lines) |
| 222 | + |
| 223 | + def write(self, output_path: str, content: str) -> None: |
| 224 | + """Write README to output path.""" |
| 225 | + out_path = Path(output_path) |
| 226 | + out_path.parent.mkdir(parents=True, exist_ok=True) |
| 227 | + out_path.write_text(content, encoding="utf-8") |
0 commit comments