-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate_blog.py
398 lines (324 loc) · 12.3 KB
/
update_blog.py
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import os
import re
import shutil
import time
import json
import subprocess
from datetime import datetime, timezone
from pathlib import Path
# Configuration
CONFIG = {
# Repository settings
"repo": {
"owner": "apotenza92",
"name": "blog",
},
# Folder structure
"folders": {
"posts": "posts",
"images": "images",
"static": "static",
"content": "content",
"public": "public",
},
# Workflow settings
"workflow": {"check_delay": 10, "max_checks": 30}, # seconds # 5 minutes maximum
}
def find_onedrive_root():
"""Find OneDrive root directory across different OS configurations"""
possible_paths = [
os.path.expanduser("~/OneDrive"), # Windows/Mac default
os.path.expanduser("~/OneDrive - Personal"), # Business account variant
"/Users/Shared/OneDrive", # Alternative Mac location
os.path.expanduser(
"~/Library/CloudStorage/OneDrive-Personal"
), # New Mac location
]
for path in possible_paths:
if os.path.exists(path):
return path
raise FileNotFoundError("Could not find OneDrive folder")
def find_obsidian_vault(start_path, vault_name="Notes"):
"""Find Obsidian vault by looking for .obsidian folder"""
# First try direct path
direct_path = os.path.join(start_path, vault_name)
if os.path.exists(os.path.join(direct_path, ".obsidian")):
return direct_path
# Search recursively up to 2 levels deep
for root, dirs, _ in os.walk(start_path):
if ".obsidian" in dirs:
return root
# Don't go too deep
if root.count(os.sep) - start_path.count(os.sep) >= 2:
dirs.clear()
raise FileNotFoundError(f"Could not find Obsidian vault '{vault_name}'")
def get_latest_workflow_run():
try:
# Get workflows started in the last 5 minutes
current_time = datetime.now(timezone.utc).isoformat()
result = subprocess.run(
[
"gh",
"api",
f"/repos/{CONFIG['repo']['owner']}/{CONFIG['repo']['name']}/actions/runs?created=>2023-01-01&per_page=5",
],
capture_output=True,
text=True,
check=True,
)
runs = json.loads(result.stdout).get("workflow_runs", [])
# Find the most recent "in_progress" or "queued" run
for run in runs:
if run["status"] in ["in_progress", "queued"]:
return run
return runs[0] if runs else None
except subprocess.CalledProcessError as e:
print(f"Error getting workflow runs: {e}")
return None
def wait_for_workflow():
delay = CONFIG["workflow"]["check_delay"]
max_checks = CONFIG["workflow"]["max_checks"]
print(f"\nWaiting {delay} seconds for workflow to start...")
time.sleep(delay)
print("Checking workflow status...")
attempts = 0
while attempts < max_checks:
run = get_latest_workflow_run()
if not run:
print("No workflow run found")
break
status = run["status"]
conclusion = run["conclusion"]
run_id = run["id"]
if status == "completed":
if conclusion == "success":
print("\n✅ Workflow completed successfully!")
else:
print(f"\n❌ Workflow failed with conclusion: {conclusion}")
repo = CONFIG["repo"]
print(
f"Check: https://github.com/{repo['owner']}/{repo['name']}/actions/runs/{run_id}"
)
break
print(f"Status: {status}... (checking again in {delay} seconds)")
time.sleep(delay)
attempts += 1
if attempts >= max_checks:
print("\n⚠️ Timed out waiting for workflow to complete")
def setup_paths():
"""Initialize and validate all required paths"""
try:
onedrive_root = find_onedrive_root()
ob_root = find_obsidian_vault(onedrive_root)
except FileNotFoundError as e:
print(f"Error: {e}")
print("Falling back to default path...")
ob_root = os.path.expanduser("~/OneDrive/Notes")
# Setup paths
paths = {
"obsidian": {
"root": ob_root,
"posts": os.path.join(ob_root, CONFIG["folders"]["posts"]),
},
"hugo": {
"root": os.path.dirname(os.path.abspath(__file__)),
},
}
# Add hugo subpaths
paths["hugo"]["posts"] = os.path.join(
paths["hugo"]["root"], CONFIG["folders"]["content"], CONFIG["folders"]["posts"]
)
paths["hugo"]["images"] = os.path.join(
paths["hugo"]["root"], CONFIG["folders"]["static"], CONFIG["folders"]["images"]
)
# Create necessary directories
os.makedirs(paths["hugo"]["posts"], exist_ok=True)
os.makedirs(paths["hugo"]["images"], exist_ok=True)
return paths
def create_new_post(title, paths):
"""Create a new blog post using the papermod archetype"""
# Convert title to filename format
filename = f"{title.lower().replace(' ', '-')}.md"
print(f"Creating new post: {filename}")
try:
subprocess.run(
["hugo", "new", f"posts/{filename}"],
cwd=paths["hugo"]["root"],
check=True,
)
# Copy the new file to Obsidian posts directory
source = os.path.join(paths["hugo"]["posts"], filename)
dest = os.path.join(paths["obsidian"]["posts"], filename)
shutil.copy2(source, dest)
print(f"✅ Created {filename}")
return True
except subprocess.CalledProcessError as e:
print(f"Error creating post: {e}")
return False
def get_local_timezone():
"""Get the local timezone name"""
return datetime.now().astimezone().tzinfo
def format_date(date_str):
"""Format date string to Hugo compatible format with local timezone"""
try:
# Remove ordinal indicators from the date string
date_str = date_str.strip('"')
date_str = re.sub(r"(\d)(st|nd|rd|th)", r"\1", date_str)
try:
# Parse Obsidian's specific format
date_obj = datetime.strptime(date_str, "%B %d %Y, %I:%M %p")
local_tz = get_local_timezone()
date_obj = date_obj.replace(tzinfo=local_tz)
return date_obj.isoformat()
except ValueError:
# Fallback formats if needed
for fmt in [
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
]:
try:
date_obj = datetime.strptime(date_str, fmt)
local_tz = get_local_timezone()
date_obj = date_obj.replace(tzinfo=local_tz)
return date_obj.isoformat()
except ValueError:
continue
raise ValueError(f"Could not parse date: {date_str}")
except Exception as e:
print(f"Warning: Date parsing error - {e}")
return date_str
def sync_posts(paths):
"""Sync posts from Obsidian to Hugo and merge frontmatter"""
try:
# Sync the files
subprocess.run(
[
"rsync",
"-av",
"--delete",
f"{paths['obsidian']['posts']}/",
f"{paths['hugo']['posts']}/",
],
check=True,
)
# Process each markdown file
for filename in os.listdir(paths["hugo"]["posts"]):
if not filename.endswith(".md"):
continue
filepath = os.path.join(paths["hugo"]["posts"], filename)
with open(filepath, "r") as file:
content = file.read()
# Split content into frontmatter and body
parts = content.split("---", 2)
if len(parts) >= 3: # Has frontmatter
frontmatter = parts[1]
body = parts[2]
# Parse existing frontmatter
fields = {}
for line in frontmatter.strip().split("\n"):
if ":" in line:
key, value = line.split(":", 1)
key = key.strip()
value = value.strip()
# Skip date created
if key == "date created":
continue
# Convert date modified to date with proper format
if key == "date modified" or key == "date":
key = "date"
value = format_date(value)
fields[key] = value
# Create new frontmatter with just title and date
new_frontmatter = "---\n"
if "title" in fields:
new_frontmatter += f"title: {fields['title']}\n"
if "date" in fields:
new_frontmatter += f"date: {fields['date']}\n"
new_frontmatter += "---"
content = f"{new_frontmatter}{body}"
else: # No frontmatter
content = "---\n---\n\n" + content
# Write the modified content back
with open(filepath, "w") as file:
file.write(content)
except subprocess.CalledProcessError as e:
print(f"Error during rsync: {e}")
if not os.path.exists(paths["obsidian"]["posts"]):
print(f"Source directory {paths['obsidian']['posts']} does not exist!")
return False
return True
def process_images(paths):
"""Process and copy images from posts"""
wiki_pattern = r"!\[\[([^]]*\.(?:png|jpe?g|webp))\]\]"
for filename in os.listdir(paths["hugo"]["posts"]):
if not filename.endswith(".md"):
continue
filepath = os.path.join(paths["hugo"]["posts"], filename)
with open(filepath, "r") as file:
content = file.read()
wiki_images = re.findall(wiki_pattern, content, re.IGNORECASE)
if not wiki_images:
continue
print(f"\nProcessing {filename}")
print(f"Found {len(wiki_images)} images:")
for idx, rel_path in enumerate(wiki_images, 1):
source = os.path.join(paths["obsidian"]["root"], rel_path)
image_filename = os.path.basename(rel_path)
# Convert wikilink to markdown
repo = CONFIG["repo"]
new_link = (
# f"![](/{repo['name']}/images/{image_filename.replace(' ', '%20')})"
f"![](/images/{image_filename.replace(' ', '%20')})"
)
content = content.replace(f"![[{rel_path}]]", new_link)
if os.path.exists(source):
shutil.copy(source, paths["hugo"]["images"])
print(f" ✓ [{idx}] {image_filename}")
else:
print(
f" ✗ [{idx}] {image_filename} (not found in {os.path.dirname(rel_path)})"
)
with open(filepath, "w") as file:
file.write(content)
def update_blog(paths):
"""Build and deploy blog updates"""
# Clean public folder
subprocess.run(
["rm", "-rf", CONFIG["folders"]["public"]],
cwd=paths["hugo"]["root"],
check=True,
)
# Build and push
subprocess.run(["hugo"], check=True)
subprocess.run(["git", "add", "."], cwd=paths["hugo"]["root"], check=True)
subprocess.run(
["git", "commit", "-m", "Updated blog"], cwd=paths["hugo"]["root"], check=True
)
subprocess.run(["git", "push"], cwd=paths["hugo"]["root"], check=True)
def main():
# Setup
paths = setup_paths()
# Sync and process
if not sync_posts(paths):
return
process_images(paths)
print("\nFinished Processing Images!")
# Update and deploy
update_blog(paths)
print("\nBlog Updated and Changes Committed!")
# Check deployment
try:
subprocess.run(["gh", "--version"], check=True, capture_output=True)
wait_for_workflow()
except FileNotFoundError:
print(
"\nWarning: GitHub CLI (gh) not found. Please install it to track workflow status."
)
print("Install with: brew install gh")
# Open blog
repo = CONFIG["repo"]
# blog_url = f"https://{repo['owner']}.github.io/{repo['name']}/"
blog_url = f"https://blog.apotenza.com"
subprocess.run(["open", blog_url], check=True)
if __name__ == "__main__":
main()