-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmdsync.py
More file actions
executable file
·4642 lines (3792 loc) · 193 KB
/
mdsync.py
File metadata and controls
executable file
·4642 lines (3792 loc) · 193 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
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3.11
"""
mdsync - Sync between Google Docs and Markdown files
"""
import os
import sys
import re
import argparse
import json
import yaml
import difflib
import uuid
import time
from pathlib import Path
from typing import Optional, Tuple
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
import io
# Confluence imports
try:
from atlassian import Confluence
CONFLUENCE_AVAILABLE = True
except ImportError:
CONFLUENCE_AVAILABLE = False
Confluence = None
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/documents',
'https://www.googleapis.com/auth/drive']
def find_config_file(filename: str) -> Optional[str]:
"""Find a config file in multiple possible locations."""
search_paths = [
Path.cwd() / filename, # Current directory
Path.home() / '.config' / 'mdsync' / filename, # XDG config
Path.home() / '.mdsync' / filename, # Home directory
]
for path in search_paths:
if path.exists():
return str(path)
return None
def get_credentials():
"""Get or create Google API credentials."""
creds = None
# Find token file
token_file = find_config_file('token.json')
# The file token.json stores the user's access and refresh tokens
if token_file and os.path.exists(token_file):
creds = Credentials.from_authorized_user_file(token_file, SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
# Find credentials file
credentials_file = find_config_file('credentials.json')
if not credentials_file:
print("Error: credentials.json not found!", file=sys.stderr)
print("Searched in:", file=sys.stderr)
print(" - Current directory", file=sys.stderr)
print(" - ~/.config/mdsync/", file=sys.stderr)
print(" - ~/.mdsync/", file=sys.stderr)
print("\nPlease follow the setup instructions in SETUP_GUIDE.md", file=sys.stderr)
sys.exit(1)
flow = InstalledAppFlow.from_client_secrets_file(
credentials_file, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
# Save in the same location as credentials, or current directory
if not token_file:
credentials_file = find_config_file('credentials.json')
if credentials_file:
token_file = str(Path(credentials_file).parent / 'token.json')
else:
token_file = 'token.json'
with open(token_file, 'w') as token:
token.write(creds.to_json())
return creds
def extract_doc_id(url_or_id: str) -> str:
"""Extract document ID from a Google Docs URL or return the ID if already provided."""
# If it's already just an ID (no slashes or dots), return it
if '/' not in url_or_id and '.' not in url_or_id:
return url_or_id
# Try to extract from URL
match = re.search(r'/document/d/([a-zA-Z0-9-_]+)', url_or_id)
if match:
return match.group(1)
# If no match, assume it's already an ID
return url_or_id
def is_google_doc(path: str) -> bool:
"""Check if the path is a Google Docs URL or ID."""
if not path:
return False
return ('docs.google.com' in path or
('/' not in path and '.' not in path and len(path) > 20))
def is_confluence_page(path: str) -> bool:
"""Check if the path is a Confluence page URL or ID."""
if not path:
return False
return ('atlassian.net/wiki' in path or
path.startswith('confluence:') or
(path.isdigit() and len(path) < 20)) # Confluence page IDs are numeric
def parse_confluence_destination(dest: str) -> dict:
"""Parse Confluence destination into components."""
result = {'type': None, 'space': None, 'page_id': None, 'page_title': None, 'url': None}
if dest.startswith('confluence:'):
# Format: confluence:SPACE/PAGE_ID or confluence:SPACE/Page+Title
parts = dest[11:].split('/', 1) # Remove 'confluence:' prefix
result['type'] = 'confluence'
result['space'] = parts[0] if parts else None
if len(parts) > 1:
if parts[1].isdigit():
result['page_id'] = parts[1]
else:
result['page_title'] = parts[1].replace('+', ' ')
elif 'atlassian.net/wiki' in dest:
# Parse Confluence URL
result['type'] = 'confluence'
result['url'] = dest
# Extract space and page ID from URL
import re
space_match = re.search(r'/spaces/([^/]+)', dest)
page_match = re.search(r'/pages/(\d+)', dest)
if space_match:
result['space'] = space_match.group(1)
if page_match:
result['page_id'] = page_match.group(1)
elif dest.isdigit():
# Just a page ID
result['type'] = 'confluence'
result['page_id'] = dest
return result
def get_confluence_credentials(secrets_file_path: Optional[str] = None):
"""Get Confluence credentials as a dict (for direct API calls).
Args:
secrets_file_path: Optional explicit path to secrets.yaml file
"""
# Look for Confluence credentials in multiple locations
confluence_url = os.getenv('CONFLUENCE_URL')
confluence_username = os.getenv('CONFLUENCE_USERNAME')
confluence_token = os.getenv('CONFLUENCE_API_TOKEN') or os.getenv('CONFLUENCE_TOKEN')
# Try secrets.yaml first (preferred method)
secrets_paths = []
if secrets_file_path:
# Explicit path provided
secrets_paths = [Path(secrets_file_path)]
else:
# Default search paths
secrets_paths = [
Path.cwd() / 'secrets.yaml',
Path.cwd() / 'secrets.yml',
Path.home() / '.config' / 'mdsync' / 'secrets.yaml',
Path.home() / '.mdsync' / 'secrets.yaml',
]
for secrets_path in secrets_paths:
if secrets_path.exists():
try:
with open(secrets_path, 'r') as f:
secrets = yaml.safe_load(f)
if secrets and 'confluence' in secrets:
conf = secrets['confluence']
confluence_url = confluence_url or conf.get('url')
confluence_username = confluence_username or conf.get('username')
confluence_token = confluence_token or conf.get('api_token') or conf.get('token')
break
except Exception:
pass
# Try confluence.json as fallback
if not all([confluence_url, confluence_username, confluence_token]):
config_paths = [
Path.cwd() / 'confluence.json',
Path.home() / '.config' / 'mdsync' / 'confluence.json',
Path.home() / '.mdsync' / 'confluence.json',
]
for config_path in config_paths:
if config_path.exists():
try:
with open(config_path, 'r') as f:
config = json.load(f)
confluence_url = confluence_url or config.get('url')
confluence_username = confluence_username or config.get('username')
confluence_token = confluence_token or config.get('api_token') or config.get('token')
break
except Exception:
pass
if not all([confluence_url, confluence_username, confluence_token]):
return None
return {
'url': confluence_url,
'username': confluence_username,
'api_token': confluence_token
}
def get_confluence_client(secrets_file_path: Optional[str] = None):
"""Get Confluence API client from secrets.yaml, environment variables, or config.
Args:
secrets_file_path: Optional explicit path to secrets.yaml file
"""
if not CONFLUENCE_AVAILABLE:
print("Error: Confluence support not available. Install with: pip install atlassian-python-api", file=sys.stderr)
sys.exit(1)
# Look for Confluence credentials in multiple locations
confluence_url = os.getenv('CONFLUENCE_URL')
confluence_username = os.getenv('CONFLUENCE_USERNAME')
confluence_token = os.getenv('CONFLUENCE_API_TOKEN') or os.getenv('CONFLUENCE_TOKEN')
# Try secrets.yaml first (preferred method)
secrets_paths = []
if secrets_file_path:
# Explicit path provided
secrets_paths = [Path(secrets_file_path)]
else:
# Default search paths
secrets_paths = [
Path.cwd() / 'secrets.yaml',
Path.cwd() / 'secrets.yml',
Path.home() / '.config' / 'mdsync' / 'secrets.yaml',
Path.home() / '.mdsync' / 'secrets.yaml',
]
for secrets_path in secrets_paths:
if secrets_path.exists():
try:
with open(secrets_path, 'r') as f:
secrets = yaml.safe_load(f)
if secrets and 'confluence' in secrets:
conf = secrets['confluence']
confluence_url = confluence_url or conf.get('url')
confluence_username = confluence_username or conf.get('username')
confluence_token = confluence_token or conf.get('api_token') or conf.get('token')
break
except Exception:
pass
# Fallback to JSON config files
if not all([confluence_url, confluence_username, confluence_token]):
config_paths = [
Path.home() / '.config' / 'mdsync' / 'confluence.json',
Path.home() / '.mdsync' / 'confluence.json',
Path.cwd() / 'confluence.json',
]
for config_path in config_paths:
if config_path.exists():
try:
with open(config_path, 'r') as f:
config = json.load(f)
confluence_url = confluence_url or config.get('url')
confluence_username = confluence_username or config.get('username')
confluence_token = confluence_token or config.get('token')
break
except Exception:
pass
if not all([confluence_url, confluence_username, confluence_token]):
print("Error: Confluence credentials not found!", file=sys.stderr)
print("\nOption 1: Create secrets.yaml in current directory:", file=sys.stderr)
print(" confluence:", file=sys.stderr)
print(" url: https://yoursite.atlassian.net", file=sys.stderr)
print(" username: your-email@domain.com", file=sys.stderr)
print(" api_token: your-api-token", file=sys.stderr)
print("\nOption 2: Set environment variables:", file=sys.stderr)
print(" CONFLUENCE_URL=https://yoursite.atlassian.net", file=sys.stderr)
print(" CONFLUENCE_USERNAME=your-email@domain.com", file=sys.stderr)
print(" CONFLUENCE_API_TOKEN=your-api-token", file=sys.stderr)
print("\nSee secrets.yaml.example for template", file=sys.stderr)
sys.exit(1)
return Confluence(
url=confluence_url,
username=confluence_username,
password=confluence_token,
cloud=True
)
def markdown_to_confluence_storage(markdown_content: str) -> str:
"""Convert markdown to Confluence storage format using proper HTML conversion.
Uses the markdown library with extensions for better formatting support,
similar to the md2confluence project approach.
"""
import markdown
# Convert markdown to HTML with extensions (similar to md2confluence)
html_content = markdown.markdown(
markdown_content,
extensions=[
'tables', # Support for tables
'fenced_code', # Support for ```code blocks```
'codehilite', # Syntax highlighting
'nl2br', # Convert newlines to <br>
'sane_lists' # Better list handling
]
)
# Convert to Confluence Storage Format
confluence_content = html_content
# Generate Confluence-compatible anchor IDs from heading text
# Confluence auto-generates anchors from heading text, so we need to match that format
def generate_confluence_anchor(heading_text):
"""Generate a Confluence-compatible anchor ID from heading text.
Confluence generates anchors by:
1. Preserving original case (NOT lowercasing)
2. Replacing spaces with hyphens
3. URL encoding special characters (:, [, ], etc.)
"""
import urllib.parse
# Handle None case
if heading_text is None:
return ''
# Confluence preserves case and uses URL encoding
anchor = heading_text.strip()
# Remove markdown formatting but preserve the text structure
anchor = re.sub(r'\*\*([^*]+)\*\*', r'\1', anchor) # Remove bold
anchor = re.sub(r'\*([^*]+)\*', r'\1', anchor) # Remove italic
anchor = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', anchor) # Remove links
# Unescape escaped brackets (from markdown like \[IN PROGRESS\])
anchor = re.sub(r'\\\[', '[', anchor) # Match \ followed by [
anchor = re.sub(r'\\\]', ']', anchor) # Match \ followed by ]
# Replace spaces with hyphens (but keep case)
anchor = re.sub(r'\s+', '-', anchor)
# URL encode (Confluence uses URL encoding for anchors)
# Don't encode hyphens, they're part of the anchor format
return urllib.parse.quote(anchor, safe='-')
# Update heading IDs to match Confluence's auto-generated format
def fix_heading_anchor(match):
heading_tag = match.group(1)
existing_id = match.group(2) if match.group(2) else None
heading_text = match.group(3) # The actual heading text content
# Handle None case (shouldn't happen, but be safe)
if heading_text is None:
return match.group(0) # Return original if something's wrong
# Remove markdown anchor syntax {#anchor} from heading text if present
# This is formatting noise from Google Docs that shouldn't be displayed
clean_heading_text = re.sub(r'\s*\{#[^}]+\}\s*$', '', heading_text).strip()
# Generate anchor from CLEAN heading text (without the {#...} part)
anchor_id = generate_confluence_anchor(clean_heading_text)
# Use the clean heading text for display
return f'<h{heading_tag} id="{anchor_id}">{clean_heading_text}</h{heading_tag}>'
# Update headings to have Confluence-compatible anchor IDs
confluence_content = re.sub(
r'<h([1-6])(?:\s+id="([^"]*)")?>(.*?)</h\1>',
fix_heading_anchor,
confluence_content
)
# Map of markdown anchor names to Confluence anchors (for TOC links)
# We'll build this by scanning the markdown content before conversion
anchor_to_heading_map = {}
heading_pattern = r'^#{1,6}\s+(.+?)(?:\s+\{#([^}]+)\})?$'
for line in markdown_content.split('\n'):
match = re.match(heading_pattern, line)
if match:
heading_text = match.group(1).strip()
explicit_anchor = match.group(2) if match.group(2) else None
# Remove markdown anchor syntax {#anchor} from heading text if present
# This is formatting noise that shouldn't be part of the anchor generation
clean_heading = re.sub(r'\s*\{#[^}]+\}\s*$', '', heading_text).strip()
# Remove markdown link syntax from heading text for anchor generation
clean_heading = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', clean_heading) # Remove links
clean_heading = re.sub(r'\\\[([^\]]+)\\\]', r'[\1]', clean_heading) # Unescape brackets
# Generate anchor from CLEAN heading text (Confluence's way - without the {#...} part)
confluence_anchor = generate_confluence_anchor(clean_heading)
# Map explicit anchor (if present) to the Confluence-generated anchor
if explicit_anchor:
anchor_to_heading_map[explicit_anchor] = confluence_anchor
# Also map variations of the heading text to the anchor
anchor_to_heading_map[clean_heading.lower()] = confluence_anchor
anchor_to_heading_map[heading_text.lower()] = confluence_anchor
# Update anchor links to match Confluence's generated anchors
def fix_anchor_link(match):
# Regex already extracted the anchor name (without #) from href="#anchor"
anchor_name = match.group(1) # This is already without the #
text = match.group(2)
# Try to find the matching Confluence anchor
# First check if we have a mapping for this anchor
if anchor_name in anchor_to_heading_map:
confluence_anchor = anchor_to_heading_map[anchor_name]
else:
# Generate anchor from the link text (fallback)
confluence_anchor = generate_confluence_anchor(text)
return f'<a href="#{confluence_anchor}">{text}</a>'
# Fix anchor links before the general link conversion
# This regex matches <a href="#anchor">text</a> and extracts anchor (without #) and text
confluence_content = re.sub(
r'<a href="#([^"]+)">(.*?)</a>',
fix_anchor_link,
confluence_content
)
# Convert code blocks to simpler format (remove codehilite divs)
confluence_content = re.sub(
r'<div class="codehilite"><pre><span></span><code[^>]*>(.*?)</code></pre></div>',
r'<pre><code>\1</code></pre>',
confluence_content,
flags=re.DOTALL
)
# Remove syntax highlighting spans from code blocks
confluence_content = re.sub(
r'<span class="[^"]*">([^<]*)</span>',
r'\1',
confluence_content
)
# Convert special syntax for Confluence macros (:::note, :::warning, etc.)
def convert_special_macro(match):
macro_type = match.group(1).lower()
title = match.group(2) if match.group(2) else ""
content = match.group(3).strip()
# Remove any <p> tags that markdown might have added
content = re.sub(r'^<p>|</p>$', '', content)
# Handle success type - use info macro with checkmark emoji
if macro_type == 'success':
macro_type = 'info'
if not title:
title = "✅ Success"
elif not title.startswith('✅'):
title = f"✅ {title}"
# Build the macro with optional title
macro_params = ""
if title:
macro_params = f' <ac:parameter ac:name="title">{title}</ac:parameter>\n'
return f'''<ac:structured-macro ac:name="{macro_type}" ac:schema-version="1" ac:macro-id="{uuid.uuid4()}">
{macro_params} <ac:rich-text-body>
<p>{content}</p>
</ac:rich-text-body>
</ac:structured-macro>'''
# Convert :::type [title] content ::: syntax
confluence_content = re.sub(
r':::(\w+)(?:\s+([^\n]+))?\n(.*?)\n:::',
convert_special_macro,
confluence_content,
flags=re.DOTALL
)
# Convert block quotes to Confluence note macros
def convert_blockquote_to_note(match):
content = match.group(1).strip()
# Remove any <p> tags that markdown might have added
content = re.sub(r'^<p>|</p>$', '', content)
return f'''<ac:structured-macro ac:name="note">
<ac:rich-text-body>
<p>{content}</p>
</ac:rich-text-body>
</ac:structured-macro>'''
confluence_content = re.sub(
r'<blockquote>(.*?)</blockquote>',
convert_blockquote_to_note,
confluence_content,
flags=re.DOTALL
)
# Convert links - distinguish between anchor links, external URLs, and internal pages
def convert_link(match):
href = match.group(1)
text = match.group(2)
# Anchor link (starts with #) - same page anchor
if href.startswith('#'):
anchor_name = href[1:] # Remove the #
# For same-page anchors, use Confluence anchor format
# Note: Confluence will auto-generate anchors from headings, but we preserve explicit ones
return f'<a href="#{anchor_name}">{text}</a>'
# External URL (starts with http/https)
elif href.startswith(('http://', 'https://', 'mailto:')):
return f'<a href="{href}">{text}</a>'
# Internal page link - convert to Confluence format
else:
return f'<ac:link><ri:page ri:content-title="{href}"/><ac:link-body>{text}</ac:link-body></ac:link>'
confluence_content = re.sub(
r'<a href="([^"]+)">(.*?)</a>',
convert_link,
confluence_content
)
return confluence_content
def export_confluence_to_markdown(page_id: str, confluence, output_path: str = None) -> str:
"""Export a Confluence page to Markdown format using html2text for better conversion."""
try:
import html2text
from bs4 import BeautifulSoup
# Get page content
page = confluence.get_page_by_id(page_id, expand='body.storage')
if not page:
print(f"Error: Page {page_id} not found", file=sys.stderr)
sys.exit(1)
# Get the storage format content
storage_content = page['body']['storage']['value']
# Pre-process Confluence-specific tags before conversion
soup = BeautifulSoup(storage_content, 'html.parser')
# Convert Confluence internal links to regular HTML links
for link in soup.find_all('ac:link'):
page_ref = link.find('ri:page')
if page_ref and page_ref.get('ri:content-title'):
page_title = page_ref.get('ri:content-title')
link_body = link.find('ac:link-body')
link_text = link_body.get_text() if link_body else page_title
# Create a simple markdown-style link
new_link = soup.new_tag('a', href=page_title)
new_link.string = link_text
link.replace_with(new_link)
# Convert back to HTML string
cleaned_html = str(soup)
# Use html2text for proper HTML to Markdown conversion
h = html2text.HTML2Text()
h.body_width = 0 # Don't wrap lines
h.ignore_links = False
h.ignore_images = False
h.ignore_emphasis = False
h.skip_internal_links = False
h.inline_links = True
h.protect_links = True
h.unicode_snob = True # Use unicode instead of HTML entities
markdown_content = h.handle(cleaned_html)
# If output path provided, add frontmatter with confluence_url
if output_path:
space_key = page.get('space', {}).get('key', '')
# Remove /wiki from the end of confluence.url if present
base_url = confluence.url.rstrip('/')
if base_url.endswith('/wiki'):
base_url = base_url[:-5] # Remove '/wiki'
confluence_url = f"{base_url}/wiki/spaces/{space_key}/pages/{page_id}"
# Check if content already has frontmatter
if markdown_content.startswith('---'):
# Parse existing frontmatter and add confluence_url
try:
import frontmatter
post = frontmatter.loads(markdown_content)
post.metadata['confluence_url'] = confluence_url
frontmatter_content = frontmatter.dumps(post)
except Exception:
# Fallback: prepend frontmatter
frontmatter_content = f"---\nconfluence_url: {confluence_url}\n---\n\n{markdown_content}"
else:
# Add frontmatter to the content
frontmatter_content = f"---\nconfluence_url: {confluence_url}\n---\n\n{markdown_content}"
# Write to file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(frontmatter_content)
return frontmatter_content
else:
return markdown_content.strip()
except Exception as error:
print(f"An error occurred: {error}", file=sys.stderr)
sys.exit(1)
def import_markdown_to_confluence(markdown_path: str, page_id: str, confluence, quiet: bool = False):
"""Import a Markdown file to an existing Confluence page."""
try:
# Read the markdown file
with open(markdown_path, 'r', encoding='utf-8') as f:
markdown_content = f.read()
# Extract metadata from frontmatter
frontmatter = extract_frontmatter_metadata(markdown_content)
frontmatter_labels = frontmatter['labels']
# Get existing page to preserve space and version
page = confluence.get_page_by_id(page_id, expand='version,space')
if not page:
print(f"Error: Page {page_id} not found", file=sys.stderr)
sys.exit(1)
space_key = page.get('space', {}).get('key', '')
title = page.get('title', '')
# Generate Confluence URL
# Remove /wiki from the end of confluence.url if present
base_url = confluence.url.rstrip('/')
if base_url.endswith('/wiki'):
base_url = base_url[:-5] # Remove '/wiki'
confluence_url = f"{base_url}/wiki/spaces/{space_key}/pages/{page_id}"
# Resolve internal markdown links to Confluence URLs
base_dir = os.path.dirname(os.path.abspath(markdown_path))
resolved_content = resolve_markdown_links_to_confluence(markdown_content, base_dir)
# Strip frontmatter and convert markdown to Confluence storage format
content_for_confluence = strip_frontmatter_for_remote_sync(resolved_content)
storage_content = markdown_to_confluence_storage(content_for_confluence)
# Update the page
confluence.update_page(
page_id=page_id,
title=title,
body=storage_content,
parent_id=page.get('ancestors', [{}])[-1].get('id') if page.get('ancestors') else None,
type='page',
representation='storage'
)
# Update frontmatter with Confluence URL
update_frontmatter_confluence_url(markdown_path, confluence_url)
# Set labels authoritatively if any in frontmatter
if frontmatter_labels:
confluence_creds = get_confluence_credentials()
if confluence_creds:
set_confluence_labels(
page_id,
frontmatter_labels,
confluence_creds['url'],
confluence_creds['username'],
confluence_creds['api_token']
)
if not quiet:
print(f"✓ Successfully updated Confluence page: {title}")
print(f" Page ID: {page_id}")
print(f" Space: {space_key}")
print(f" URL: {confluence_url}")
if frontmatter_labels:
print(f" Labels: {', '.join(frontmatter_labels)}")
print(f" Updated frontmatter in {markdown_path}")
except FileNotFoundError:
print(f"Error: Markdown file not found: {markdown_path}", file=sys.stderr)
sys.exit(1)
except Exception as error:
print(f"An error occurred: {error}", file=sys.stderr)
sys.exit(1)
def extract_frontmatter_metadata(markdown_content: str) -> dict:
"""Extract metadata from markdown frontmatter (title, labels, gdoc_url, confluence_url, batch, etc.)."""
try:
import frontmatter
post = frontmatter.loads(markdown_content)
return {
'title': post.metadata.get('title'),
'labels': post.metadata.get('labels', []),
'parent': post.metadata.get('parent'),
'gdoc_url': post.metadata.get('gdoc_url'),
'confluence_url': post.metadata.get('confluence_url'),
'batch': post.metadata.get('batch'),
'gdoc_created': post.metadata.get('gdoc_created'),
'gdoc_modified': post.metadata.get('gdoc_modified'),
'confluence_created': post.metadata.get('confluence_created'),
'confluence_modified': post.metadata.get('confluence_modified'),
}
except Exception:
return {
'title': None,
'labels': [],
'parent': None,
'gdoc_url': None,
'confluence_url': None,
'batch': None,
'gdoc_created': None,
'gdoc_modified': None,
'confluence_created': None,
'confluence_modified': None,
}
def update_frontmatter_metadata(content: str, metadata: dict) -> str:
"""Update frontmatter metadata in markdown content."""
try:
import frontmatter
post = frontmatter.loads(content)
# Update metadata
for key, value in metadata.items():
post.metadata[key] = value
# Return updated content
return frontmatter.dumps(post)
except Exception:
# If frontmatter library fails, fall back to manual YAML handling
if not content.startswith('---'):
# No existing frontmatter, add it
frontmatter_yaml = yaml.dump(metadata, default_flow_style=False, sort_keys=False)
return f"---\n{frontmatter_yaml}---\n\n{content}"
try:
# Find the end of existing frontmatter
end_marker = content.find('---', 3)
if end_marker == -1:
# Malformed frontmatter, replace it
frontmatter_yaml = yaml.dump(metadata, default_flow_style=False, sort_keys=False)
return f"---\n{frontmatter_yaml}---\n\n{content}"
# Extract content after frontmatter
content_after_frontmatter = content[end_marker + 3:].lstrip('\n')
# Create new frontmatter
frontmatter_yaml = yaml.dump(metadata, default_flow_style=False, sort_keys=False)
return f"---\n{frontmatter_yaml}---\n\n{content_after_frontmatter}"
except Exception:
# If anything fails, just add new frontmatter
frontmatter_yaml = yaml.dump(metadata, default_flow_style=False, sort_keys=False)
return f"---\n{frontmatter_yaml}---\n\n{content}"
def update_frontmatter_gdoc_url(markdown_path: str, gdoc_url: str) -> bool:
"""Update the gdoc_url and sync date in markdown frontmatter."""
try:
import frontmatter
from datetime import datetime
# Read current content
with open(markdown_path, 'r', encoding='utf-8') as f:
content = f.read()
# Parse frontmatter
post = frontmatter.loads(content)
# Update gdoc_url and sync dates
post.metadata['gdoc_url'] = gdoc_url
current_time = datetime.now().isoformat()
# Set created date if this is the first time we're adding a gdoc_url
if 'gdoc_created' not in post.metadata:
post.metadata['gdoc_created'] = current_time
# Always update modified date
post.metadata['gdoc_modified'] = current_time
# Write back
with open(markdown_path, 'w', encoding='utf-8') as f:
f.write(frontmatter.dumps(post))
return True
except Exception as e:
print(f"Warning: Could not update frontmatter in {markdown_path}: {e}", file=sys.stderr)
return False
def update_frontmatter_confluence_url(markdown_path: str, confluence_url: str) -> bool:
"""Update the confluence_url and sync dates in markdown frontmatter."""
try:
import frontmatter
from datetime import datetime
# Read current content
with open(markdown_path, 'r', encoding='utf-8') as f:
content = f.read()
# Parse frontmatter
post = frontmatter.loads(content)
# Update confluence_url and sync dates
post.metadata['confluence_url'] = confluence_url
current_time = datetime.now().isoformat()
# Set created date if this is the first time we're adding a confluence_url
if 'confluence_created' not in post.metadata:
post.metadata['confluence_created'] = current_time
# Always update modified date
post.metadata['confluence_modified'] = current_time
# Write back
with open(markdown_path, 'w', encoding='utf-8') as f:
f.write(frontmatter.dumps(post))
return True
except Exception as e:
print(f"Warning: Could not update frontmatter in {markdown_path}: {e}", file=sys.stderr)
return False
def resolve_markdown_links_to_confluence(markdown_content: str, base_dir: str = None) -> str:
"""Resolve internal markdown links to Confluence URLs based on frontmatter."""
if not base_dir:
base_dir = os.getcwd()
# Pattern to match [text](file.md) links
link_pattern = r'\[([^\]]+)\]\(([^)]+\.md)\)'
def replace_link(match):
link_text = match.group(1)
file_path = match.group(2)
# Convert relative path to absolute
if not os.path.isabs(file_path):
file_path = os.path.join(base_dir, file_path)
# Check if the referenced file exists and has confluence_url in frontmatter
if os.path.exists(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Extract confluence_url from frontmatter
metadata = extract_frontmatter_metadata(content)
confluence_url = metadata.get('confluence_url')
if confluence_url:
return f'[{link_text}]({confluence_url})'
except Exception:
pass
# If no confluence_url found, return original link
return match.group(0)
# Replace all markdown links
return re.sub(link_pattern, replace_link, markdown_content)
def check_gdoc_frozen_status(doc_id: str, creds) -> bool:
"""Check if a Google Doc is frozen (locked) at runtime."""
try:
# Use the existing check_lock_status function
drive_service = build('drive', 'v3', credentials=creds)
# Get file metadata
file_metadata = drive_service.files().get(
fileId=doc_id,
fields='contentRestrictions'
).execute()
# Check if there are content restrictions
restrictions = file_metadata.get('contentRestrictions', [])
if restrictions:
for restriction in restrictions:
if restriction.get('readOnly') == True:
return True
return False
except Exception:
# If we can't check, assume not frozen
return False
def check_confluence_frozen_status(page_id: str, confluence) -> bool:
"""Check if a Confluence page is frozen (locked) at runtime."""
try:
# Get page restrictions
confluence_creds = get_confluence_credentials()
if not confluence_creds:
return False
# Use the existing check_confluence_lock_status logic
import requests
url = f"{confluence_creds['url']}/rest/api/content/{page_id}/restriction"
auth = (confluence_creds['username'], confluence_creds['api_token'])
response = requests.get(url, auth=auth)
if response.status_code == 200:
restrictions = response.json()
# Check if there are UPDATE restrictions
for restriction in restrictions.get('restrictions', {}).get('update', {}).get('restrictions', []):
if restriction.get('type') == 'user' or restriction.get('type') == 'group':
return True
return False
except Exception:
# If we can't check, assume not frozen
return False
def extract_doc_id_from_url(url: str) -> str:
"""Extract Google Doc ID from various URL formats."""
import re
# Handle different Google Docs URL formats
patterns = [
r'/document/d/([a-zA-Z0-9-_]+)', # Standard format
r'id=([a-zA-Z0-9-_]+)', # Alternative format
r'^([a-zA-Z0-9-_]+)$' # Just the ID
]
for pattern in patterns:
match = re.search(pattern, url)
if match:
return match.group(1)
return None
def get_confluence_permissions_config(secrets_file_path: Optional[str] = None):
"""Get default permissions configuration from secrets.yaml.
Args:
secrets_file_path: Optional explicit path to secrets.yaml file
"""
secrets_paths = []
if secrets_file_path:
# Explicit path provided
secrets_paths = [Path(secrets_file_path)]
else:
# Default search paths
secrets_paths = [
Path.cwd() / 'secrets.yaml',
Path.cwd() / 'secrets.yml',
Path.home() / '.config' / 'mdsync' / 'secrets.yaml',
Path.home() / '.mdsync' / 'secrets.yaml',
]
for secrets_path in secrets_paths:
if secrets_path.exists():
try:
with open(secrets_path, 'r') as f:
secrets = yaml.safe_load(f)
if secrets and 'confluence' in secrets:
perms = secrets['confluence'].get('permissions', {})
if perms:
return perms
except Exception:
pass
return None
def lock_confluence_page(page_id: str, confluence_url: str, username: str, api_token: str,
allowed_editors: dict = None, secrets_file_path: Optional[str] = None) -> bool:
"""Lock a Confluence page by setting edit restrictions.