-
Notifications
You must be signed in to change notification settings - Fork 395
/
mogenerator.m
1409 lines (1237 loc) · 57.1 KB
/
mogenerator.m
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
// mogenerator.m
// Copyright (c) 2006-2019 Jonathan 'Wolf' Rentzsch: http://rentzsch.com
// Some rights reserved: http://opensource.org/licenses/mit
// http://github.com/rentzsch/mogenerator
#import "mogenerator.h"
#import "NSManagedObjectModel+momcom.h"
#import "NSAttributeDescription+momcom.h"
#import "NSString+MORegEx.h"
static NSString * const kTemplateVar = @"TemplateVar";
static NSString *gCustomBaseClass;
static NSString *gCustomBaseClassImport;
static NSString *gCustomBaseClassForced;
static BOOL gSwift;
static const NSString *const kAttributeValueScalarTypeKey = @"attributeValueScalarType";
static const NSString *const kAdditionalHeaderFileNameKey = @"additionalHeaderFileName";
static const NSString *const kAdditionalImportsKey = @"additionalImports";
static const NSString *const kCustomBaseClass = @"mogenerator.customBaseClass";
static const NSString *const kReadOnly = @"mogenerator.readonly";
static const NSString *const kIgnored = @"mogenerator.ignore";
@interface NSEntityDescription (fetchedPropertiesAdditions)
- (NSDictionary*)fetchedPropertiesByName;
@end
@implementation NSEntityDescription (fetchedPropertiesAdditions)
- (NSDictionary*)fetchedPropertiesByName {
NSMutableDictionary *fetchedPropertiesByName = [NSMutableDictionary dictionary];
NSArray *properties = [self properties];
for (NSPropertyDescription *property in properties)
{
if ([property isKindOfClass:[NSFetchedPropertyDescription class]]) {
[fetchedPropertiesByName setObject:property forKey:[property name]];
}
}
return fetchedPropertiesByName;
}
@end
@interface NSEntityDescription (swiftAdditions)
- (NSString *)sanitizedManagedObjectClassName;
@end
@implementation NSEntityDescription (swiftAdditions)
- (NSString *)sanitizedManagedObjectClassName {
NSString *className = [self managedObjectClassName];
if ([className hasPrefix:@"."]) {
return [className stringByReplacingOccurrencesOfString:@"." withString:@""];
}
return className;
}
@end
@interface NSEntityDescription (userInfoAdditions)
- (BOOL)hasUserInfoKeys;
- (NSDictionary *)userInfoByKeys;
@end
@implementation NSEntityDescription (userInfoAdditions)
- (NSDictionary*)sanitizedUserInfo {
NSMutableCharacterSet *validCharacters = [[[NSCharacterSet letterCharacterSet] mutableCopy] autorelease];
[validCharacters formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
[validCharacters addCharactersInString:@"_"];
NSCharacterSet *invalidCharacters = [validCharacters invertedSet];
NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:[[self userInfo] count]];
for (NSString *key in self.userInfo) {
if ([key rangeOfCharacterFromSet:invalidCharacters].location == NSNotFound) {
NSString *value = [self.userInfo objectForKey:key];
value = [value stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
[result setObject:value forKey:key];
}
}
return result;
}
- (BOOL)hasUserInfoKeys {
return ([self.sanitizedUserInfo count] > 0);
}
- (NSDictionary *)userInfoByKeys {
NSMutableDictionary *userInfoByKeys = [NSMutableDictionary dictionary];
for (NSString *key in self.sanitizedUserInfo)
[userInfoByKeys setObject:[NSDictionary dictionaryWithObjectsAndKeys:key, @"key", [self.sanitizedUserInfo objectForKey:key], @"value", nil] forKey:key];
return userInfoByKeys;
}
@end
@implementation NSManagedObjectModel (entitiesWithACustomSubclassVerbose)
- (NSArray*)entitiesWithACustomSubclassInConfiguration:(NSString*)configuration_ verbose:(BOOL)verbose_ {
NSMutableArray *result = [NSMutableArray array];
NSArray* allEntities = nil;
if (nil == configuration_) {
allEntities = [self entities];
}
else if (NSNotFound != [[self configurations] indexOfObject:configuration_]){
allEntities = [self entitiesForConfiguration:configuration_];
}
else {
if (verbose_){
ddprintf(@"No configuration %@ found in model. No files will be generated.\n(model configurations: %@)\n", configuration_, [self configurations]);
}
return nil;
}
if (verbose_ && [allEntities count] == 0){
ddprintf(@"No entities found in model (or in specified configuration). No files will be generated.\n(model description: %@)\n", self);
}
for (NSEntityDescription *entity in allEntities)
{
NSString *entityClassName = [entity managedObjectClassName];
if ([entity hasCustomClass]){
[result addObject:entity];
} else {
if (verbose_) {
ddprintf(@"skipping entity %@ (%@) because it doesn't use a custom subclass.\n",
entity.name, entityClassName);
}
}
}
return [result sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"managedObjectClassName"
ascending:YES] autorelease]]];
}
@end
@implementation NSEntityDescription (userInfo)
- (BOOL)isIgnored {
NSString *readonlyUserinfoValue = [[self userInfo] objectForKey:kIgnored];
if (readonlyUserinfoValue != nil) {
return YES;
}
return NO;
}
@end
@implementation NSEntityDescription (customBaseClass)
- (BOOL)hasCustomBaseCaseImport {
return gCustomBaseClassImport == nil ? NO : YES;
}
- (NSString*)baseClassImport {
return gCustomBaseClassImport;
}
- (BOOL)hasCustomClass {
NSString *entityClassName = [self managedObjectClassName];
BOOL result = !([entityClassName isEqualToString:@"NSManagedObject"]
|| [entityClassName isEqualToString:@""]
|| [entityClassName isEqualToString:gCustomBaseClass]);
return result;
}
- (BOOL)hasSuperentity {
NSEntityDescription *superentity = [self superentity];
if (superentity) {
return YES;
}
return NO;
}
- (BOOL)hasCustomSuperentity {
NSString *forcedBaseClass = [self forcedCustomBaseClass];
if (!forcedBaseClass) {
NSEntityDescription *superentity = [self superentity];
if (superentity) {
return [superentity hasCustomClass] ? YES : NO;
} else {
return gCustomBaseClass ? YES : NO;
}
} else {
return YES;
}
}
- (BOOL)hasCustomSuperclass {
// For Swift, where "override" is needed when both the entity and its superentity have custom classes.
BOOL result = [self hasCustomClass] && [self hasCustomSuperentity] && [[self superentity] hasCustomClass];
return result;
}
- (BOOL)hasAdditionalHeaderFile {
return [[[self userInfo] allKeys] containsObject:kAdditionalHeaderFileNameKey];
}
- (BOOL)hasAdditionalImports {
return [[[self userInfo] allKeys] containsObject:kAdditionalImportsKey];
}
- (NSString*)customSuperentity {
NSString *forcedBaseClass = [self forcedCustomBaseClass];
if (!forcedBaseClass) {
NSEntityDescription *superentity = [self superentity];
if (superentity) {
return [superentity managedObjectClassName];
} else {
return gCustomBaseClass ? gCustomBaseClass : @"NSManagedObject";
}
} else {
return forcedBaseClass;
}
}
- (NSString*)sanitizedCustomSuperentity {
NSString *customSuperentity = [self customSuperentity];
if ([customSuperentity hasPrefix:@"."]) {
return [customSuperentity stringByReplacingOccurrencesOfString:@"." withString:@""];
}
return customSuperentity;
}
- (NSString*)forcedCustomBaseClass {
NSString* userInfoCustomBaseClass = [[self userInfo] objectForKey:kCustomBaseClass];
return userInfoCustomBaseClass ? userInfoCustomBaseClass : gCustomBaseClassForced;
}
/** @TypeInfo NSAttributeDescription */
- (NSArray*)allAttributes {
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
return [[[self attributesByName] allValues] sortedArrayUsingDescriptors:sortDescriptors];
}
/** @TypeInfo NSAttributeDescription */
- (NSArray*)noninheritedAttributes {
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
NSEntityDescription *superentity = [self superentity];
if (superentity) {
NSMutableArray *result = [[[[self attributesByName] allValues] mutableCopy] autorelease];
[result removeObjectsInArray:[[superentity attributesByName] allValues]];
return [result sortedArrayUsingDescriptors:sortDescriptors];
} else {
return [[[self attributesByName] allValues] sortedArrayUsingDescriptors:sortDescriptors];
}
}
- (NSString*)additionalHeaderFileName {
return [[self userInfo] objectForKey:kAdditionalHeaderFileNameKey];
}
- (NSArray *)additionalImports {
NSString *csvString = [[self userInfo] objectForKey:kAdditionalImportsKey];
NSMutableArray *imports = [[csvString componentsSeparatedByString:@","] mutableCopy];
[imports enumerateObjectsUsingBlock:^(NSString *import, NSUInteger idx, BOOL * _Nonnull stop) {
imports[idx] = [import stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
}];
return imports;
}
/** @TypeInfo NSAttributeDescription */
- (NSArray*)noninheritedAttributesSansType {
NSArray *attributeDescriptions = [self noninheritedAttributes];
NSMutableArray *filteredAttributeDescriptions = [NSMutableArray arrayWithCapacity:[attributeDescriptions count]];
for (NSAttributeDescription *attributeDescription in attributeDescriptions)
{
if ([[attributeDescription name] isEqualToString:@"type"]) {
ddprintf(@"WARNING skipping 'type' attribute on %@ (%@) - see https://github.com/rentzsch/mogenerator/issues/74\n",
self.name, self.managedObjectClassName);
} else {
[filteredAttributeDescriptions addObject:attributeDescription];
}
}
return filteredAttributeDescriptions;
}
/** @TypeInfo NSRelationshipDescription */
- (NSArray*)allRelationships {
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
return [[[self relationshipsByName] allValues] sortedArrayUsingDescriptors:sortDescriptors];
}
/** @TypeInfo NSRelationshipDescription */
- (NSArray*)noninheritedRelationships {
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
NSEntityDescription *superentity = [self superentity];
if (superentity) {
NSMutableArray *result = [[[[self relationshipsByName] allValues] mutableCopy] autorelease];
[result removeObjectsInArray:[[superentity relationshipsByName] allValues]];
return [result sortedArrayUsingDescriptors:sortDescriptors];
} else {
return [[[self relationshipsByName] allValues] sortedArrayUsingDescriptors:sortDescriptors];
}
}
/** @TypeInfo NSEntityUserInfoDescription */
- (NSArray*)userInfoKeyValues {
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES]];
NSEntityDescription *superentity = [self superentity];
if (superentity) {
NSMutableArray *result = [[[[self userInfoByKeys] allValues] mutableCopy] autorelease];
[result removeObjectsInArray:[[superentity userInfoByKeys] allValues]];
return [result sortedArrayUsingDescriptors:sortDescriptors];
} else {
return [[[self userInfoByKeys] allValues] sortedArrayUsingDescriptors:sortDescriptors];
}
}
/** @TypeInfo NSFetchedPropertyDescription */
- (NSArray*)noninheritedFetchedProperties {
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
NSEntityDescription *superentity = [self superentity];
if (superentity) {
NSMutableArray *result = [[[[self fetchedPropertiesByName] allValues] mutableCopy] autorelease];
[result removeObjectsInArray:[[superentity fetchedPropertiesByName] allValues]];
return [result sortedArrayUsingDescriptors:sortDescriptors];
} else {
return [[[self fetchedPropertiesByName] allValues] sortedArrayUsingDescriptors:sortDescriptors];
}
}
/** @TypeInfo NSAttributeDescription */
- (NSArray*)indexedNoninheritedAttributes {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isIndexed == YES"];
return [[self noninheritedAttributes] filteredArrayUsingPredicate:predicate];
}
#pragma mark Fetch Request support
- (NSDictionary*)fetchRequestTemplates {
// -[NSManagedObjectModel _fetchRequestTemplatesByName] is a private method, but it's the only way to get
// model fetch request templates without knowing their name ahead of time. rdar://problem/4901396 asks for
// a public method (-[NSManagedObjectModel fetchRequestTemplatesByName]) that does the same thing.
// If that request is fulfilled, this code won't need to be modified thanks to KVC lookup order magic.
// UPDATE: 10.5 now has a public -fetchRequestTemplatesByName method.
NSDictionary *fetchRequests = [[self managedObjectModel] valueForKey:@"fetchRequestTemplatesByName"];
NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:[fetchRequests count]];
NSArray *keys = [fetchRequests allKeys];
for (NSString *fetchRequestName in keys)
{
NSFetchRequest *fetchRequest = [fetchRequests objectForKey:fetchRequestName];
if ([fetchRequest entity] == self) {
[result setObject:fetchRequest forKey:fetchRequestName];
}
}
return result;
}
- (NSString*)_resolveKeyPathType:(NSString*)keyPath {
NSArray *components = [keyPath componentsSeparatedByString:@"."];
// Hope the set of keys in the key path consists of solely relationships. Abort otherwise
NSEntityDescription *entity = self;
for (NSString *key in components)
{
id property = [[entity propertiesByName] objectForKey:key];
if ([property isKindOfClass:[NSAttributeDescription class]]) {
NSString *result = [property objectAttributeType];
return gSwift ? result : [result substringToIndex:[result length] -1];
} else if ([property isKindOfClass:[NSRelationshipDescription class]]) {
entity = [property destinationEntity];
}
assert(property);
}
return [entity managedObjectClassName];
}
// auxiliary function
- (BOOL)bindingsArray:(NSArray*)bindings containsVariableNamed:(NSString*)name {
for (NSDictionary *dict in bindings) {
if ([[dict objectForKey:@"name"] isEqual:name]) {
return YES;
}
}
return NO;
}
- (void)_processPredicate:(NSPredicate*)predicate_ bindings:(NSMutableArray*)bindings_ {
if (!predicate_) return;
if ([predicate_ isKindOfClass:[NSCompoundPredicate class]]) {
for (NSPredicate *subpredicate in [(NSCompoundPredicate*)predicate_ subpredicates])
{
[self _processPredicate:subpredicate bindings:bindings_];
}
} else if ([predicate_ isKindOfClass:[NSComparisonPredicate class]]) {
assert([[(NSComparisonPredicate*)predicate_ leftExpression] expressionType] == NSKeyPathExpressionType);
NSExpression *lhs = [(NSComparisonPredicate*)predicate_ leftExpression];
NSExpression *rhs = [(NSComparisonPredicate*)predicate_ rightExpression];
switch([rhs expressionType]) {
case NSConstantValueExpressionType:
case NSEvaluatedObjectExpressionType:
case NSKeyPathExpressionType:
case NSFunctionExpressionType:
// Don't do anything with these.
break;
case NSVariableExpressionType: {
// TODO SHOULD Handle LHS keypaths.
NSString *type = nil;
NSAttributeDescription *attribute = [[self attributesByName] objectForKey:[lhs keyPath]];
if (attribute) {
type = [attribute objectAttributeClassName];
} else {
type = [self _resolveKeyPathType:[lhs keyPath]];
}
if (!gSwift) {
type = [type stringByAppendingString:@"*"];
}
// make sure that no repeated variables are entered here.
if (![self bindingsArray:bindings_ containsVariableNamed:[rhs variable]]) {
[bindings_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[rhs variable], @"name",
type, @"type",
nil]];
}
} break;
default:
assert(0 && "unknown NSExpression type");
}
}
}
- (NSArray*)prettyFetchRequests {
NSDictionary *fetchRequests = [self fetchRequestTemplates];
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[fetchRequests count]];
NSArray *keys = [fetchRequests allKeys];
for (NSString *fetchRequestName in keys)
{
NSFetchRequest *fetchRequest = [fetchRequests objectForKey:fetchRequestName];
NSMutableArray *bindings = [NSMutableArray array];
[self _processPredicate:[fetchRequest predicate] bindings:bindings];
[result addObject:[NSDictionary dictionaryWithObjectsAndKeys:
fetchRequestName, @"name",
bindings, @"bindings",
[NSNumber numberWithBool:[bindings count] > 0], @"hasBindings",
[NSNumber numberWithBool:[fetchRequestName hasPrefix:@"one"]], @"singleResult",
nil]];
}
return result;
}
@end
@implementation NSAttributeDescription (typing)
- (BOOL)isUnsigned
{
BOOL isUnsigned = NO;
for (NSPredicate *pred in [self validationPredicates]) {
NSString* formatString = pred.predicateFormat;
NSRange range = [formatString rangeOfString:@"SELF >="];
if (range.location != NSNotFound) {
NSUInteger startIndex = range.location + range.length;
NSString *minString = [formatString substringFromIndex:startIndex];
NSScanner *scanner = [NSScanner scannerWithString:minString];
NSInteger minValue;
BOOL success = [scanner scanInteger:&minValue];
if (success && (minValue >= 0)) {
isUnsigned = YES;
break;
}
}
}
return isUnsigned;
}
- (BOOL)hasScalarAttributeType {
switch ([self attributeType]) {
case NSInteger16AttributeType:
case NSInteger32AttributeType:
case NSInteger64AttributeType:
case NSDoubleAttributeType:
case NSFloatAttributeType:
case NSBooleanAttributeType:
return YES;
break;
default:
return NO;
}
}
- (BOOL)usesScalarAttributeType {
NSNumber *usesScalarAttributeType = [[self userInfo] objectForKey:kUsesScalarAttributeType];
if (usesScalarAttributeType) {
return usesScalarAttributeType.boolValue;
} else {
return NO;
}
}
- (BOOL)usesCustomScalarAttributeType {
NSString *attributeValueScalarType = [[self userInfo] objectForKey:kAttributeValueScalarTypeKey];
return (attributeValueScalarType != nil);
}
- (NSString*)scalarAttributeType {
BOOL isUnsigned = [self isUnsigned];
NSString *attributeValueScalarType = [[self userInfo] objectForKey:kAttributeValueScalarTypeKey];
if (attributeValueScalarType) {
return attributeValueScalarType;
} else {
switch ([self attributeType]) {
case NSInteger16AttributeType:
return gSwift ? isUnsigned ? @"UInt16" : @"Int16" : isUnsigned ? @"uint16_t" : @"int16_t";
break;
case NSInteger32AttributeType:
return gSwift ? isUnsigned ? @"UInt32" : @"Int32" : isUnsigned ? @"uint32_t" : @"int32_t";
break;
case NSInteger64AttributeType:
return gSwift ? isUnsigned ? @"UInt64" : @"Int64" : isUnsigned ? @"uint64_t" : @"int64_t";
break;
case NSDoubleAttributeType:
return gSwift ? @"Double" : @"double";
break;
case NSFloatAttributeType:
return gSwift ? @"Float" : @"float";
break;
case NSBooleanAttributeType:
return gSwift ? @"Bool" : @"BOOL";
break;
default:
return nil;
}
}
}
- (NSString*)scalarAccessorMethodName {
BOOL isUnsigned = [self isUnsigned];
switch ([self attributeType]) {
case NSInteger16AttributeType:
if (isUnsigned) {
return @"unsignedShortValue";
}
return @"shortValue";
break;
case NSInteger32AttributeType:
if (isUnsigned) {
return @"unsignedIntValue";
}
return @"intValue";
break;
case NSInteger64AttributeType:
if (isUnsigned) {
return @"unsignedLongLongValue";
}
return @"longLongValue";
break;
case NSDoubleAttributeType:
return @"doubleValue";
break;
case NSFloatAttributeType:
return @"floatValue";
break;
case NSBooleanAttributeType:
return @"boolValue";
break;
default:
return nil;
}
}
- (NSString*)scalarFactoryMethodName {
BOOL isUnsigned = [self isUnsigned];
switch ([self attributeType]) {
case NSInteger16AttributeType:
if (isUnsigned) {
return @"numberWithUnsignedShort:";
}
return @"numberWithShort:";
break;
case NSInteger32AttributeType:
if (isUnsigned) {
return @"numberWithUnsignedInt:";
}
return @"numberWithInt:";
break;
case NSInteger64AttributeType:
if (isUnsigned) {
return @"numberWithUnsignedLongLong:";
}
return @"numberWithLongLong:";
break;
case NSDoubleAttributeType:
return @"numberWithDouble:";
break;
case NSFloatAttributeType:
return @"numberWithFloat:";
break;
case NSBooleanAttributeType:
return @"numberWithBool:";
break;
default:
return nil;
}
}
- (BOOL)hasDefinedAttributeType {
return [self attributeType] != NSUndefinedAttributeType;
}
- (NSString*)objectAttributeClassName {
NSString *result = nil;
if ([self hasTransformableAttributeType]) {
result = [[self userInfo] objectForKey:@"attributeValueClassName"];
if (!result) {
result = gSwift ? @"AnyObject" : @"NSObject";
}
} else {
// Forcibly generate the correct class name in case we are
// running on macOS < 10.13
switch ([self attributeType]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
case NSURIAttributeType:
result = @"NSURL";
break;
case NSUUIDAttributeType:
result = @"NSUUID";
break;
#pragma clang diagnostic pop
default:
result = [self attributeValueClassName];
}
}
if (gSwift) {
if ([result isEqualToString:@"NSString"]) {
result = @"String";
} else if ([result isEqualToString:@"NSDate"]) {
result = @"Date";
} else if ([result isEqualToString:@"NSData"]) {
result = @"Data";
} else if ([result isEqualToString:@"NSURL"]) {
result = @"URL";
} else if ([result isEqualToString:@"NSUUID"]) {
result = @"UUID";
}
}
return result;
}
- (NSArray*)objectAttributeTransformableProtocols {
if ([self hasAttributeTransformableProtocols]) {
NSString *protocolsString = [[self userInfo] objectForKey:@"attributeTransformableProtocols"];
NSCharacterSet *removeCharSet = [NSCharacterSet characterSetWithCharactersInString:@", "];
NSMutableArray *protocols = [NSMutableArray arrayWithArray:[protocolsString componentsSeparatedByCharactersInSet:removeCharSet]];
[protocols removeObject:@""];
return protocols;
}
return nil;
}
- (BOOL)hasAttributeTransformableProtocols {
return [self hasTransformableAttributeType] && [[self userInfo] objectForKey:@"attributeTransformableProtocols"];
}
- (BOOL)usesCustomObjectAttributeType {
NSString *attributeValueClassName = [[self userInfo] objectForKey:@"attributeValueClassName"];
return (attributeValueClassName != nil);
}
- (NSString*)objectAttributeType {
NSString *result = [self objectAttributeClassName];
if ([result isEqualToString:@"Class"]) {
// `Class` (don't append asterisk).
} else if ([result rangeOfString:@"<"].location != NSNotFound) {
// `id<Protocol1,Protocol2>` (don't append asterisk).
} else if ([result isEqualToString:@"NSObject"]) {
result = gSwift ? @"AnyObject" : @"id";
} else if (!gSwift) {
result = [result stringByAppendingString:@"*"]; // Make it a pointer.
}
return result;
}
- (BOOL)hasTransformableAttributeType {
return ([self attributeType] == NSTransformableAttributeType);
}
- (BOOL)isReadonly {
NSString *readonlyUserinfoValue = [[self userInfo] objectForKey:kReadOnly];
if (readonlyUserinfoValue != nil) {
return YES;
}
return NO;
}
@end
@implementation NSRelationshipDescription (collectionClassName)
- (NSString*)jr_CollectionClassStringWithOrderedClassName:(NSString*)orderedClassName
unorderedClassName:(NSString*)unorderedClassName
{
NSString *generic = [NSString stringWithFormat:@"<%@*>", self.destinationEntity.managedObjectClassName];
if (gSwift) {
// No generics for Swift sets, for now.
return [self jr_isOrdered] ? orderedClassName : unorderedClassName;
}
return [self jr_isOrdered]
? [orderedClassName stringByAppendingString:generic]
: [unorderedClassName stringByAppendingString:generic];
}
- (NSString*)mutableCollectionClassName {
return [self jr_CollectionClassStringWithOrderedClassName:@"NSMutableOrderedSet"
unorderedClassName:@"NSMutableSet"];
}
- (NSString*)immutableCollectionClassName {
return [self jr_CollectionClassStringWithOrderedClassName:@"NSOrderedSet"
unorderedClassName:@"NSSet"];
}
- (BOOL)jr_isOrdered {
if ([self respondsToSelector:@selector(isOrdered)]) {
return [self isOrdered];
} else {
return NO;
}
}
@end
@implementation NSString (camelCaseString)
- (NSString*)camelCaseString {
NSArray *lowerCasedWordArray = [[self wordArray] arrayByMakingObjectsPerformSelector:@selector(lowercaseString)];
NSUInteger wordIndex = 1, wordCount = [lowerCasedWordArray count];
NSMutableArray *camelCasedWordArray = [NSMutableArray arrayWithCapacity:wordCount];
if (wordCount)
[camelCasedWordArray addObject:[lowerCasedWordArray objectAtIndex:0]];
for (; wordIndex < wordCount; wordIndex++) {
[camelCasedWordArray addObject:[[lowerCasedWordArray objectAtIndex:wordIndex] initialCapitalString]];
}
return [camelCasedWordArray componentsJoinedByString:@""];
}
@end
@interface MogeneratorTemplateDesc : NSObject {
NSString *templateName;
NSString *templatePath;
}
- (instancetype)initWithName:(NSString*)name_ path:(NSString*)path_;
- (NSString*)templateName;
- (void)setTemplateName:(NSString*)name_;
- (NSString*)templatePath;
- (void)setTemplatePath:(NSString*)path_;
@end
static MiscMergeEngine* engineWithTemplateDesc(MogeneratorTemplateDesc *templateDesc_) {
MiscMergeTemplate *template = [[[MiscMergeTemplate alloc] init] autorelease];
[template setStartDelimiter:@"<$" endDelimiter:@"$>"];
if ([templateDesc_ templatePath]) {
[template parseContentsOfFile:[templateDesc_ templatePath]];
} else {
NSData *templateData = [[NSBundle mainBundle] objectForInfoDictionaryKey:[templateDesc_ templateName]];
assert(templateData);
NSString *templateString = [[[NSString alloc] initWithData:templateData encoding:NSUTF8StringEncoding] autorelease];
[template setFilename:[@"x-__info_plist://" stringByAppendingString:[templateDesc_ templateName]]];
[template parseString:templateString];
}
return [[[MiscMergeEngine alloc] initWithTemplate:template] autorelease];
}
@implementation MOGeneratorApp
- (id)init {
self = [super init];
if (self) {
templateVar = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)dealloc {
[templateVar release];
[super dealloc];
}
NSString *ApplicationSupportSubdirectoryName = @"mogenerator";
- (MogeneratorTemplateDesc*)templateDescNamed:(NSString*)fileName_ {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory;
if (templatePath) {
if ([fileManager fileExistsAtPath:templatePath isDirectory:&isDirectory] && isDirectory) {
return [[[MogeneratorTemplateDesc alloc] initWithName:fileName_
path:[templatePath stringByAppendingPathComponent:fileName_]] autorelease];
}
} else if (templateGroup) {
NSArray *appSupportDirectories = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask+NSLocalDomainMask, YES);
assert(appSupportDirectories);
for (NSString *appSupportDirectory in appSupportDirectories)
{
if ([fileManager fileExistsAtPath:appSupportDirectory isDirectory:&isDirectory]) {
NSString *appSupportSubdirectory = [appSupportDirectory stringByAppendingPathComponent:ApplicationSupportSubdirectoryName];
appSupportSubdirectory = [appSupportSubdirectory stringByAppendingPathComponent:templateGroup];
if ([fileManager fileExistsAtPath:appSupportSubdirectory isDirectory:&isDirectory] && isDirectory) {
NSString *appSupportFile = [appSupportSubdirectory stringByAppendingPathComponent:fileName_];
if ([fileManager fileExistsAtPath:appSupportFile isDirectory:&isDirectory] && !isDirectory) {
return [[[MogeneratorTemplateDesc alloc] initWithName:fileName_ path:appSupportFile] autorelease];
}
}
}
}
} else {
return [[[MogeneratorTemplateDesc alloc] initWithName:fileName_ path:nil] autorelease];
}
ddprintf(@"templateDescNamed:@\"%@\": file not found", fileName_);
exit(EXIT_FAILURE);
return nil;
}
- (void)application:(DDCliApplication*)app
willParseOptions:(DDGetoptLongParser*)optionsParser;
{
[optionsParser setGetoptLongOnly:YES];
DDGetoptOption optionTable[] =
{
// Long Short Argument options
{@"v2", '2', DDGetoptNoArgument},
{@"model", 'm', DDGetoptRequiredArgument},
{@"configuration", 'C', DDGetoptRequiredArgument},
{@"base-class", 0, DDGetoptRequiredArgument},
{@"base-class-import", 0, DDGetoptRequiredArgument},
{@"base-class-force", 0, DDGetoptRequiredArgument},
// For compatibility:
{@"baseClass", 0, DDGetoptRequiredArgument},
{@"includem", 0, DDGetoptRequiredArgument},
{@"includeh", 0, DDGetoptRequiredArgument},
{@"template-path", 0, DDGetoptRequiredArgument},
// For compatibility:
{@"templatePath", 0, DDGetoptRequiredArgument},
{@"output-dir", 'O', DDGetoptRequiredArgument},
{@"machine-dir", 'M', DDGetoptRequiredArgument},
{@"human-dir", 'H', DDGetoptRequiredArgument},
{@"template-group", 0, DDGetoptRequiredArgument},
{@"list-source-files", 0, DDGetoptNoArgument},
{@"orphaned", 0, DDGetoptNoArgument},
{@"help", 'h', DDGetoptNoArgument},
{@"version", 0, DDGetoptNoArgument},
{@"template-var", 0, DDGetoptKeyValueArgument},
{@"swift", 'S', DDGetoptNoArgument},
{nil, 0, 0},
};
[optionsParser addOptionsFromTable:optionTable];
[optionsParser setArgumentsFilename:@".mogenerator-args"];
}
- (void)printUsage {
printf("\n"
"Mogenerator Help\n"
"================\n"
"\n"
"Mogenerator generates code from your Core Data model files.\n"
"\n"
"Typical Use\n"
"-----------\n"
"\n"
"$ mogenerator --model MyModel.xcdatamodeld --output-dir MyModel\n"
"\n"
"Use the --model argument to supply the required data model file.\n"
"\n"
"If --output-dir is optional but recommended. If not supplied, mogenerator will\n"
"output generated files into the current directory.\n"
"\n"
"All Options\n"
"-----------\n"
"\n"
"--model MODEL Path to model\n"
"--output-dir DIR Output directory\n"
"--swift Generate Swift templates instead of Objective-C\n"
"--configuration CONFIG Only consider entities included in the named\n"
" configuration\n"
"--base-class CLASS Custom base class\n"
"--base-class-import TEXT Imports base class as #import TEXT\n"
"--base-class-force CLASS Same as --base-class except will force all entities to\n"
" have the specified base class. Even if a super entity\n"
" exists\n"
"--includem FILE Generate aggregate include file for .m files for both\n"
" human and machine generated source files\n"
"--includeh FILE Generate aggregate include file for .h files for human\n"
" generated source files only\n"
"--template-path PATH Path to templates (absolute or relative to model path)\n"
"--template-group NAME Name of template group\n"
"--template-var KEY=VALUE A key-value pair to pass to the template file. There\n"
" can be many of these.\n"
"--machine-dir DIR Output directory for machine files\n"
"--human-dir DIR Output directory for human files\n"
"--list-source-files Only list model-related source files\n"
"--orphaned Only list files whose entities no longer exist\n"
"--version Display version and exit\n"
"--help Display this help and exit\n"
);
}
- (NSString*)xcodeSelectPrintPath {
NSString *result = @"";
@try {
NSTask *task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:@"/usr/bin/xcode-select"];
[task setArguments:[NSArray arrayWithObject:@"-print-path"]];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
// Ensures that the current tasks output doesn't get hijacked
[task setStandardInput:[NSPipe pipe]];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
NSData *data = [file readDataToEndOfFile];
result = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
result = [result substringToIndex:[result length]-1]; // trim newline
} @catch(NSException *ex) {
ddprintf(@"WARNING couldn't launch /usr/bin/xcode-select\n");
}
return result;
}
- (void)setModel:(NSString*)momOrXCDataModelFilePath {
assert(!model); // Currently we only can load one model.
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:momOrXCDataModelFilePath]) {
NSString *reason = [NSString stringWithFormat:@"error loading file at %@: no such file exists", momOrXCDataModelFilePath];
DDCliParseException *e = [DDCliParseException parseExceptionWithReason:reason
exitCode:EX_NOINPUT];
@throw e;
}
origModelBasePath = [momOrXCDataModelFilePath stringByDeletingLastPathComponent];
// If given a data model bundle (.xcdatamodeld) file, assume its "current" data model file.
if ([[momOrXCDataModelFilePath pathExtension] isEqualToString:@"xcdatamodeld"]) {
// xcdatamodeld bundles have a ".xccurrentversion" plist file in them with a
// "_XCCurrentVersionName" key representing the current model's file name.
NSString *xccurrentversionPath = [momOrXCDataModelFilePath stringByAppendingPathComponent:@".xccurrentversion"];
if ([fm fileExistsAtPath:xccurrentversionPath]) {
NSDictionary *xccurrentversionPlist = [NSDictionary dictionaryWithContentsOfFile:xccurrentversionPath];
NSString *currentModelName = [xccurrentversionPlist objectForKey:@"_XCCurrentVersionName"];
if (currentModelName) {
momOrXCDataModelFilePath = [momOrXCDataModelFilePath stringByAppendingPathComponent:currentModelName];
}
}
else {
// Freshly created models with only one version do NOT have a .xccurrentversion file, but only have one model
// in them. Use that model.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self endswith %@", @".xcdatamodel"];
NSArray *contents = [[fm contentsOfDirectoryAtPath:momOrXCDataModelFilePath error:nil]
filteredArrayUsingPredicate:predicate];
if (contents.count == 1) {
momOrXCDataModelFilePath = [momOrXCDataModelFilePath stringByAppendingPathComponent:[contents lastObject]];
}
}
}
NSString *momFilePath = nil;
if ([[momOrXCDataModelFilePath pathExtension] isEqualToString:@"xcdatamodel"]) {
// We've been handed a .xcdatamodel data model, transparently compile it into a .mom managed object model.
NSString *contentsPath = [momOrXCDataModelFilePath stringByAppendingPathComponent:@"contents"];
if ([[NSFileManager defaultManager] fileExistsAtPath:contentsPath]) {
// Cool, the model is in the Xcode 4.0+ format, we can compile it ourselves.
NSError *compileError = nil;
momFilePath = [NSManagedObjectModel compileModelAtPath:momOrXCDataModelFilePath inDirectory:NSTemporaryDirectory() error:&compileError];
if (momFilePath == nil) {
NSLog(@"Error: %@", [compileError localizedDescription]);
}
assert(momFilePath);
} else {
NSString *momcTool = nil;
{{
if (NO && [fm fileExistsAtPath:@"/usr/bin/xcrun"]) {
// Cool, we can just use Xcode 3.2.6/4.x's xcrun command to find and execute momc for us.
momcTool = @"/usr/bin/xcrun momc";
} else {
// Rats, don't have xcrun. Hunt around for momc in various places where various versions of Xcode stashed it.
NSString *xcodeSelectMomcPath = [NSString stringWithFormat:@"%@/usr/bin/momc", [self xcodeSelectPrintPath]];
if ([fm fileExistsAtPath:xcodeSelectMomcPath]) {
momcTool = [NSString stringWithFormat:@"\"%@\"", xcodeSelectMomcPath]; // Quote for safety.
} else if ([fm fileExistsAtPath:@"/Applications/Xcode.app/Contents/Developer/usr/bin/momc"]) {
// Xcode 4.3 - Command Line Tools for Xcode
momcTool = @"/Applications/Xcode.app/Contents/Developer/usr/bin/momc";
} else if ([fm fileExistsAtPath:@"/Developer/usr/bin/momc"]) {
// Xcode 3.1.
momcTool = @"/Developer/usr/bin/momc";
} else if ([fm fileExistsAtPath:@"/Library/Application Support/Apple/Developer Tools/Plug-ins/XDCoreDataModel.xdplugin/Contents/Resources/momc"]) {
// Xcode 3.0.
momcTool = @"\"/Library/Application Support/Apple/Developer Tools/Plug-ins/XDCoreDataModel.xdplugin/Contents/Resources/momc\"";
} else if ([fm fileExistsAtPath:@"/Developer/Library/Xcode/Plug-ins/XDCoreDataModel.xdplugin/Contents/Resources/momc"]) {
// Xcode 2.4.