-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitmynotes.py
More file actions
1474 lines (1157 loc) · 61.9 KB
/
gitmynotes.py
File metadata and controls
1474 lines (1157 loc) · 61.9 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 python
## ===================================================================
## GitMyNotes - LICENSE AND CREDITS
## This app/collection of scripts at https://github.com/mariochampion/gitmynotes
## released under the GNU Affero General Public License v3.0
##
##
## GitMyNotes scripts crafted and copyright 2025 by mario champion (mariochampion.com)
##
## please open issues and pull requests and comments
## thanks and always remember: this robot loves you.
## boop boop!!!
## ===================================================================
#### USING THIS SCRIPT
## Export up to 10 notes from a specific folder
# python gitmynotes.py --folder="somefolder" --max-notes=10
## Export all notes from a specific folder
# python gitmynotes.py --folder="somefolder"
## Specify to restore notes folder even if not emptied
# python gitmynotes.py --folder-name="somefolder" --max-notes=10 --restore=always
## go crazy and specify nothing, to get all the defaults!
# python gitmynotes.py
import subprocess
import os, sys
import argparse
import math
import csv
import logging
from datetime import datetime
from typing import Tuple
from ruamel.yaml import YAML
from enum import Enum
class PrintLevel(Enum):
NONE = 0
RESULTS = 1
DEBUG = 2
ALL = 3
# R4 (incremental): module-level logger. setup_logging() in main() attaches a
# FileHandler at <script_dir>/gitmynotes.log so warning-/error-level events flow
# to a parseable record alongside the existing colored TTY output. Colored
# print_color() callsites are preserved as-is; logger.warning / logger.error /
# logger.exception calls are added in paired form at each warning/error site so
# non-interactive runs (Cowork routines, cron) get a structured log without
# ANSI codes. Chatty debug_print / results_print are deliberately untouched in
# this pass.
logger = logging.getLogger("gitmynotes")
#### USER CONFIGS
PRINT_LEVEL = PrintLevel.ALL
## get user configs from file ./gmn_config.yaml
def load_configs_from_file():
yaml=YAML(typ='safe') # default, if not specfied, is 'rt' (round-trip)
loaded_configs = yaml.load(open("gmn_config.yaml"))
return loaded_configs
##### Describe this function
def setup_git_repo(repo_path, DEFAULT_GITHUB_URL):
"""Initialize Git repo and set remote if not already set up"""
if not os.path.exists(os.path.join(repo_path, '.git')):
try:
subprocess.run(['git', 'init'], cwd=repo_path)
print_color(textcolor="green",msg=f"SUCCESS: GIT INIT with {repo_path}")
except:
logger.exception(f"ERROR: Did not GIT INIT {repo_path}")
print_color(textcolor="red",msg=f"ERROR: Did not GIT INIT {repo_path}")
try:
subprocess.run(['git', 'remote', 'add', 'origin', DEFAULT_GITHUB_URL], cwd=repo_path)
print_color(textcolor="green",msg=f"SUCCESS: GIT REMOTE ADD ORIGIN with {repo_path}")
except:
logger.exception(f"ERROR: Did not GIT REMOTE ADD ORIGIN with {repo_path}")
print_color(textcolor="RED",msg=f"ERROR: Did not GIT REMOTE ADD ORIGIN with {repo_path}")
try:
subprocess.run(['git', 'branch', '-m', 'main'], cwd=repo_path)
print_color(textcolor="green",msg=f"SUCCESS: GIT BRANCH -M MAIN with {repo_path}")
except:
logger.exception(f"ERROR: GIT BRANCH -M MAIN with {repo_path}")
print_color(textcolor="red",msg=f"ERROR: GIT BRANCH -M MAIN with {repo_path}")
# Add this to handle remote repository state
try:
subprocess.run(['git', 'pull', 'origin', 'main'], cwd=repo_path)
print_color(textcolor="green",msg=f"Remote content pulled")
except:
logger.warning(f"No remote content to pull from {repo_path}")
print_color(textcolor="magenta",msg=f"No remote content to pull")
##### Describe this function
def export_notes_to_markdown(DEFAULT_CURRENTNOTE_FILE, export_path, notes_account, folder_name=None, max_notes=None, wrapper_dir=None):
"""Export Notes using applescript/osascript with folder and count limits.
notes_account scopes every Notes lookup (folder + iteration) to the specified
account (e.g. 'iCloud', 'On My Mac'). Threaded through from --notes-account /
DEFAULT_NOTES_ACCOUNT (R6).
"""
## tell the people some information
if (max_notes > 0 and folder_name !="" and wrapper_dir !=""):
print_color(textcolor="white",msg=f"Starting export of {max_notes} Notes from '{folder_name}' into '{wrapper_dir}/{folder_name}'...")
elif (max_notes > 0 and folder_name !="" and wrapper_dir==None):
print_color(textcolor="white",msg=f"Starting export of {max_notes} Notes from '{folder_name}'...")
elif (max_notes > 0 and folder_name==None and wrapper_dir==None):
print_color(textcolor="white",msg=f"Starting export of {max_notes} Notes...")
elif (max_notes==None and folder_name==None and wrapper_dir==None):
print_color(textcolor="white",msg=f"Starting export of all Notes...")
# Escape quotes in the account name for AppleScript (R6)
notes_account_escaped = notes_account.replace('"', '\\"')
applescript = f'''
tell application "Notes"
set targetAccount to "{notes_account_escaped}"
tell account targetAccount
if length of "{folder_name if folder_name else ''}" > 0 then
try
set targetFolder to folder "{folder_name}"
set allNotes to every note in targetFolder
set export_path_full to "{export_path}/{wrapper_dir}/{folder_name}"
on error
log "Folder {folder_name} not found"
return 0
end try
else
set allNotes to every note
set export_path_full to "{export_path}/{wrapper_dir}"
end if
set noteCount to (count of allNotes)
if {max_notes} > 0 then
set maxToProcess to {max_notes}
else
set maxToProcess to noteCount
end if
if maxToProcess < noteCount then
set notesToProcess to maxToProcess
else
set notesToProcess to noteCount
end if
-- B4: track empty/locked notes so caller can report them to the user.
set lockedCount to 0
set lockedMarker to "<div><i>[empty or locked note -- no content exported by GitMyNotes]</i></div>"
repeat with i from 1 to notesToProcess
set currentNote to item i of allNotes
set noteTitle to the name of currentNote
-- Write to file and track title for when unsupported note breaks.
-- B9: use the absolute path the Python caller resolved for us (config
-- value is anchored to the script dir in main() if it wasn't already
-- absolute). Otherwise osascript's shell cwd (usually the user's home)
-- and Python's cwd could disagree, leaving get_currentnote_data to
-- silently read stale data from a previous run.
do shell script "echo " & i & "++++" & quoted form of noteTitle & " > " & quoted form of "{DEFAULT_CURRENTNOTE_FILE}"
--log ("Exporting note: " & noteTitle)
set linebreaker to "\n"
set noteCreateDate to "<div><b>Creation Date:</b> " & creation date of currentNote & "<br></div>"
set noteModDate to "<div><b>Modification Date:</b> " & modification date of currentNote & "<br></div>"
-- B4: fetching `body of` on a locked/password-protected note returns "" (not
-- an error). Wrap in try as a belt-and-suspenders guard anyway, and substitute
-- a stub marker for any empty body so the committed .md is self-explanatory
-- instead of silently mostly-empty.
try
set noteContent to the body of currentNote
on error
set noteContent to ""
end try
if noteContent is "" then
set noteContent to lockedMarker
set lockedCount to lockedCount + 1
end if
-- Clean the title for use as filename
set cleanTitle to do shell script "echo " & quoted form of noteTitle & " | sed 's/[^a-zA-Z0-9.]/-/g' | tr '[:upper:]' '[:lower:]'"
set fileName to cleanTitle & ".md"
-- Write to file
do shell script "echo " & quoted form of noteCreateDate & quoted form of linebreaker & quoted form of noteModDate & quoted form of linebreaker & quoted form of noteContent & " > " & quoted form of export_path_full & "/" & fileName
end repeat
-- B4: compound return value so Python can report locked count without needing a
-- side-channel file or stderr (stderr would trip the B1 "type 100002" branch).
return (notesToProcess as string) & "|" & (lockedCount as string)
end tell
end tell
'''
result = subprocess.run(['osascript', '-e', applescript], capture_output=True, text=True)
if result.stdout:
results_print(f"EXPORT NOTES stdout: {result.stdout}")
if result.stderr:
results_print(f"Error in EXPORT NOTES:")
results_print(f"{result.stderr}")
### LOOK FOR ERROR OF UNSPPORTED (usually image) IN NOTE,
### AND MOVE THIS TO <foldername>_UNSUPPORTED
searchstring = "type 100002"
if searchstring in result.stderr:
# currentnote.txt is written by AppleScript immediately before each note's
# export, so its 1-based index points at the failing note. Notes 1..(i-1)
# were already exported successfully to disk -- we must return that count
# so the caller commits + audits + moves them. Returning 0 here would
# orphan those files on disk with no audit row and leave the originals in
# the source folder, creating duplicates on the next run (the "zombie
# exports" bug, B1).
noteCount, noteTitle = get_currentnote_data(DEFAULT_CURRENTNOTE_FILE)
print(f"{searchstring} is present for note '{noteTitle}'.")
folder_dest = folder_name + "_unsupported"
move_one_note(noteTitle, folder_name, folder_dest, notes_account, create=True)
goodnotes = noteCount - 1
logger.warning(
f"Unsupported note '{noteTitle}' (folder '{folder_name}', index {noteCount}) aborted batch; "
f"exported {goodnotes} note(s) before the failure."
)
print_color(textcolor="cyan", msg=f"Exported {goodnotes} note(s) successfully before hitting unsupported content; continuing with those.")
return goodnotes
else:
debug_print(f"{searchstring} is not present.")
return 0
# B4: stdout is a compound "exported|lockedCount" string (see AppleScript `return`).
# The `type 100002` branch above still returns a plain int directly, so this parser
# only runs on the success path.
stdout_val = result.stdout.strip() if result.stdout else ""
if not stdout_val:
return 0
if '|' in stdout_val:
try:
exported_str, locked_str = stdout_val.split('|', 1)
exported_count = int(exported_str.strip())
locked_count = int(locked_str.strip())
except ValueError:
debug_print(f"Could not parse compound export result: {stdout_val!r}")
return 0
if locked_count > 0:
plural = "s" if locked_count != 1 else ""
logger.warning(
f"{locked_count} empty or locked note{plural} committed as stub{plural} "
f"in folder '{folder_name}' (title + dates only; no content available from Notes.app)."
)
print_color(
textcolor="yellow",
msg=f"NOTE: {locked_count} empty or locked note{plural} committed as stub{plural} (title + dates only; no content available from Notes.app).",
)
return exported_count
# Backwards-compatible fallback: plain int return (shouldn't happen post-B4 but safe).
try:
return int(stdout_val)
except ValueError:
return 0
##### Describe this function
def git_add_commit_push(repo_path, folder_name=None, wrapper_dir=None):
"""Commit changes and push to GitHub"""
# Always operate from the git root directory
result_gitadd = subprocess.run(['git', 'add', f'{wrapper_dir}'], cwd=repo_path)
if result_gitadd.returncode == 0:
print_color(textcolor="green",msg=f"Successful GIT ADD to origin/main.")
results_print(f"1 result_gitadd: {result_gitadd}")
else:
logger.error(f"GIT ADD failed (returncode={result_gitadd.returncode}) in repo '{repo_path}', wrapper_dir='{wrapper_dir}'.")
print_color(textcolor="red",msg=f"Error GIT ADD to origin/main:")
results_print(f"2 result_gitadd: {result_gitadd}")
folder_info = f"from folder '{folder_name}'" if folder_name else ""
commit_message = f"Backed up {folder_info} - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
result_gitcommit = subprocess.run(['git', 'commit', '-m', commit_message], cwd=repo_path, capture_output=True, text=True)
# Classify the commit result.
# Git returns nonzero with a "nothing to commit" message when the staging area is empty.
# This happens naturally when re-exporting notes whose content hasn't changed since the
# last backup -- the exported .md is byte-identical to what's already committed. Treat
# that case as benign (not a real error) so we still attempt the push below, which
# drains any prior unpushed commits from earlier runs.
nothing_to_commit = (
result_gitcommit.returncode != 0
and ("nothing to commit" in result_gitcommit.stdout
or "nothing added to commit" in result_gitcommit.stdout)
)
commit_ok = (result_gitcommit.returncode == 0) or nothing_to_commit
commit_print_msg = f''' - repo path: {repo_path}
- folder name:{folder_name}
- commit message:{commit_message}
'''
if result_gitcommit.returncode == 0:
print_color(textcolor="green",msg=f"Successful GIT COMMIT to origin/main.")
print_color(textcolor="white",msg=f"{commit_print_msg}")
elif nothing_to_commit:
print_color(textcolor="cyan",msg=f"No changes to commit -- note content is identical to what's already in git. (Normal when re-exporting unchanged notes.)")
print_color(textcolor="white",msg=f"{commit_print_msg}")
else:
logger.error(
f"GIT COMMIT failed (returncode={result_gitcommit.returncode}) in repo '{repo_path}'. "
f"folder='{folder_name}'. stdout={result_gitcommit.stdout!r} stderr={result_gitcommit.stderr!r}"
)
print_color(textcolor="red",msg=f"Error GIT COMMIT to origin/main:")
print_color(textcolor="white",msg=f"{commit_print_msg}")
results_print(f"result_gitcommit: {result_gitcommit}")
if commit_ok:
# Try to pull and rebase before pushing
try:
subprocess.run(['git', 'pull', '--rebase', 'origin', 'main'], cwd=repo_path, capture_output=True, text=True)
except:
logger.warning(f"git pull --rebase failed before push in repo '{repo_path}'; continuing to push.")
print_color(textcolor="magenta",msg=f"No remote changes to pull")
result_push = subprocess.run(['git', 'push', 'origin', 'main'], cwd=repo_path, capture_output=True, text=True)
if result_push.returncode == 0:
# Note: git emits "Everything up-to-date" on stderr with returncode 0 when
# there's nothing new to push -- treated the same as a real push here.
print_color(textcolor="green",msg=f"Successful GIT PUSH to origin/main.")
results_print(f"1 result_push: {result_push}")
print(" ")
else:
logger.error(
f"GIT PUSH failed (returncode={result_push.returncode}) in repo '{repo_path}'. "
f"stdout={result_push.stdout!r} stderr={result_push.stderr!r}"
)
print_color(textcolor="red",msg=f"Error GIT PUSH to origin/main:")
results_print(f"2 result_push: {result_push}")
print(" ")
# Optionally, try force push if regular push fails
# result = subprocess.run(['git', 'push', '-f', 'origin', 'main'], cwd=repo_path, capture_output=True, text=True)
else:
logger.error(f"Skipping GIT PUSH due to upstream commit error in repo '{repo_path}'.")
print_color(textcolor="red",msg=f"Commit error so no GIT PUSH to origin/main:")
print(" ")
##### Describe this function
def export_notes_metadata(output_file, folder, max_notes, newline_delimiter, notes_account):
"""
Export macOS Notes metadata (title, quoted title, and modification date) to a CSV file.
Args:
output_file (str): Path to the output CSV file
folder (str): Name of the folder to export notes from. Required; the
all-folders case is guarded off at the top of main() (B10).
max_notes (int): Maximum number of notes to export (None for all notes)
newline_delimiter (str): Default newline delimiter (|||)
notes_account (str): macOS Notes account to scope the lookup to (e.g.
'iCloud', 'On My Mac'). Threaded through from --notes-account /
DEFAULT_NOTES_ACCOUNT (R6).
"""
debug_print(f"INSIDE export_notes_metadata: {output_file}, {folder}, {max_notes}, {newline_delimiter}, {notes_account}")
# Escape quotes in the account name for AppleScript (R6)
notes_account_escaped = notes_account.replace('"', '\\"')
# AppleScript to get notes information
applescript = f'''
tell application "Notes"
set targetAccount to "{notes_account_escaped}"
tell account targetAccount
set noteList to {{}}
'''
applescript += f'''
set custom_delimiter to "{newline_delimiter}"
'''
if folder:
applescript += f'''
set targetFolder to null
repeat with f in folders
if (name of f as string) is "{folder}" then
set targetFolder to f
exit repeat
end if
end repeat
set theNotes to notes of targetFolder
if targetFolder is null then
return "Folder not found"
end if
'''
else:
applescript += '''
set theNotes to notes
'''
''' Determine the number of repeats/ size of loop'''
if max_notes:
applescript += f'''
repeat with i from 1 to {max_notes}
set theNote to item i of theNotes
'''
else:
applescript += '''
repeat with theNote in theNotes
'''
applescript += '''
set noteTitle to name of theNote as string
--log ("Processing note: " & noteTitle)
-- clean noteTitle using quoted form to handle special characters
set noteTitle to do shell script ("echo " & quoted form of noteTitle & "| sed 's/,/-/g'")
-- Clean the title for use as filename, using quoted form again
set cleanTitle to do shell script ("echo " & quoted form of noteTitle & " | sed 's/[^a-zA-Z0-9.]/-/g' | tr '[:upper:]' '[:lower:]'")
set noteData to noteTitle &","& cleanTitle & ".md" &","& modification date of theNote & custom_delimiter
copy noteData to the end of noteList
end repeat
return noteList
end tell
end tell
'''
result,output = process_applescript(applescript)
results_print(f"process_applescript result: {result}")
print("-------------------")
results_print(f"process_applescript output: {output}")
# Parse the output
notes_data = []
raw_output = output.split(newline_delimiter)
raw_output = raw_output[:-1]
current_datetime = datetime.now()
for line in raw_output:
line = line.rstrip(",")
#Remove leading and trailing commas
if line.startswith(','): line = line[1:]
if line.endswith(','): line = line[:-1]
line_items = line.split(',',2)
title = line_items[0].strip()
quoted_title = line_items[1].strip()
mod_date = line_items[2].strip()
# Convert date string to datetime object and format it
try:
date_obj = datetime.strptime(mod_date, '%Y-%m-%d %H:%M:%S +0000')
formatted_date = date_obj.strftime('%Y-%m-%d %H:%M:%S')
except ValueError:
formatted_date = mod_date
print_color(textcolor="white",msg=f"Adding row to audit file: {output_file}")
print_color(textcolor="white",msg=f" - from Notes folder: '{folder}', Notes title:' {title}', ModDate: '{formatted_date}', Markdown title: '{quoted_title}', Exported Date: '{current_datetime}'")
print(" ")
notes_data.append([folder, title, formatted_date, quoted_title, current_datetime])
# Write to CSV
mode = 'a' if os.path.exists(output_file) else 'w'
with open(output_file, mode, newline='', encoding='utf-8') as f:
writer = csv.writer(f)
if mode == 'w': # Only write header for new files
writer.writerow(['Folder', 'Original Title', 'Last Modified', 'Exported Title', 'Exported Date'])
writer.writerows(notes_data)
print_color(textcolor="green",msg=f"22 SUCCESS: Exported {len(notes_data)} notes to '{output_file}'", addseparator=True)
return notes_data
def get_currentnote_data(filename):
with open(filename, 'r') as file:
line = file.readline().strip()
notecount, notetitle = line.split("++++")
return int(notecount), notetitle
##### Describe this function
def move_one_note(note_name, folder_source, folder_dest, notes_account, create=True):
''' Move processed notes into destination folder '''
# if processed_notes exists, then that stage was a success, so next step:
# create_gitmynotes_folder(folder_dest) so we have a place to move notes
if create:
success, message = create_gitnotes_folder(folder_dest, notes_account)
if success:
print_color(textcolor="green",msg=f"Create notes folder Success: {message}")
else:
logger.error(f"Failed to create Notes folder '{folder_dest}' (account '{notes_account}'): {message}")
print_color(textcolor="red",msg=f"Create notes folder Failed: {message}")
debug_print(f"Now to move UNSUPPORTED note '{note_name}' from '{folder_source}' to '{folder_dest}'")
# Escape any quotes in folder names + notes account name (R6)
folder_source_escaped = folder_source.replace('"', '\\"')
folder_dest_escaped = folder_dest.replace('"', '\\"')
notes_account_escaped = notes_account.replace('"', '\\"')
applescript_moveonenote = f'''
tell application "Notes"
set targetAccount to "{notes_account_escaped}"
tell account targetAccount
try
set sourceFolder to folder "{folder_source_escaped}"
set destFolder to folder "{folder_dest_escaped}"
set theNote to first note of sourceFolder whose name is "{note_name}"
-- Check if we have notes to move
if theNote is missing value then
return "No such note found in source folder"
end if
-- Do the move
try
move theNote to destFolder
on error errMsg
return "Error moving note " & theNote & " : " & errMsg
end try
return "SUCCESS: Moved one note '" & theNote & "' to " & destFolder
on error errMsg
return "Error: " & errMsg
end try
end tell
end tell
'''
result_onemove, output_onemove = process_applescript(applescript_moveonenote)
debug_print(f"applescript_moveonenote result: {result_onemove} {output_onemove}")
logger.warning(
f"Unsupported note '{note_name}' moved from '{folder_source}' to '{folder_dest}'. "
f"Re-run command to drain remaining notes in this batch."
)
print_color(textcolor='red', msg=f''' uh oh, unsupported note encountered: '{note_name}'
Note moved to notes folder: '{folder_dest}'.
Previous notes will be moved in this loop, but.
please run your command again to ensure all notes are moved.''', addseparator=True)
return 0
##### Describe this function
def move_processed_notes(folder_source, folder_dest, max_notes, notes_account, create=True):
''' Move processed notes into destination folder '''
# if processed_notes exists, then that stage was a success, so next step:
# create_gitmynotes_folder(folder_dest) so we have a place to move notes
if create:
success, message = create_gitnotes_folder(folder_dest, notes_account)
if success:
print_color(textcolor="green",msg=f"Create notes folder Success: {message}")
else:
logger.error(f"Failed to create Notes folder '{folder_dest}' (account '{notes_account}'): {message}")
print_color(textcolor="red",msg=f"Create notes folder Failed: {message}")
debug_print(f"Now to move up to {max_notes} notes from '{folder_source}' to '{folder_dest}'")
# Escape any quotes in folder names + notes account name (R6)
folder_source_escaped = folder_source.replace('"', '\\"')
folder_dest_escaped = folder_dest.replace('"', '\\"')
notes_account_escaped = notes_account.replace('"', '\\"')
applescript_movenote = f'''
tell application "Notes"
set targetAccount to "{notes_account_escaped}"
tell account targetAccount
try
set sourceFolder to folder "{folder_source_escaped}"
set destFolder to folder "{folder_dest_escaped}"
set theNotes to every note of sourceFolder
set noteCount to (count of theNotes)
-- Check if we have notes to move
if noteCount is 0 then
return "No notes found in source folder"
end if
-- Determine how many notes to actually move
if {max_notes} ≤ noteCount then
set notesToMove to {max_notes}
else
set notesToMove to noteCount
end if
repeat with i from 1 to notesToMove
try
move item i of theNotes to destFolder
on error errMsg
return "Error moving note " & i & ": " & errMsg
end try
end repeat
return "SUCCESS: Moved " & notesToMove & " notes"
on error errMsg
return "Error: " & errMsg
end try
end tell
end tell
'''
result_move, output_move = process_applescript(applescript_movenote)
results_print(f"applescript_movenote result: {result_move} {output_move}")
return result_move
##### Describe this function
def create_gitnotes_folder(folder: str, notes_account: str) -> Tuple[bool, str]:
"""
Create a folder in macOS Notes app under the configured Notes account.
Args:
folder (str): Name of the folder to create
notes_account (str): Notes account to scope the create to (e.g. 'iCloud',
'On My Mac'). Threaded through from --notes-account / DEFAULT_NOTES_ACCOUNT (R6).
Returns:
Tuple[bool, str]: (success status, message/error details)
"""
print_color(textcolor="white",msg=f"Attempting to create Notes folder: {folder}")
# Properly escape quotes in folder + account name for AppleScript
folder_escaped = folder.replace('"', '\\"')
notes_account_escaped = notes_account.replace('"', '\\"')
applescript = f'''
tell application "Notes"
try
set targetAccount to "{notes_account_escaped}"
tell account targetAccount
if not (exists folder "{folder_escaped}") then
make new folder with properties {{name:"{folder_escaped}"}}
return "Folder created successfully"
else
return "Folder already exists"
end if
end tell
on error errMsg
return "Error: " & errMsg
end try
end tell
'''
return process_applescript(applescript)
##### Describe this function
def process_applescript(applescript):
''' generic function to process applescript and return a result object'''
# print_color(textcolor='white', msg=f"Processing AppleScript...")
try:
result = subprocess.run(
['osascript', '-e', applescript],
capture_output=True,
text=True,
check=True # This will raise CalledProcessError if osascript fails
)
## Set the applescript blank so process_applescript can be used repeatedly
applescript = ""
# Check for any stderr output
if result.stderr:
return False, f"AppleScript Error: {result.stderr}"
# Check the actual output
output = result.stdout.strip()
if "Error:" in output:
return False, output
else:
return True, output
except subprocess.CalledProcessError as e:
return False, f"Process Error: {e.stderr}"
except Exception as e:
return False, f"Unexpected Error: {str(e)}"
def get_foldernotecount(folder, notes_account):
if folder:
debug_print(f"Getting count of notes in folder: {folder}")
# Properly escape quotes in folder + account name for AppleScript (R6)
folder_escaped = folder.replace('"', '\\"')
notes_account_escaped = notes_account.replace('"', '\\"')
applescript_notecount = f'''
tell application "Notes"
set targetAccount to "{notes_account_escaped}"
tell account targetAccount
if length of "{folder_escaped if folder_escaped else ''}" > 0 then
try
set folderToCount to folder "{folder_escaped}"
set folderNotes to every note in folderToCount
set folderNoteCount to (count of folderNotes)
return folderNoteCount
on error
log "Folder {folder_escaped} not found"
return 0
end try
end if
end tell
end tell
'''
result,output_count = process_applescript(applescript_notecount)
results_print(f"'{folder_escaped}' notecount: {output_count}")
print("")
return int(output_count)
else:
print("No folder set. ToDo: work thru defaults flow.")
def restore_source_foldernote(folder_source, folder_bkup, restore_notes, notes_account):
## if count of notes in folder_source is 0, and count of folder_dest is > 0
## then move all the notes from dest back to source. (as it was in the beginning, so shall...)
## notes_account scopes every Notes lookup to the configured account (R6).
if restore_notes != 'empty' and restore_notes != 'always':
return
source_count = get_foldernotecount(folder_source, notes_account)
bkup_count = get_foldernotecount(folder_bkup, notes_account)
if restore_notes == 'empty':
if source_count == 0:
if bkup_count > 0:
results_print(f"Source folder {folder_source} notecount is {source_count}!")
results_print(f"Option '--restore-notes={restore_notes}' so processed notes in '{folder_bkup}' will be moved back.")
restore_result = move_processed_notes(folder_bkup, folder_source, bkup_count, notes_account, create=False)
return restore_result
if restore_notes == 'always':
if bkup_count > 0:
results_print(f"Source folder {folder_source} not empty! Contains {source_count} un-backed-up notes.") #this may sometime be not clear
results_print(f"Option --restore-notes={restore_notes} so processed notes in {folder_bkup} will be moved back.")
results_print(f"WARNING: This non-'empty' setting can cause some notes to never be backed up.")
restore_result = move_processed_notes(folder_bkup, folder_source, bkup_count, notes_account, create=False)
return restore_result
else:
return
def update_yaml_config(file_path, key, value):
"""
Updates a specific key-value pair in a YAML config file while preserving comments and formatting.
Args:
file_path (str): Path to the YAML configuration file
key (str): The key to update
value: The new value for the specified key
"""
# Use ruamel.yaml to preserve comments and formatting
yaml_handler = YAML()
yaml_handler.preserve_quotes = True # Preserve existing quote styles
yaml_handler.width = 4096 # Prevent automatic line wrapping
# Read the existing file
with open(file_path, 'r') as file:
config = yaml_handler.load(file)
# Update the specific key
config[key] = value
# Write back to the file, preserving original structure
with open(file_path, 'w') as file:
yaml_handler.dump(config, file)
def update_yaml_config_multi(file_path, updates):
"""
Updates multiple key-value pairs in a YAML config file in a single read+write
cycle, preserving comments and formatting. Used to flush per-run usage counter
updates atomically (R10) instead of one yaml round-trip per key.
Args:
file_path (str): Path to the YAML configuration file
updates (dict): Mapping of {key: new_value} pairs to apply. An empty dict
is a no-op (the file isn't touched).
"""
if not updates:
return
yaml_handler = YAML()
yaml_handler.preserve_quotes = True
yaml_handler.width = 4096
with open(file_path, 'r') as file:
config = yaml_handler.load(file)
for key, value in updates.items():
config[key] = value
with open(file_path, 'w') as file:
yaml_handler.dump(config, file)
## PRINT OPTIONS
def debug_print(*args, **kwargs):
if PRINT_LEVEL.value >= PrintLevel.DEBUG.value:
print("DEBUG:", *args, **kwargs)
def results_print(*args, **kwargs):
if PRINT_LEVEL.value >= PrintLevel.RESULTS.value:
print("RESULT:", *args, **kwargs)
def setup_logging():
"""Configure the gitmynotes logger (R4, incremental).
Attaches a FileHandler to '<script_dir>/gitmynotes.log' at WARNING level.
Uses append mode (default) so each run extends the same file -- no size-
based rotation in this pass; can swap in RotatingFileHandler later if the
file grows uncomfortably. Format includes a timestamp and level so non-
interactive consumers (Cowork routines, post-mortem inspection) can parse
the file without dealing with ANSI codes from the TTY-oriented prints.
Idempotent: skips re-adding the handler if a FileHandler already points at
the same path (defensive against any future re-entry into main()).
"""
log_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"gitmynotes.log",
)
for existing in logger.handlers:
if (isinstance(existing, logging.FileHandler)
and getattr(existing, "baseFilename", None) == log_path):
return
handler = logging.FileHandler(log_path)
handler.setLevel(logging.WARNING)
handler.setFormatter(logging.Formatter(
fmt="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
))
logger.addHandler(handler)
logger.setLevel(logging.WARNING)
def build_initial_msg(this_msg=None, folder=None, max_notes=None, export_path=None, github_url=None, print_level=None, local_only=None):
# get some values for an initial msg
if this_msg:
initial_msg = f'''{this_msg}
'''
else:
initial_msg = f''' Welcome, 'tis a good day to GitMyNotes
NOTE: locked notes unlocked in this Notes.app session export as cleartext.
Close them before running if that's not what you want. (See README.)
'''
if folder:
initial_msg += f''' - Notes folder: {folder}
'''
if print_level:
initial_msg += f''' - print-level: {print_level}
'''
if max_notes:
initial_msg += f''' - max-notes: {max_notes}
'''
if export_path:
initial_msg += f''' - Export to: {export_path}
'''
if local_only:
initial_msg += f''' - Local Only option set via '--local'.
DO NOT SEND TO:
'''
if github_url:
initial_msg += f''' - GitHub repo: {github_url}
'''
return initial_msg
def build_final_msg(gitnotes_url, audit_file, usage_totals, share_url):
# get some values for an initial msg
final_msg = f''' GitMyNotes actions complete!
'''
if gitnotes_url:
final_msg += f''' - Check your GitMyNotes: {gitnotes_url}
'''
if audit_file:
final_msg += f''' - Check your audit file: {audit_file}
'''
if usage_totals:
final_msg += f' - Runs::Folders::Notes: '+str(usage_totals[0])+'::'+str(usage_totals[1])+'::'+str(usage_totals[2])
final_msg += f'''
'''
if share_url:
final_msg += f''' - Tell your friends, learn more: https://GitMyNotes.com/
'''
return final_msg
##### Describe this function
def main():
# R4 (incremental): wire up the file logger first so any subsequent
# warning- / error-level event in this run lands in <script_dir>/gitmynotes.log
# alongside the existing colored TTY prints. Hardcoded log location for now;
# CLI override can be added later if needed.
setup_logging()
######## ---- Get DEFAULT_& vars from config file ---- #######
DEFAULT_NOTES_FOLDER_FORCE = None ##special case not in config file because... reasons.
DEFAULT_LOCAL_ONLY = None ##special case not in config file to turn OFF sending to github
cfg = load_configs_from_file()
DEFAULT_GITHUB_URL = cfg['DEFAULT_GITHUB_URL']
DEFAULT_NOTES_FOLDER = cfg['DEFAULT_NOTES_FOLDER']
DEFAULT_EXPORT_PATH = cfg['DEFAULT_EXPORT_PATH']
DEFAULT_BATCH_SIZE = cfg['DEFAULT_BATCH_SIZE']
DEFAULT_NOTES_WRAPPERDIR = cfg['DEFAULT_NOTES_WRAPPERDIR']
DEFAULT_PROCESSED_FOLDER_ENDING = cfg['DEFAULT_PROCESSED_FOLDER_ENDING']
DEFAULT_AUDIT_FILE_ENDING = cfg['DEFAULT_AUDIT_FILE_ENDING']
DEFAULT_LOOPCOUNT_BEFORE_CONFIRM = cfg['DEFAULT_LOOPCOUNT_BEFORE_CONFIRM']
DEFAULT_NEWLINE_DELIMITER = cfg['DEFAULT_NEWLINE_DELIMITER']
DEFAULT_RESTORE_NOTES = cfg['DEFAULT_RESTORE_NOTES']
DEFAULT_CURRENTNOTE_FILE = cfg['DEFAULT_CURRENTNOTE_FILE']
# B9: resolve DEFAULT_CURRENTNOTE_FILE to an absolute path so AppleScript's
# shell (osascript cwd is usually $HOME) and Python (cwd = wherever the user
# invoked the script) agree on where the side-channel file lives. If the
# config value is already absolute, respect it; otherwise anchor to the
# directory containing this script, which keeps the existing .gitignore
# entry valid and keeps the file inspectable while debugging.
if not os.path.isabs(DEFAULT_CURRENTNOTE_FILE):
DEFAULT_CURRENTNOTE_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)),