-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate-cli.py
More file actions
2844 lines (2533 loc) · 135 KB
/
Copy pathgenerate-cli.py
File metadata and controls
2844 lines (2533 loc) · 135 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
"""
Generate reminderkit-generated.m from ReminderKit private API.
USAGE:
python3 generate-cli.py > reminderkit-generated.m
# Then: make reminderkit
MAINTENANCE:
This generator produces reminderkit-generated.m — the config-driven
Objective-C code for the reminders CLI. Handwritten commands live in
reminderkit-handwritten.m, tests in reminderkit-tests.m, and the
assembly file reminderkit.m #includes all three.
To add a new READ property:
1. Add an entry to REMINDER_READ_PROPS below
2. Format: "objcPropertyName": ("jsonKey", "type_hint")
3. Type hints: "string", "bool", "bool_getter", "int", "uint",
"date", "datecomps", "objid", "set_hashtags"
4. Regenerate: make generate
To add a new WRITE operation (setter):
1. Add an entry to REMINDER_WRITE_OPS below
2. Format: "cli-flag": ("setterSelector:", "arg_type")
3. Arg types: "string", "bool", "int", "uint", "datecomps"
4. For no-arg methods (like removeFromParentReminder), add to SPECIAL_WRITE_OPS
5. Regenerate
To discover new properties/methods:
make remkit-inspect && ./remkit-inspect 2>&1 | less
Architecture:
remkit-inspect.m -> dumps ObjC runtime properties/methods (discovery tool)
generate-cli.py -> generates reminderkit-generated.m from config dicts (this file)
reminderkit-generated.m -> AUTO-GENERATED, do not edit manually
reminderkit-handwritten.m -> manually maintained commands
reminderkit-tests.m -> test infrastructure
reminderkit.m -> assembly file (#includes the above three + usage/main)
Makefile -> builds everything, `make generate` regenerates
"""
# --- Configuration ---
# Properties to expose on REMReminder (read)
# Maps property name -> (json_key, type_hint)
# type_hint: "string", "bool", "int", "uint", "date", "objid", "set_hashtags", "datecomps"
# Note: "url" is read via attachmentContext, not icsUrl
#
# Omit-when-default: fields whose default (zero/false/empty) value is suppressed
# from the output dict unless --full is passed. This is the "smart defaults"
# contract consumed by scripts; see CONTRACT.md.
#
# The "objid" type is split into two emitted fields: "<jsonKey>" (bare UUID)
# and "<jsonKey>Uri"/"uri" (x-apple-reminderkit:// URL). For the main object
# the keys are literally "id" + "uri"; for referenced objects (listID, parent)
# we use "<camelCase>Id" + "<camelCase>Uri" to avoid key collisions.
REMINDER_READ_PROPS = {
"titleAsString": ("title", "string"),
"notesAsString": ("notes", "string"),
"completed": ("completed", "bool_getter"), # getter is isCompleted
"priority": ("priority", "uint"),
"flagged": ("flagged", "int"),
"allDay": ("allDay", "bool"),
"isOverdue": ("isOverdue", "bool"),
"isRecurrent": ("isRecurrent", "bool"),
"objectID": ("id", "objid_self"),
"listID": ("listId", "objid_ref"),
"parentReminderID": ("parentId", "objid_ref"),
"dueDateComponents": ("dueDate", "datecomps"),
"startDateComponents":("startDate", "datecomps"),
"creationDate": ("createdAt", "date"),
"lastModifiedDate": ("modifiedAt", "date"),
"completionDate": ("completedAt", "date"),
"hashtags": ("hashtags", "set_hashtags"),
"timeZone": ("timeZone", "string"),
"assignmentContext": ("assignments", "assignment_context"),
}
# Fields to omit from default output when they hold their default/zero value.
# (All set of json keys — applied in reminderToDict.)
OMIT_WHEN_DEFAULT = {
"allDay", # false
"completed", # false
"flagged", # 0
"isOverdue", # false
"isRecurrent", # false
"priority", # 0
"hashtags", # empty array (already suppressed but documented)
}
# Setters to expose on REMReminderChangeItem (write via update command)
# Maps cli_flag -> (setter_method, arg_type)
# arg_type: "string", "bool", "uint", "int", "datecomps", "url"
# Note: "url" setter uses attachmentContext, not setIcsUrl:
REMINDER_WRITE_OPS = {
"title": ("setTitleAsString:", "string"),
"notes": ("setNotesAsString:", "string"),
"completed": ("setCompleted:", "bool"),
"priority": ("setPriority:", "uint"),
"flagged": ("setFlagged:", "bool"),
"due-date": ("setDueDateComponents:", "datecomps"),
"start-date": ("setStartDateComponents:", "datecomps"),
"url": (None, "url"), # handled specially
}
# Special write operations (not simple setters)
SPECIAL_WRITE_OPS = {
"remove-from-list": "removeFromList",
}
def generate_header():
return '''// AUTO-GENERATED by generate-cli.py — do not edit manually
#import <Foundation/Foundation.h>
#import <EventKit/EventKit.h>
#import <objc/runtime.h>
#import <objc/message.h>
#include <mach-o/dyld.h>
#include <unistd.h>
#include <sys/wait.h>
#include <spawn.h>
#include <fcntl.h>
// --- Framework Loading ---
static Class REMStoreClass;
static Class REMSaveRequestClass;
static Class REMListSectionCIClass;
static Class REMMembershipClass;
static Class REMMembershipsClass;
static void loadFramework(void) {
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/ReminderKit.framework"] load];
REMStoreClass = NSClassFromString(@"REMStore");
REMSaveRequestClass = NSClassFromString(@"REMSaveRequest");
REMListSectionCIClass = NSClassFromString(@"REMListSectionChangeItem");
REMMembershipClass = NSClassFromString(@"REMMembership");
REMMembershipsClass = NSClassFromString(@"REMMemberships");
}
static BOOL hasRemindersAccess(void) {
EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:EKEntityTypeReminder];
return status == EKAuthorizationStatusAuthorized || status == EKAuthorizationStatusFullAccess;
}
static BOOL requestRemindersAccessOnce(void) {
if (hasRemindersAccess()) return YES;
EKEventStore *eventStore = [[EKEventStore alloc] init];
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
__block BOOL granted = NO;
if ([eventStore respondsToSelector:@selector(requestFullAccessToRemindersWithCompletion:)]) {
[eventStore requestFullAccessToRemindersWithCompletion:^(BOOL didGrant, NSError *error) {
(void)error;
granted = didGrant;
dispatch_semaphore_signal(sem);
}];
} else {
[eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL didGrant, NSError *error) {
(void)error;
granted = didGrant;
dispatch_semaphore_signal(sem);
}];
}
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
return granted;
}
static void printRemindersAccessDeniedHelp(void) {
fprintf(stderr, "Error: Reminders access denied.\\n\\n");
fprintf(stderr, "Your terminal app needs permission to access Reminders.\\n\\n");
fprintf(stderr, "1. Grant permission (triggers macOS prompt):\\n");
fprintf(stderr, " osascript -e 'tell application \\"Reminders\\" to get name of every list'\\n\\n");
fprintf(stderr, "2. If previously denied, reset first, then re-run step 1:\\n");
fprintf(stderr, " tccutil reset Reminders <bundle-id>\\n\\n");
fprintf(stderr, " Find your terminal's bundle ID:\\n");
fprintf(stderr, " osascript -e 'id of app \\"iTerm\\"' (replace iTerm with your terminal app name)\\n\\n");
fprintf(stderr, "3. Then retry your reminderkit command.\\n");
}
static BOOL runRemindersPermissionPreflight(void) {
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/osascript"];
[task setArguments:@[@"-e", @"tell application \\"Reminders\\" to get name of every list"]];
[task setStandardInput:[NSFileHandle fileHandleWithNullDevice]];
[task setStandardOutput:[NSFileHandle fileHandleWithNullDevice]];
[task setStandardError:[NSFileHandle fileHandleWithNullDevice]];
@try {
[task launch];
[task waitUntilExit];
} @catch (__unused NSException *exception) {
return NO;
}
return [task terminationStatus] == 0;
}
static BOOL isRemindersAccessError(NSError *error) {
return [[error domain] isEqualToString:@"NSCocoaErrorDomain"] && [error code] == 4097;
}
static void requestRemindersAccess(void) {
if (requestRemindersAccessOnce()) return;
runRemindersPermissionPreflight();
if (requestRemindersAccessOnce()) return;
printRemindersAccessDeniedHelp();
exit(1);
}
static id getStore(void) {
requestRemindersAccess();
return ((id (*)(id, SEL, BOOL))objc_msgSend)(
[REMStoreClass alloc], sel_registerName("initUserInteractive:"), YES);
}
// --- Helpers ---
static void errorExit(NSString *msg) {
fprintf(stderr, "Error: %s\\n", [msg UTF8String]);
exit(1);
}
static BOOL parseBoolString(id value) {
if ([value isKindOfClass:[NSNumber class]]) return [value boolValue];
if (![value isKindOfClass:[NSString class]]) errorExit(@"Expected boolean or boolean string");
NSString *lower = [(NSString *)value lowercaseString];
return [lower isEqualToString:@"true"] || [lower isEqualToString:@"1"] || [lower isEqualToString:@"yes"];
}
static NSString *objectIDToString(id objID) {
if (!objID) return nil;
return [objID description];
}
static NSUUID *objectIDToNSUUID(id objID) {
if (!objID) return nil;
@try {
return ((id (*)(id, SEL))objc_msgSend)(objID, sel_registerName("uuid"));
} @catch (__unused NSException *e) {
return nil;
}
}
// --- ID Output Mode (omit-when-default, field projection, full mode) ---
// Populated from CLI flags in main(). Shared by reminderToDict + helpers.
static BOOL gOutputFull = NO; // --full
static NSArray *gOutputFields = nil; // --fields id,title,notes,...
static BOOL gOutputLegacyID = NO; // batch results keep old id format
// NSManagedObjectID description looks like:
// "🎅~<x-apple-reminderkit://REMCDReminder/706D8583-A718-4644-9056-E79D9C8E9625>"
// Extract the canonical x-callback-url form (no emoji, no angle brackets).
static NSString *objectIDToURI(id objID) {
if (!objID) return nil;
NSString *desc = [objID description];
if (!desc) return nil;
// Find the first '<' and the matching '>' at the end.
NSRange lt = [desc rangeOfString:@"<"];
NSRange gt = [desc rangeOfString:@">" options:NSBackwardsSearch];
if (lt.location != NSNotFound && gt.location != NSNotFound && gt.location > lt.location) {
return [desc substringWithRange:NSMakeRange(lt.location + 1, gt.location - lt.location - 1)];
}
// Fallback: if the string already starts with the scheme, return as-is.
if ([desc hasPrefix:@"x-apple-reminderkit://"]) return desc;
return desc;
}
// Extract the bare UUID (last path component) from an NSManagedObjectID.
// Returns nil if no UUID-shaped token is found.
static NSString *objectIDToUUID(id objID) {
if (!objID) return nil;
NSString *uri = objectIDToURI(objID);
if (!uri) return nil;
NSArray *parts = [uri componentsSeparatedByString:@"/"];
if (parts.count == 0) return nil;
NSString *tail = [parts lastObject];
// Strip any stray trailing '>' just in case.
if ([tail hasSuffix:@">"]) tail = [tail substringToIndex:tail.length - 1];
// Validate UUID shape (36 chars with dashes).
if (tail.length == 36 && [tail characterAtIndex:8] == '-') return [tail uppercaseString];
return nil;
}
// Build the full legacy id string (with emoji prefix) from an NSManagedObjectID.
// This is the exact byte-for-byte representation scripts using pre-v2 output
// would see. Only used in --full mode for the "id" field.
static NSString *objectIDToLegacyString(id objID) {
return objectIDToString(objID);
}
// Accept either a bare UUID or any form that contains one ("706D...", the full
// emoji-URL wrapped form, the naked x-apple-reminderkit:// URL, etc.). Returns
// the uppercased bare UUID, or nil if the input doesn't look like one.
static NSString *normalizeIDInput(NSString *input) {
if (!input || input.length == 0) return nil;
// If the whole input is already a UUID, short-circuit.
if (input.length == 36 && [input characterAtIndex:8] == '-') {
return [input uppercaseString];
}
// Otherwise scan for a UUID-shaped token (36 chars, dash positions 8/13/18/23).
NSCharacterSet *hex = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF-"];
NSUInteger n = input.length;
for (NSUInteger i = 0; i + 36 <= n; i++) {
BOOL ok = YES;
for (NSUInteger j = 0; j < 36; j++) {
unichar c = [input characterAtIndex:i + j];
if (![hex characterIsMember:c]) { ok = NO; break; }
if ((j == 8 || j == 13 || j == 18 || j == 23) && c != '-') { ok = NO; break; }
if (j != 8 && j != 13 && j != 18 && j != 23 && c == '-') { ok = NO; break; }
}
if (ok) return [[input substringWithRange:NSMakeRange(i, 36)] uppercaseString];
}
return nil;
}
// Add a key to a shaped dict's field order (used when callers add new keys
// after shaping, e.g. subtasks, listName). No-op if not a shaped dict.
static void addFieldIfRequested(NSMutableDictionary *dict, NSString *key, id value) {
if (!value) return;
if (gOutputFields && gOutputFields.count > 0) {
if (![gOutputFields containsObject:key]) return; // not requested, drop
dict[key] = value;
NSMutableArray *order = dict[@"__fieldOrder__"];
if ([order isKindOfClass:[NSMutableArray class]] && ![order containsObject:key]) {
[order addObject:key];
}
return;
}
dict[key] = value;
}
// --- Field projection helper ---
// Apply gOutputFields / gOutputFull / OMIT_WHEN_DEFAULT to a fully-populated dict.
// When gOutputFields is set we return an ordered dict containing only the requested
// keys (preserving user-specified order, values taken from src).
// When gOutputFull is NO and gOutputFields is nil, we apply the omit-when-default rules.
// Omit-when-default rules (only relevant when --full is NOT set):
// allDay=false, completed=false, flagged=0, isOverdue=false,
// isRecurrent=false, priority=0, hashtags=[]
static id applyOutputShape(NSDictionary *src) {
// --fields takes precedence over --full
if (gOutputFields && gOutputFields.count > 0) {
// Preserve order via a plain NSMutableDictionary plus a sibling order array
// that printJSON's sortedKeys would otherwise destroy. We therefore use
// NSJSONWritingSortedKeys=NO and build an NSMutableDictionary that the
// printer renders in insertion order. See printJSON below.
NSMutableDictionary *out = [NSMutableDictionary dictionary];
NSMutableArray *order = [NSMutableArray array];
for (NSString *field in gOutputFields) {
id v = src[field];
if (v) {
out[field] = v;
[order addObject:field];
}
}
out[@"__fieldOrder__"] = order; // printer reads and strips this
return out;
}
if (gOutputFull) return src; // all fields including defaults
// Default: omit-when-default
NSMutableDictionary *out = [src mutableCopy];
if ([out[@"allDay"] isKindOfClass:[NSNumber class]] && ![out[@"allDay"] boolValue]) [out removeObjectForKey:@"allDay"];
if ([out[@"completed"] isKindOfClass:[NSNumber class]] && ![out[@"completed"] boolValue]) [out removeObjectForKey:@"completed"];
if ([out[@"isOverdue"] isKindOfClass:[NSNumber class]] && ![out[@"isOverdue"] boolValue]) [out removeObjectForKey:@"isOverdue"];
if ([out[@"isRecurrent"] isKindOfClass:[NSNumber class]] && ![out[@"isRecurrent"] boolValue]) [out removeObjectForKey:@"isRecurrent"];
if ([out[@"priority"] isKindOfClass:[NSNumber class]] && [out[@"priority"] integerValue] == 0) [out removeObjectForKey:@"priority"];
if ([out[@"flagged"] isKindOfClass:[NSNumber class]] && [out[@"flagged"] integerValue] == 0) [out removeObjectForKey:@"flagged"];
if ([out[@"hashtags"] isKindOfClass:[NSArray class]] && [(NSArray *)out[@"hashtags"] count] == 0) [out removeObjectForKey:@"hashtags"];
return out;
}
static NSString *dateToISO(NSDate *date) {
if (!date) return nil;
NSISO8601DateFormatter *fmt = [[NSISO8601DateFormatter alloc] init];
return [fmt stringFromDate:date];
}
static NSString *dateCompsToString(NSDateComponents *comps) {
if (!comps) return nil;
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *date = [cal dateFromComponents:comps];
if (date) return dateToISO(date);
// Fallback: manual formatting
return [NSString stringWithFormat:@"%04ld-%02ld-%02ld",
(long)[comps year], (long)[comps month], (long)[comps day]];
}
static NSDateComponents *stringToDateComps(NSString *str) {
// Parse ISO date string like "2026-03-15" or "2026-03-15T10:00:00"
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSArray *parts = [str componentsSeparatedByString:@"T"];
NSArray *dateParts = [parts[0] componentsSeparatedByString:@"-"];
if (dateParts.count >= 3) {
comps.year = [dateParts[0] integerValue];
comps.month = [dateParts[1] integerValue];
comps.day = [dateParts[2] integerValue];
}
if (parts.count > 1) {
NSArray *timeParts = [parts[1] componentsSeparatedByString:@":"];
if (timeParts.count >= 2) {
comps.hour = [timeParts[0] integerValue];
comps.minute = [timeParts[1] integerValue];
}
}
return comps;
}
static NSString *normalizeQuotes(NSString *str) {
if (!str) return nil;
NSString *result = [str stringByReplacingOccurrencesOfString:@"\\u2018" withString:@"'"];
result = [result stringByReplacingOccurrencesOfString:@"\\u2019" withString:@"'"];
return result;
}
// Strip any internal "__fieldOrder__" markers from a JSON-ready structure.
// Returns a new object tree. Used by printJSON before serialisation.
static id stripFieldOrderMarkers(id obj) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *src = obj;
NSMutableDictionary *dst = [NSMutableDictionary dictionary];
for (NSString *k in src) {
if ([k isEqualToString:@"__fieldOrder__"]) continue;
dst[k] = stripFieldOrderMarkers(src[k]);
}
return dst;
}
if ([obj isKindOfClass:[NSArray class]]) {
NSMutableArray *dst = [NSMutableArray array];
for (id e in obj) [dst addObject:stripFieldOrderMarkers(e)];
return dst;
}
return obj;
}
// Serialize JSON manually when any top-level or nested dict has a
// __fieldOrder__ marker, so we can preserve insertion order. Otherwise
// fall back to NSJSONSerialization (sorted keys for stability).
static NSString *jsonIndent(NSUInteger lvl) {
NSMutableString *s = [NSMutableString string];
for (NSUInteger i = 0; i < lvl; i++) [s appendString:@" "];
return s;
}
// Return the JSON-escaped string body (INCLUDING surrounding quotes).
// Example: jsonEscapeQuoted(@"he\\"llo") -> "\\"he\\\\\\"llo\\""
static NSString *jsonEscapeQuoted(NSString *s) {
NSError *e = nil;
NSData *d = [NSJSONSerialization dataWithJSONObject:@[s] options:0 error:&e];
if (!d) return @"\\"\\"";
NSString *full = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
// full looks like ["..."], strip the outer brackets only
if (full.length >= 4) return [full substringWithRange:NSMakeRange(1, full.length - 2)];
return @"\\"\\"";
}
static void jsonWriteValue(NSMutableString *out, id v, NSUInteger lvl, BOOL hasOrder);
static void jsonWriteDict(NSMutableString *out, NSDictionary *d, NSUInteger lvl, BOOL hasOrder) {
NSArray *keys;
NSArray *orderMarker = d[@"__fieldOrder__"];
if ([orderMarker isKindOfClass:[NSArray class]]) {
keys = orderMarker;
} else {
// Sort keys for stability, matching NSJSONWritingSortedKeys.
keys = [[d allKeys] sortedArrayUsingSelector:@selector(compare:)];
}
if (keys.count == 0) { [out appendString:@"{\\n\\n"]; [out appendString:jsonIndent(lvl)]; [out appendString:@"}"]; return; }
[out appendString:@"{\\n"];
NSUInteger idx = 0;
for (NSString *k in keys) {
if ([k isEqualToString:@"__fieldOrder__"]) continue;
id v = d[k];
if (!v) continue;
[out appendString:jsonIndent(lvl + 1)];
[out appendString:jsonEscapeQuoted(k)];
[out appendString:@" : "];
jsonWriteValue(out, v, lvl + 1, hasOrder);
// We don't easily know if there's a next key; append comma+newline unconditionally
// and strip the trailing ,\\n below.
[out appendString:@",\\n"];
idx++;
}
// Strip trailing ",\\n"
if (idx > 0 && [out hasSuffix:@",\\n"]) [out deleteCharactersInRange:NSMakeRange(out.length - 2, 2)];
[out appendString:@"\\n"];
[out appendString:jsonIndent(lvl)];
[out appendString:@"}"];
}
static void jsonWriteArray(NSMutableString *out, NSArray *a, NSUInteger lvl, BOOL hasOrder) {
if (a.count == 0) { [out appendString:@"[]"]; return; }
[out appendString:@"[\\n"];
for (NSUInteger i = 0; i < a.count; i++) {
[out appendString:jsonIndent(lvl + 1)];
jsonWriteValue(out, a[i], lvl + 1, hasOrder);
if (i + 1 < a.count) [out appendString:@","];
[out appendString:@"\\n"];
}
[out appendString:jsonIndent(lvl)];
[out appendString:@"]"];
}
static void jsonWriteValue(NSMutableString *out, id v, NSUInteger lvl, BOOL hasOrder) {
if ([v isKindOfClass:[NSDictionary class]]) { jsonWriteDict(out, v, lvl, hasOrder); return; }
if ([v isKindOfClass:[NSArray class]]) { jsonWriteArray(out, v, lvl, hasOrder); return; }
if ([v isKindOfClass:[NSString class]]) {
[out appendString:jsonEscapeQuoted(v)];
return;
}
if ([v isKindOfClass:[NSNumber class]]) {
NSNumber *n = v;
// Objective-C: @YES/@NO are NSNumbers; detect via objCType.
const char *t = [n objCType];
if (t[0] == 'c' || t[0] == 'B') { [out appendString:[n boolValue] ? @"true" : @"false"]; return; }
[out appendString:[n stringValue]];
return;
}
if (v == [NSNull null] || !v) { [out appendString:@"null"]; return; }
// Fallback: serialize via NSJSONSerialization in a wrapper array.
NSError *e = nil;
NSData *d = [NSJSONSerialization dataWithJSONObject:@[v] options:0 error:&e];
if (d) {
NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
if (s.length >= 2) { [out appendString:[s substringWithRange:NSMakeRange(1, s.length - 2)]]; return; }
}
[out appendString:@"null"];
}
// Recursively walk and set hasOrder=YES if any dict has __fieldOrder__.
static BOOL hasFieldOrderMarker(id obj) {
if ([obj isKindOfClass:[NSDictionary class]]) {
if (((NSDictionary *)obj)[@"__fieldOrder__"]) return YES;
for (id v in [(NSDictionary *)obj allValues]) {
if (hasFieldOrderMarker(v)) return YES;
}
} else if ([obj isKindOfClass:[NSArray class]]) {
for (id v in (NSArray *)obj) if (hasFieldOrderMarker(v)) return YES;
}
return NO;
}
static void printJSON(id obj) {
if (hasFieldOrderMarker(obj)) {
NSMutableString *out = [NSMutableString string];
jsonWriteValue(out, obj, 0, YES);
printf("%s\\n", [out UTF8String]);
return;
}
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:obj
options:NSJSONWritingPrettyPrinted | NSJSONWritingSortedKeys error:&error];
if (error) errorExit([error localizedDescription]);
printf("%s\\n", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding].UTF8String);
}
// --- List Helpers ---
static NSString *listName(id list) {
if (!list) return nil;
id storage = ((id (*)(id, SEL))objc_msgSend)(list, sel_registerName("storage"));
return ((id (*)(id, SEL))objc_msgSend)(storage, sel_registerName("name"));
}
static BOOL listIsGroup(id list) {
return list && ((BOOL (*)(id, SEL))objc_msgSend)(list, sel_registerName("isGroup"));
}
static NSArray *fetchLists(id store) {
NSError *error = nil;
NSArray *lists = ((id (*)(id, SEL, id*))objc_msgSend)(
store, sel_registerName("fetchEligibleDefaultListsWithError:"), &error);
if (error && isRemindersAccessError(error)) {
runRemindersPermissionPreflight();
error = nil;
lists = ((id (*)(id, SEL, id*))objc_msgSend)(
store, sel_registerName("fetchEligibleDefaultListsWithError:"), &error);
}
if (error) {
if (isRemindersAccessError(error)) {
printRemindersAccessDeniedHelp();
exit(1);
}
errorExit([NSString stringWithFormat:@"Failed to fetch lists: %@", error]);
}
return lists;
}
static NSArray *fetchAccounts(id store) {
NSError *error = nil;
NSArray *accounts = ((id (*)(id, SEL, id*))objc_msgSend)(
store, sel_registerName("fetchAccountsWithError:"), &error);
if (error) errorExit([NSString stringWithFormat:@"Failed to fetch accounts: %@", error]);
return accounts ?: @[];
}
static NSArray *fetchGroups(id store) {
NSMutableArray *groups = [NSMutableArray array];
for (id account in fetchAccounts(store)) {
id groupContext = ((id (*)(id, SEL))objc_msgSend)(account, sel_registerName("groupContext"));
NSError *error = nil;
NSArray *accountGroups = ((id (*)(id, SEL, id*))objc_msgSend)(
groupContext, sel_registerName("fetchGroupsWithError:"), &error);
if (error) errorExit([NSString stringWithFormat:@"Failed to fetch groups: %@", error]);
if (accountGroups) [groups addObjectsFromArray:accountGroups];
}
return groups;
}
static id findGroup(id store, NSString *name) {
NSArray *groups = fetchGroups(store);
for (id group in groups) {
NSString *candidateName = listName(group);
if ([candidateName isEqualToString:name]) return group;
}
NSString *normalizedName = normalizeQuotes(name);
for (id group in groups) {
if ([normalizeQuotes(listName(group)) isEqualToString:normalizedName]) return group;
}
return nil;
}
static NSArray *fetchChildLists(id group) {
id sublistContext = ((id (*)(id, SEL))objc_msgSend)(group, sel_registerName("sublistContext"));
NSError *error = nil;
NSArray *lists = ((id (*)(id, SEL, id*))objc_msgSend)(
sublistContext, sel_registerName("fetchListsWithError:"), &error);
if (error) errorExit([NSString stringWithFormat:@"Failed to fetch lists in group: %@", error]);
return lists ?: @[];
}
static NSMutableDictionary *listIdentityDict(id list) {
NSMutableDictionary *d = [NSMutableDictionary dictionary];
NSString *name = listName(list);
id objID = ((id (*)(id, SEL))objc_msgSend)(list, sel_registerName("objectID"));
if (name) d[@"name"] = name;
if (objID) {
if (gOutputFull) {
d[@"id"] = objectIDToLegacyString(objID) ?: @"";
NSString *uuid = objectIDToUUID(objID);
if (uuid) d[@"uuid"] = uuid;
} else {
NSString *uuid = objectIDToUUID(objID);
d[@"id"] = uuid ?: (objectIDToString(objID) ?: @"");
NSString *uri = objectIDToURI(objID);
if (uri) d[@"uri"] = uri;
}
}
return d;
}
static NSMutableDictionary *listToDict(id list) {
NSMutableDictionary *d = listIdentityDict(list);
id group = ((id (*)(id, SEL))objc_msgSend)(list, sel_registerName("parentList"));
if (group && listIsGroup(group)) {
NSString *groupName = listName(group);
id groupID = ((id (*)(id, SEL))objc_msgSend)(group, sel_registerName("objectID"));
if (groupName) d[@"group"] = groupName;
if (groupID) {
if (gOutputFull) {
d[@"groupID"] = objectIDToLegacyString(groupID) ?: @"";
} else {
NSString *uuid = objectIDToUUID(groupID);
if (uuid) d[@"groupId"] = uuid;
NSString *uri = objectIDToURI(groupID);
if (uri) d[@"groupUri"] = uri;
}
}
}
return (NSMutableDictionary *)applyOutputShape(d);
}
static id findList(id store, NSString *name) {
NSArray *lists = fetchLists(store);
for (id list in lists) {
NSString *candidateName = listName(list);
if ([candidateName isEqualToString:name]) return list;
}
// Normalized fallback: retry with curly quotes normalized to straight quotes
NSString *normalizedName = normalizeQuotes(name);
for (id list in lists) {
NSString *candidateName = listName(list);
if ([normalizeQuotes(candidateName) isEqualToString:normalizedName]) return list;
}
return nil;
}
static NSArray *fetchReminders(id store, id list, BOOL includeCompleted) {
id listObjID = ((id (*)(id, SEL))objc_msgSend)(list, sel_registerName("objectID"));
NSError *error = nil;
NSArray *all = ((id (*)(id, SEL, id, id*))objc_msgSend)(
store, sel_registerName("fetchRemindersForEventKitBridgingWithListIDs:error:"),
@[listObjID], &error);
if (error) errorExit([NSString stringWithFormat:@"Failed to fetch reminders: %@", error]);
if (includeCompleted) return all;
NSMutableArray *incomplete = [NSMutableArray array];
for (id rem in all) {
BOOL done = ((BOOL (*)(id, SEL))objc_msgSend)(rem, sel_registerName("isCompleted"));
if (!done) [incomplete addObject:rem];
}
return incomplete;
}
static id findReminder(id store, NSString *title, NSString *listName) {
NSArray *lists;
if (listName) {
id list = findList(store, listName);
if (!list) errorExit([NSString stringWithFormat:@"List not found: %@", listName]);
lists = @[list];
} else {
lists = fetchLists(store);
}
for (id list in lists) {
NSArray *rems = fetchReminders(store, list, YES);
for (id rem in rems) {
NSString *t = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("titleAsString"));
if ([t isEqualToString:title]) return rem;
}
}
// Normalized fallback: retry with curly quotes normalized to straight quotes
NSString *normalizedTitle = normalizeQuotes(title);
for (id list in lists) {
NSArray *rems = fetchReminders(store, list, YES);
for (id rem in rems) {
NSString *t = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("titleAsString"));
if ([normalizeQuotes(t) isEqualToString:normalizedTitle]) return rem;
}
}
return nil;
}
static NSString *normalizeURL(NSString *url) {
// Strip trailing slash for comparison
while ([url hasSuffix:@"/"]) {
url = [url substringToIndex:url.length - 1];
}
return [url lowercaseString];
}
static NSArray *findReminders(id store, NSString *title, NSString *listName) {
NSArray *lists;
if (listName) {
id list = findList(store, listName);
if (!list) errorExit([NSString stringWithFormat:@"List not found: %@", listName]);
lists = @[list];
} else {
lists = fetchLists(store);
}
NSMutableArray *results = [NSMutableArray array];
NSString *normalizedTitle = normalizeQuotes(title);
NSString *lowerTitle = [normalizedTitle lowercaseString];
for (id list in lists) {
NSArray *rems = fetchReminders(store, list, NO);
for (id rem in rems) {
NSString *t = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("titleAsString"));
if (!t) continue;
NSString *lowerT = [[normalizeQuotes(t) lowercaseString] copy];
if ([lowerT rangeOfString:lowerTitle].location != NSNotFound) {
[results addObject:rem];
}
}
}
return results;
}
static NSArray *findRemindersByURL(id store, NSString *url, NSString *listName) {
NSArray *lists;
if (listName) {
id list = findList(store, listName);
if (!list) errorExit([NSString stringWithFormat:@"List not found: %@", listName]);
lists = @[list];
} else {
lists = fetchLists(store);
}
NSMutableArray *results = [NSMutableArray array];
NSString *normalizedSearch = normalizeURL(url);
for (id list in lists) {
NSArray *rems = fetchReminders(store, list, NO);
for (id rem in rems) {
@try {
id attCtx = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("attachmentContext"));
if (!attCtx) continue;
NSArray *urlAtts = ((id (*)(id, SEL))objc_msgSend)(attCtx, sel_registerName("urlAttachments"));
if (urlAtts.count == 0) continue;
NSURL *attUrl = ((id (*)(id, SEL))objc_msgSend)(urlAtts[0], sel_registerName("url"));
if (!attUrl) continue;
NSString *normalizedAtt = normalizeURL([attUrl absoluteString]);
if ([normalizedAtt isEqualToString:normalizedSearch]) {
[results addObject:rem];
}
} @catch (NSException *e) {}
}
}
return results;
}
static id findReminderByID(id store, NSString *idString) {
if (!idString) return nil;
// Accept EITHER a bare UUID or any form that contains one (emoji-URL
// wrapped, naked scheme URL, etc.). We normalize both sides.
NSString *normalizedInput = normalizeIDInput(idString);
NSArray *lists = fetchLists(store);
for (id list in lists) {
NSArray *rems = fetchReminders(store, list, YES);
for (id rem in rems) {
id objID = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("objectID"));
NSString *uuid = objectIDToUUID(objID);
if (normalizedInput && uuid && [uuid isEqualToString:normalizedInput]) return rem;
// Fallback for legacy exact-match (emoji-URL form or scheme URL)
NSString *idStr = objectIDToString(objID);
if (idStr && [idStr isEqualToString:idString]) return rem;
}
}
return nil;
}
static id requireUniqueReminder(id store, NSString *title, NSString *listName) {
NSArray *matches = findReminders(store, title, listName);
if (matches.count == 0) {
errorExit([NSString stringWithFormat:@"Reminder not found: %@", title]);
}
if (matches.count > 1) {
NSMutableString *msg = [NSMutableString stringWithFormat:@"Multiple reminders match '%@'. Use --id to specify:\\n", title];
for (id rem in matches) {
NSString *t = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("titleAsString"));
id objID = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("objectID"));
NSString *idStr = objectIDToString(objID);
[msg appendFormat:@" - \\"%@\\" (id: %@)\\n", t, idStr];
}
errorExit(msg);
}
return matches[0];
}
'''
def generate_reminder_to_dict():
"""Generate the reminderToDict function from REMINDER_READ_PROPS."""
lines = [
'static NSMutableDictionary *reminderToDict(id rem) {',
' NSMutableDictionary *dict = [NSMutableDictionary dictionary];',
'',
]
for prop, (json_key, type_hint) in REMINDER_READ_PROPS.items():
sel = prop
if type_hint == "string":
lines.append(f' @try {{')
lines.append(f' NSString *val_{json_key} = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' if (val_{json_key}) dict[@"{json_key}"] = val_{json_key};')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "bool":
lines.append(f' @try {{')
lines.append(f' BOOL val_{json_key} = ((BOOL (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' dict[@"{json_key}"] = @(val_{json_key});')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "bool_getter":
lines.append(f' @try {{')
lines.append(f' BOOL val_{json_key} = ((BOOL (*)(id, SEL))objc_msgSend)(rem, sel_registerName("isCompleted"));')
lines.append(f' dict[@"{json_key}"] = @(val_{json_key});')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "uint":
lines.append(f' @try {{')
lines.append(f' NSUInteger val_{json_key} = ((NSUInteger (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' dict[@"{json_key}"] = @(val_{json_key});')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "int":
lines.append(f' @try {{')
lines.append(f' NSInteger val_{json_key} = ((NSInteger (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' dict[@"{json_key}"] = @(val_{json_key});')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "objid_self":
# In default (v2) mode: bare UUID under "id", new "uri" field with scheme URL.
# In --full mode: exact legacy bytes under "id" (emoji-wrapped form) + new
# "uuid" field with bare UUID. Suppress "uri" in --full for byte-compat.
lines.append(f' @try {{')
lines.append(f' id val_{json_key} = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' if (val_{json_key}) {{')
lines.append(f' if (gOutputFull) {{')
lines.append(f' dict[@"{json_key}"] = objectIDToLegacyString(val_{json_key});')
lines.append(f' NSString *_uuid = objectIDToUUID(val_{json_key});')
lines.append(f' if (_uuid) dict[@"uuid"] = _uuid;')
lines.append(f' }} else {{')
lines.append(f' NSString *_uuid = objectIDToUUID(val_{json_key});')
lines.append(f' dict[@"{json_key}"] = _uuid ?: objectIDToString(val_{json_key});')
lines.append(f' NSString *_uri = objectIDToURI(val_{json_key});')
lines.append(f' if (_uri) dict[@"uri"] = _uri;')
lines.append(f' }}')
lines.append(f' }}')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "objid_ref":
# In default (v2) mode: bare UUID under "<key>Id" + x-callback URL under "<key>Uri".
# In --full mode: legacy emoji form under the original "<key>ID" key (byte-compat),
# no Uri, no Id suffix field.
base = json_key[:-2] if json_key.endswith("Id") else json_key
uri_key = base + "Uri"
legacy_key = base + "ID" # pre-v2 camelCase was listID / parentID
lines.append(f' @try {{')
lines.append(f' id val_{json_key} = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' if (val_{json_key}) {{')
lines.append(f' if (gOutputFull) {{')
lines.append(f' dict[@"{legacy_key}"] = objectIDToLegacyString(val_{json_key});')
lines.append(f' }} else {{')
lines.append(f' NSString *_uuid = objectIDToUUID(val_{json_key});')
lines.append(f' dict[@"{json_key}"] = _uuid ?: objectIDToString(val_{json_key});')
lines.append(f' NSString *_uri = objectIDToURI(val_{json_key});')
lines.append(f' if (_uri) dict[@"{uri_key}"] = _uri;')
lines.append(f' }}')
lines.append(f' }}')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "objid":
lines.append(f' @try {{')
lines.append(f' id val_{json_key} = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' if (val_{json_key}) dict[@"{json_key}"] = objectIDToString(val_{json_key});')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "date":
lines.append(f' @try {{')
lines.append(f' NSDate *val_{json_key} = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' if (val_{json_key}) dict[@"{json_key}"] = dateToISO(val_{json_key});')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "datecomps":
lines.append(f' @try {{')
lines.append(f' NSDateComponents *val_{json_key} = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("{sel}"));')
lines.append(f' if (val_{json_key}) dict[@"{json_key}"] = dateCompsToString(val_{json_key});')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "set_hashtags":
lines.append(f' @try {{')
lines.append(f' NSSet *tags = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("hashtags"));')
lines.append(f' if (tags && tags.count > 0) {{')
lines.append(f' NSMutableArray *tagNames = [NSMutableArray array];')
lines.append(f' for (id tag in tags) {{')
lines.append(f' NSString *name = ((id (*)(id, SEL))objc_msgSend)(tag, sel_registerName("name"));')
lines.append(f' if (name) [tagNames addObject:name];')
lines.append(f' }}')
lines.append(f' dict[@"{json_key}"] = tagNames;')
lines.append(f' }}')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "assignment_context":
lines.append(f' @try {{')
lines.append(f' id assignCtx = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("assignmentContext"));')
lines.append(f' if (assignCtx) {{')
lines.append(f' NSSet *assignSet = ((id (*)(id, SEL))objc_msgSend)(assignCtx, sel_registerName("assignments"));')
lines.append(f' if (assignSet && assignSet.count > 0) {{')
lines.append(f' NSMutableArray *assignArr = [NSMutableArray array];')
lines.append(f' for (id a in assignSet) {{')
lines.append(f' NSMutableDictionary *aDict = [NSMutableDictionary dictionary];')
lines.append(f' @try {{')
lines.append(f' id assigneeID = ((id (*)(id, SEL))objc_msgSend)(a, sel_registerName("assigneeID"));')
lines.append(f' if (assigneeID) aDict[@"assigneeID"] = objectIDToString(assigneeID);')
lines.append(f' }} @catch (NSException *e2) {{}}')
lines.append(f' @try {{')
lines.append(f' id originatorID = ((id (*)(id, SEL))objc_msgSend)(a, sel_registerName("originatorID"));')
lines.append(f' if (originatorID) aDict[@"originatorID"] = objectIDToString(originatorID);')
lines.append(f' }} @catch (NSException *e2) {{}}')
lines.append(f' @try {{')
lines.append(f' NSInteger status = ((NSInteger (*)(id, SEL))objc_msgSend)(a, sel_registerName("status"));')
lines.append(f' aDict[@"status"] = @(status);')
lines.append(f' }} @catch (NSException *e2) {{}}')
lines.append(f' @try {{')
lines.append(f' NSDate *assignedDate = ((id (*)(id, SEL))objc_msgSend)(a, sel_registerName("assignedDate"));')
lines.append(f' if (assignedDate) aDict[@"assignedDate"] = dateToISO(assignedDate);')
lines.append(f' }} @catch (NSException *e2) {{}}')
lines.append(f' if (aDict.count > 0) [assignArr addObject:aDict];')
lines.append(f' }}')
lines.append(f' dict[@"{json_key}"] = assignArr;')
lines.append(f' }}')
lines.append(f' }}')
lines.append(f' }} @catch (NSException *e) {{}}')
lines.append('')
lines.append(' @try {')
lines.append(' id store = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("store"));')
lines.append(' id objID = ((id (*)(id, SEL))objc_msgSend)(rem, sel_registerName("objectID"));')
lines.append(' if (store && objID) {')
lines.append(' id view = ((id (*)(id, SEL, id))objc_msgSend)([NSClassFromString(@"REMListSectionsDataView") alloc], sel_registerName("initWithStore:"), store);')
lines.append(' NSError *sectionError = nil;')
lines.append(' id section = ((id (*)(id, SEL, id, id*))objc_msgSend)(view, sel_registerName("fetchListSectionWithReminderID:error:"), objID, §ionError);')
lines.append(' if (section) {')
lines.append(' NSString *sectionName = ((id (*)(id, SEL))objc_msgSend)(section, sel_registerName("displayName"));')
lines.append(' if (!sectionName) sectionName = ((id (*)(id, SEL))objc_msgSend)(section, sel_registerName("canonicalName"));')
lines.append(' if (sectionName) dict[@"section"] = sectionName;')
lines.append(' id sectionID = ((id (*)(id, SEL))objc_msgSend)(section, sel_registerName("objectID"));')
lines.append(' if (sectionID) {')
lines.append(' NSString *_uuid = objectIDToUUID(sectionID);')
lines.append(' dict[@"sectionId"] = _uuid ?: objectIDToString(sectionID);')
lines.append(' NSString *_uri = objectIDToURI(sectionID);')
lines.append(' if (_uri) dict[@"sectionUri"] = _uri;')
lines.append(' }')
lines.append(' }')
lines.append(' }')
lines.append(' } @catch (NSException *e) {}')
lines.append('')
# URL is read via attachmentContext