-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.py
More file actions
222 lines (170 loc) · 7.23 KB
/
Copy pathsync.py
File metadata and controls
222 lines (170 loc) · 7.23 KB
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
#!/usr/bin/env python3
"""Sync PROJECT.md and BUILDLOG.md to a WordPress page via REST API."""
import base64
import html
import os
import re
import sys
import frontmatter
import markdown
import requests
def load_project():
if not os.path.exists("PROJECT.md"):
print("ERROR: PROJECT.md not found in repo root.")
sys.exit(1)
with open("PROJECT.md", "r", encoding="utf-8") as f:
post = frontmatter.load(f)
if not post.get("title"):
print("ERROR: PROJECT.md is missing required field: title")
sys.exit(1)
if not post.get("wp_page_id"):
print("ERROR: PROJECT.md is missing wp_page_id.")
print(" Add wp_page_id to PROJECT.md frontmatter.")
print(" Find the page ID in WordPress Admin > Pages (hover over the page title to see the ID in the URL).")
sys.exit(1)
return post
def load_buildlog():
if not os.path.exists("BUILDLOG.md"):
return ""
with open("BUILDLOG.md", "r", encoding="utf-8") as f:
return f.read()
def to_html(text):
return markdown.markdown(
text,
extensions=["tables", "fenced_code", "nl2br"],
)
def read_wordpress(page_id, wp_url, wp_user, wp_password):
"""GET existing page HTML from WordPress. Exits on any non-200 response (D-05)."""
endpoint = f"{wp_url.rstrip('/')}/wp-json/wp/v2/pages/{page_id}?context=edit"
credentials = base64.b64encode(f"{wp_user}:{wp_password}".encode()).decode()
headers = {"Authorization": f"Basic {credentials}"}
try:
response = requests.get(endpoint, headers=headers, timeout=30)
except requests.exceptions.RequestException as e:
print(f"ERROR: Could not connect to WordPress API: {e}")
sys.exit(1)
if response.status_code != 200:
print(f"ERROR: Could not read WordPress page {page_id} (HTTP {response.status_code})")
print(response.text[:500])
sys.exit(1)
try:
return response.json()["content"]["raw"]
except (ValueError, KeyError) as e:
print(f"ERROR: Unexpected response structure from WordPress API: {e}")
print(response.text[:500])
sys.exit(1)
def has_section_markers(html_content):
"""True if the page contains at least one complete <!-- wp-sync:X -->...<!-- /wp-sync:X --> pair."""
return bool(re.search(r"<!-- wp-sync:(\w+) -->.*?<!-- /wp-sync:\1 -->", html_content, flags=re.DOTALL))
def replace_section(html_content, name, new_content):
"""
Replace everything between <!-- wp-sync:NAME --> and <!-- /wp-sync:NAME -->.
Returns html unchanged if the marker pair is not found (D-04 no-op).
Uses a callable replacer — string templates break on backslashes in new_content.
"""
pattern = r"(<!-- wp-sync:{n} -->).*?(<!-- /wp-sync:{n} -->)".format(
n=re.escape(name)
)
if not re.search(pattern, html_content, flags=re.DOTALL):
return html_content # marker absent — no-op
def replacer(m):
return m.group(1) + "\n" + new_content + "\n" + m.group(2)
return re.sub(pattern, replacer, html_content, flags=re.DOTALL)
def _build_status_bar(project):
"""Return status-bar HTML string(s) for a project (HTML-escaped)."""
status = html.escape(project.get("status", "in-progress"))
github_url = project.get("github_url", "")
project_type = html.escape(project.get("type", ""))
if github_url:
safe_url = html.escape(github_url, quote=True)
github_link = f' · <a href="{safe_url}">View on GitHub →</a>'
else:
github_link = ""
type_label = f" · {project_type}" if project_type else ""
status_bar = f'<p><strong>Status:</strong> {status}{type_label}{github_link}</p>'
tags = project.get("tags") or []
if not isinstance(tags, list):
tags = [tags]
if tags:
tag_tokens = " ".join(f"#{html.escape(str(t))}" for t in tags)
return status_bar + "\n" + f"<p>{tag_tokens}</p>"
return status_bar
def build_project_section(project):
"""HTML for <!-- wp-sync:project --> (D-01): status bar + body, no HR."""
parts = [_build_status_bar(project)]
body = project.content.strip()
if body:
parts.append(to_html(body))
return "\n\n".join(parts)
def build_buildlog_section(buildlog_md):
"""HTML for <!-- wp-sync:buildlog --> (D-02): buildlog HTML only, no HR."""
return to_html(buildlog_md)
def build_content(project, buildlog_md):
"""Legacy full-replace fallback (SYNC-03). Used when the WordPress page has no section markers."""
parts = [_build_status_bar(project)]
# Main project content
body = project.content.strip()
if body:
parts.append(to_html(body))
# Build log
if buildlog_md.strip():
parts.append("<hr>")
parts.append(to_html(buildlog_md))
return "\n\n".join(parts)
def update_wordpress(page_id, title, content, wp_url, wp_user, wp_password):
endpoint = f"{wp_url.rstrip('/')}/wp-json/wp/v2/pages/{page_id}"
credentials = base64.b64encode(f"{wp_user}:{wp_password}".encode()).decode()
headers = {
"Authorization": f"Basic {credentials}",
"Content-Type": "application/json",
}
payload = {
"title": title,
"content": content,
"status": "publish",
}
try:
response = requests.put(endpoint, headers=headers, json=payload, timeout=30)
except requests.exceptions.RequestException as e:
print(f"ERROR: Could not connect to WordPress API: {e}")
sys.exit(1)
if response.status_code in (200, 201):
try:
data = response.json()
print(f"Published: {data.get('link', endpoint)}")
except ValueError:
print(f"Published (no JSON body returned): {endpoint}")
else:
print(f"ERROR: WordPress API returned {response.status_code}")
print(response.text[:500])
sys.exit(1)
def main():
wp_url = os.environ.get("WP_URL", "")
wp_user = os.environ.get("WP_USER", "")
wp_password = os.environ.get("WP_APP_PASSWORD", "")
if not all([wp_url, wp_user, wp_password]):
missing = [k for k, v in {"WP_URL": wp_url, "WP_USER": wp_user, "WP_APP_PASSWORD": wp_password}.items() if not v]
print(f"ERROR: Missing environment variables: {', '.join(missing)}")
sys.exit(1)
project = load_project()
buildlog = load_buildlog()
page_id = project["wp_page_id"]
title = project["title"]
print(f"Syncing '{title}' to WordPress page {page_id}...")
existing_html = read_wordpress(page_id, wp_url, wp_user, wp_password)
if has_section_markers(existing_html):
content = existing_html
# Project section (D-01)
project_html = build_project_section(project)
content = replace_section(content, "project", project_html)
# Buildlog section (D-02, D-03)
if buildlog.strip():
buildlog_html = build_buildlog_section(buildlog)
content = replace_section(content, "buildlog", buildlog_html)
# else: buildlog marker left unchanged (D-03 — absent file means skip)
else:
# Full-replace fallback (SYNC-03) — existing behaviour, unchanged
content = build_content(project, buildlog)
update_wordpress(page_id, title, content, wp_url, wp_user, wp_password)
if __name__ == "__main__":
main()