Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

sync_repos.py 8.3 KB

You have to be logged in to leave a comment. Sign In
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
  1. #!/usr/bin/env python3
  2. """
  3. Sync GitHub repos' portfolio.json into the portfolio backend.
  4. Features
  5. - Reads repos from repos.json (or --config)
  6. - Fetches portfolio.json via GitHub raw
  7. - Optionally downloads referenced assets to assets/projects/ and rewrites URLs
  8. - Upserts to backend via POST /api/projects or PUT /api/projects/{id}
  9. Environment variables
  10. - PORTFOLIO_API_BASE: API base URL (default: http://localhost:8000/api)
  11. - PORTFOLIO_API_TOKEN: Optional bearer token for backend auth
  12. - REPOS_CONFIG: Path to repos.json (default: repos.json)
  13. - SYNC_DOWNLOAD_ASSETS: If 'true', download assets locally (default: false)
  14. - ASSET_BASE_PATH: Local dir to store assets (default: assets/projects)
  15. - ASSET_PREFIX_URL: URL prefix to reference local assets (default: /assets/projects)
  16. - REQUEST_TIMEOUT: HTTP timeout seconds (default: 20)
  17. repos.json schema
  18. [
  19. { "repo": "https://github.com/owner/name", "branch": "main", "path": "portfolio.json" }
  20. ]
  21. Assumptions
  22. - Project identifier is `slug` if present, else derived from `title`.
  23. - Backend supports POST /api/projects and PUT /api/projects/{id} where id is slug.
  24. """
  25. from __future__ import annotations
  26. import argparse
  27. import json
  28. import os
  29. import re
  30. import sys
  31. from pathlib import Path
  32. from typing import Any, Dict, List, Optional, Tuple
  33. import requests
  34. DEFAULT_API_BASE = os.environ.get("PORTFOLIO_API_BASE", "http://localhost:8000/api")
  35. DEFAULT_CONFIG = os.environ.get("REPOS_CONFIG", "repos.json")
  36. DEFAULT_TIMEOUT = float(os.environ.get("REQUEST_TIMEOUT", "20"))
  37. DOWNLOAD_ASSETS = os.environ.get("SYNC_DOWNLOAD_ASSETS", "false").lower() == "true"
  38. ASSET_BASE_PATH = Path(os.environ.get("ASSET_BASE_PATH", "assets/projects"))
  39. ASSET_PREFIX_URL = os.environ.get("ASSET_PREFIX_URL", "/assets/projects")
  40. API_TOKEN = os.environ.get("PORTFOLIO_API_TOKEN")
  41. SESSION = requests.Session()
  42. if API_TOKEN:
  43. SESSION.headers.update({"Authorization": f"Bearer {API_TOKEN}"})
  44. SESSION.headers.update({"Content-Type": "application/json"})
  45. def slugify(text: str) -> str:
  46. text = text.strip().lower()
  47. text = re.sub(r"[^a-z0-9\-\s_]", "", text)
  48. text = re.sub(r"[\s_]+", "-", text)
  49. return text
  50. def read_repos_config(path: Path) -> List[Dict[str, Any]]:
  51. with path.open("r", encoding="utf-8") as f:
  52. data = json.load(f)
  53. if not isinstance(data, list):
  54. raise ValueError("repos.json must be a list")
  55. return data
  56. def make_raw_url(repo_url: str, branch: str, file_path: str) -> str:
  57. repo_url = repo_url.rstrip("/")
  58. if repo_url.startswith("https://github.com/"):
  59. owner_name = repo_url[len("https://github.com/") :]
  60. return f"https://raw.githubusercontent.com/{owner_name}/{branch}/{file_path}"
  61. if repo_url.startswith("git@github.com:"):
  62. owner_name = repo_url[len("git@github.com:") :].removesuffix(".git")
  63. return f"https://raw.githubusercontent.com/{owner_name}/{branch}/{file_path}"
  64. # Fallback: assume raw already
  65. return repo_url
  66. def fetch_portfolio_json(raw_url: str, timeout: float = DEFAULT_TIMEOUT) -> Dict[str, Any]:
  67. resp = SESSION.get(raw_url, timeout=timeout)
  68. resp.raise_for_status()
  69. return resp.json()
  70. def ensure_slug(project: Dict[str, Any]) -> str:
  71. slug = project.get("slug")
  72. if slug:
  73. return slug
  74. title = project.get("title")
  75. if not title:
  76. raise ValueError("Project must include either 'slug' or 'title'")
  77. slug = slugify(title)
  78. project["slug"] = slug
  79. return slug
  80. def infer_assets(project: Dict[str, Any]) -> List[Tuple[str, str]]:
  81. """Return list of (field_path, url) for known asset fields."""
  82. assets: List[Tuple[str, str]] = []
  83. preview = project.get("brassFramedPreview")
  84. if isinstance(preview, str) and preview.startswith("http"):
  85. assets.append(("brassFramedPreview", preview))
  86. if isinstance(project.get("cogwheelSchema"), list):
  87. for i, url in enumerate(project["cogwheelSchema"]):
  88. if isinstance(url, str) and url.startswith("http"):
  89. assets.append((f"cogwheelSchema[{i}]", url))
  90. return assets
  91. def download_asset(url: str, dest_dir: Path, name_hint: Optional[str] = None) -> str:
  92. dest_dir.mkdir(parents=True, exist_ok=True)
  93. filename = name_hint or url.split("/")[-1]
  94. target = dest_dir / filename
  95. r = SESSION.get(url, timeout=DEFAULT_TIMEOUT)
  96. r.raise_for_status()
  97. with target.open("wb") as f:
  98. f.write(r.content)
  99. rel_url = f"{ASSET_PREFIX_URL}/{target.name}"
  100. return rel_url
  101. def maybe_localize_assets(project: Dict[str, Any]) -> None:
  102. if not DOWNLOAD_ASSETS:
  103. return
  104. assets = infer_assets(project)
  105. for field_path, url in assets:
  106. name_hint = None
  107. if "brassFramedPreview" in field_path:
  108. name_hint = f"{project.get('slug','preview')}_preview{Path(url).suffix or ''}"
  109. elif field_path.startswith("cogwheelSchema["):
  110. idx = re.search(r"\[(\d+)\]", field_path)
  111. suffix = Path(url).suffix or ""
  112. name_hint = f"{project.get('slug','schema')}_schema_{idx.group(1) if idx else '0'}{suffix}"
  113. new_url = download_asset(url, ASSET_BASE_PATH, name_hint=name_hint)
  114. # Rewrite project JSON
  115. if field_path == "brassFramedPreview":
  116. project["brassFramedPreview"] = new_url
  117. elif field_path.startswith("cogwheelSchema["):
  118. m = re.search(r"\[(\d+)\]", field_path)
  119. if m:
  120. i = int(m.group(1))
  121. arr = project.get("cogwheelSchema") or []
  122. if i < len(arr):
  123. arr[i] = new_url
  124. else:
  125. # pad if necessary
  126. while len(arr) <= i:
  127. arr.append("")
  128. arr[i] = new_url
  129. project["cogwheelSchema"] = arr
  130. def upsert_project(api_base: str, project: Dict[str, Any]) -> Dict[str, Any]:
  131. slug = ensure_slug(project)
  132. # Try POST first
  133. url_post = f"{api_base.rstrip('/')}/projects"
  134. resp = SESSION.post(url_post, data=json.dumps(project), timeout=DEFAULT_TIMEOUT)
  135. if resp.status_code in (200, 201):
  136. return resp.json() if resp.content else {"status": "created", "slug": slug}
  137. # If conflict or already exists, try PUT by slug
  138. if resp.status_code in (400, 409, 422):
  139. url_put = f"{api_base.rstrip('/')}/projects/{slug}"
  140. resp2 = SESSION.put(url_put, data=json.dumps(project), timeout=DEFAULT_TIMEOUT)
  141. resp2.raise_for_status()
  142. return resp2.json() if resp2.content else {"status": "updated", "slug": slug}
  143. resp.raise_for_status()
  144. return {"status": "unknown", "slug": slug}
  145. def process_repo(entry: Dict[str, Any], api_base: str) -> Tuple[str, str]:
  146. repo = entry["repo"]
  147. branch = entry.get("branch", "main")
  148. path = entry.get("path", "portfolio.json")
  149. raw_url = make_raw_url(repo, branch, path)
  150. pj = fetch_portfolio_json(raw_url)
  151. ensure_slug(pj)
  152. maybe_localize_assets(pj)
  153. result = upsert_project(api_base, pj)
  154. return (pj["slug"], result.get("status", "ok"))
  155. def main(argv: Optional[List[str]] = None) -> int:
  156. parser = argparse.ArgumentParser(description="Sync portfolio projects from repos")
  157. parser.add_argument("--config", default=DEFAULT_CONFIG, help="Path to repos.json")
  158. parser.add_argument("--api", default=DEFAULT_API_BASE, help="Backend API base URL")
  159. parser.add_argument("--download-assets", action="store_true", help="Download and localize assets")
  160. args = parser.parse_args(argv)
  161. if args.download_assets:
  162. global DOWNLOAD_ASSETS
  163. DOWNLOAD_ASSETS = True
  164. config_path = Path(args.config)
  165. if not config_path.exists():
  166. print(f"Config not found: {config_path}", file=sys.stderr)
  167. return 2
  168. try:
  169. repos = read_repos_config(config_path)
  170. except Exception as e:
  171. print(f"Failed to read config: {e}", file=sys.stderr)
  172. return 2
  173. successes: List[Tuple[str, str]] = []
  174. failures: List[Tuple[str, str]] = []
  175. for entry in repos:
  176. try:
  177. slug, status = process_repo(entry, args.api)
  178. print(f"[{status}] {slug}")
  179. successes.append((slug, status))
  180. except Exception as e:
  181. repo = entry.get("repo", "<unknown>")
  182. print(f"[error] {repo}: {e}", file=sys.stderr)
  183. failures.append((repo, str(e)))
  184. print(f"Done. {len(successes)} succeeded, {len(failures)} failed.")
  185. return 0 if not failures else 1
  186. if __name__ == "__main__":
  187. raise SystemExit(main())
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...