Spaces:
Sleeping
Sleeping
File size: 11,914 Bytes
3040bf7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | """Scrape real OpenAPI version histories from public Git repos.
Clones each provider's openapi repo (bare, blob-filtered), walks tags/commits,
extracts spec files at each version, and writes them to
scenarios/layer1_real/<provider>/<version>.<ext>.
Usage:
python scripts/scrape_specs.py [--out scenarios/layer1_real] [--providers stripe,github,twilio,slack,openai]
python scripts/scrape_specs.py --dry-run # print plan, do not clone
Output layout:
scenarios/layer1_real/
βββ stripe/
β βββ _versions.json # {"2024-04-10": "2024-04-10.json", ...}
β βββ 2024-04-10.json
βββ github/
β βββ _versions.json
β βββ 2024-09-01.yaml
βββ twilio/
β βββ _versions.json
β βββ messaging/
β βββ voice/
βββ slack/
β βββ _versions.json
β βββ 2024-01-01.json
βββ openai/
βββ _versions.json
βββ 2024-02-01.yaml
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# Provider configurations
# ---------------------------------------------------------------------------
PROVIDERS: Dict[str, dict] = {
"stripe": {
"url": "https://github.com/stripe/openapi.git",
"strategy": "tags",
"spec_paths": ["openapi/spec3.sdk.json", "openapi/spec3.json"],
"tag_pattern": r"^v\d+$",
"language": "python",
"framework": "stripe-python",
"max_versions": 100,
},
"github": {
"url": "https://github.com/github/rest-api-description.git",
"strategy": "commits",
"spec_paths": [
"descriptions/api.github.com/api.github.com.yaml",
"descriptions/api.github.com/api.github.com.json",
],
"language": "python",
"framework": "requests",
"max_versions": 60,
},
"twilio": {
"url": "https://github.com/twilio/twilio-oai.git",
"strategy": "commits",
"spec_paths": [
"spec/yaml/twilio_messaging_v1.yaml",
"spec/yaml/twilio_api_v2010.yaml",
],
"language": "python",
"framework": "twilio-python",
"max_versions": 50,
},
"slack": {
"url": "https://github.com/slackapi/slack-api-specs.git",
"strategy": "commits",
"spec_paths": [
"web-api/slack_web_openapi_v2.json",
"web-api/slack_web_openapi_v2_without_examples.json",
],
"language": "python",
"framework": "slack-sdk",
"max_versions": 40,
},
"openai": {
"url": "https://github.com/openai/openai-openapi.git",
"strategy": "commits",
"spec_paths": ["openapi.yaml"],
"language": "python",
"framework": "openai",
"max_versions": 30,
},
}
# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------
def _run(cmd: List[str], cwd: Optional[Path] = None, capture: bool = True) -> Tuple[int, str]:
result = subprocess.run(
cmd, cwd=str(cwd) if cwd else None,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None,
text=True,
)
return result.returncode, (result.stdout or "").strip()
def clone_bare(url: str, dest: Path) -> bool:
"""Clone bare with blob:none filter (fast, no working tree)."""
if dest.exists():
print(f" [skip] already cloned at {dest}")
return True
print(f" [clone] {url} -> {dest}")
rc, _ = _run(
["git", "clone", "--bare", "--filter=blob:none", url, str(dest)],
capture=False,
)
if rc != 0:
print(f" [warn] clone failed (rc={rc}), retrying without filter")
rc, _ = _run(["git", "clone", "--bare", "--depth=200", url, str(dest)], capture=False)
return rc == 0
def list_tags(repo: Path) -> List[str]:
rc, out = _run(["git", "tag", "--list"], cwd=repo)
if rc != 0:
return []
return [t.strip() for t in out.splitlines() if t.strip()]
def list_commits_touching(repo: Path, spec_path: str, max_n: int = 100) -> List[Tuple[str, str]]:
"""Return list of (sha, date_str) for commits that touched spec_path."""
rc, out = _run(
["git", "log", "--follow", "--format=%H %ai", "--", spec_path],
cwd=repo,
)
if rc != 0 or not out:
return []
results = []
for line in out.splitlines():
parts = line.split()
if len(parts) >= 2:
sha = parts[0]
date = parts[1] # YYYY-MM-DD
results.append((sha, date))
return results[:max_n]
def show_file(repo: Path, ref: str, spec_path: str) -> Optional[bytes]:
"""Extract file content at a specific ref."""
result = subprocess.run(
["git", "show", f"{ref}:{spec_path}"],
cwd=str(repo),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.returncode != 0:
return None
return result.stdout
def tag_to_date(tag: str, repo: Path) -> Optional[str]:
"""Try to get the commit date for a tag."""
rc, out = _run(
["git", "log", "-1", "--format=%ai", tag],
cwd=repo,
)
if rc == 0 and out:
return out.split()[0] # YYYY-MM-DD
return None
# ---------------------------------------------------------------------------
# Per-provider extraction
# ---------------------------------------------------------------------------
def extract_stripe(repo: Path, out_dir: Path, max_versions: int) -> Dict[str, str]:
"""Walk stripe tags (v700, v701, ...), extract spec3.sdk.json."""
tags = list_tags(repo)
# Filter to versioned tags
versioned = sorted(
[t for t in tags if re.match(r"^v\d+$", t)],
key=lambda t: int(t[1:]),
)
if not versioned:
# Fallback: try date-formatted tags
versioned = sorted([t for t in tags if re.match(r"^\d{4}-\d{2}-\d{2}$", t)])
versions_map: Dict[str, str] = {}
spec_paths = PROVIDERS["stripe"]["spec_paths"]
for tag in versioned[-max_versions:]:
date = tag_to_date(tag, repo)
if not date:
date = tag # use tag name as version label
for sp in spec_paths:
content = show_file(repo, tag, sp)
if content:
ext = Path(sp).suffix
fname = f"{date}{ext}"
(out_dir / fname).write_bytes(content)
versions_map[date] = fname
break
return versions_map
def extract_via_commits(
repo: Path,
out_dir: Path,
spec_paths: List[str],
max_versions: int,
subdir: Optional[str] = None,
) -> Dict[str, str]:
"""Walk commit history for each spec_path, dedup by date."""
target_dir = out_dir / subdir if subdir else out_dir
target_dir.mkdir(parents=True, exist_ok=True)
versions_map: Dict[str, str] = {}
for sp in spec_paths:
commits = list_commits_touching(repo, sp, max_versions)
if not commits:
continue
seen_dates: Dict[str, str] = {}
for sha, date in commits:
if date in seen_dates:
continue
content = show_file(repo, sha, sp)
if not content:
continue
ext = Path(sp).suffix
fname = f"{date}{ext}"
(target_dir / fname).write_bytes(content)
seen_dates[date] = fname
versions_map.update(seen_dates)
if len(versions_map) >= max_versions:
break
return versions_map
def extract_twilio(repo: Path, out_dir: Path, max_versions: int) -> Dict[str, str]:
"""Twilio has multiple product lines; organize by product."""
spec_files = {
"messaging": "spec/yaml/twilio_messaging_v1.yaml",
"api": "spec/yaml/twilio_api_v2010.yaml",
"voice": "spec/yaml/twilio_voice_v1.yaml",
}
combined: Dict[str, str] = {}
for product, sp in spec_files.items():
sub_map = extract_via_commits(repo, out_dir, [sp], max_versions // len(spec_files), subdir=product)
# Also write to the provider root for easier indexing
for date, fname in sub_map.items():
combined[f"{product}/{date}"] = f"{product}/{fname}"
return combined
# ---------------------------------------------------------------------------
# Main orchestrator
# ---------------------------------------------------------------------------
def scrape_provider(
name: str,
cfg: dict,
temp_dir: Path,
out_root: Path,
dry_run: bool = False,
) -> Dict[str, str]:
out_dir = out_root / name
out_dir.mkdir(parents=True, exist_ok=True)
if dry_run:
print(f"[dry-run] {name}: would clone {cfg['url']} and extract {cfg['max_versions']} versions")
return {}
repo_dir = temp_dir / f"{name}.git"
print(f"\n[{name}] Cloning...")
if not clone_bare(cfg["url"], repo_dir):
print(f"[{name}] Clone failed, skipping.")
return {}
print(f"[{name}] Extracting specs...")
if name == "stripe":
versions_map = extract_stripe(repo_dir, out_dir, cfg["max_versions"])
elif name == "twilio":
versions_map = extract_twilio(repo_dir, out_dir, cfg["max_versions"])
else:
versions_map = extract_via_commits(
repo_dir, out_dir, cfg["spec_paths"], cfg["max_versions"]
)
index_file = out_dir / "_versions.json"
index_file.write_text(
json.dumps({"provider": name, "versions": versions_map}, indent=2),
encoding="utf-8",
)
print(f"[{name}] Done β {len(versions_map)} versions extracted to {out_dir}")
return versions_map
def main() -> None:
parser = argparse.ArgumentParser(description="Scrape real OpenAPI specs from public repos")
parser.add_argument("--out", default="scenarios/layer1_real", help="Output directory")
parser.add_argument("--temp", default=None, help="Temp dir for bare clones (default: system temp)")
parser.add_argument("--providers", default=",".join(PROVIDERS.keys()),
help="Comma-separated provider list")
parser.add_argument("--dry-run", action="store_true", help="Print plan without cloning")
parser.add_argument("--keep-temp", action="store_true", help="Keep bare clone dirs after extraction")
args = parser.parse_args()
out_root = Path(args.out)
out_root.mkdir(parents=True, exist_ok=True)
providers_list = [p.strip() for p in args.providers.split(",") if p.strip() in PROVIDERS]
if not providers_list:
print(f"No valid providers. Available: {list(PROVIDERS.keys())}")
sys.exit(1)
use_temp_dir = args.temp is None and not args.dry_run
temp_ctx = tempfile.TemporaryDirectory(prefix="apishift_clones_") if use_temp_dir else None
temp_dir = Path(temp_ctx.name) if temp_ctx else Path(args.temp or "scripts/_temp_clones")
temp_dir.mkdir(parents=True, exist_ok=True)
summary: Dict[str, int] = {}
try:
for name in providers_list:
cfg = PROVIDERS[name]
versions_map = scrape_provider(name, cfg, temp_dir, out_root, dry_run=args.dry_run)
summary[name] = len(versions_map)
finally:
if temp_ctx and not args.keep_temp:
temp_ctx.cleanup()
print("\n=== Scrape Summary ===")
total = 0
for name, count in summary.items():
print(f" {name}: {count} versions")
total += count
print(f" TOTAL: {total} spec versions")
print(f" Output: {out_root.resolve()}")
if __name__ == "__main__":
main()
|