forked from atg/Ingredients
-
Notifications
You must be signed in to change notification settings - Fork 2
/
IGKScraper.m
2143 lines (1760 loc) · 67.6 KB
/
IGKScraper.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
//
// IGKScraper.m
// Ingredients
//
// Created by Alex Gordon on 24/01/2010.
// Written in 2010 by Fileability.
//
#import "IGKScraper.h"
#import "RegexKitLite.h"
#import "IGKDocRecordManagedObject.h"
#import "IGKLaunchController.h"
#import "NSXMLNode+IGKAdditions.h"
#import "NSString+Utilities.h"
#import "IGKDocSetManagedObject.h"
@interface IGKScraper ()
- (NSUInteger)backgroundSearch:(NSManagedObject *)docset;
+ (NSArray *)pathOfDeprecationAppendiciesForPath:(NSString *)indexPath;
- (NSManagedObject *)extractPath:(NSString *)extractPath relativeExtractPath:(NSString *)relativeExtractPath docset:(NSManagedObject *)docset isDeprecationAppendix:(BOOL)isDeprecationAppendix mainObjectIn:(NSManagedObject *)mainObjectIn;
- (NSManagedObject *)addRecordNamed:(NSString *)recordName entityName:(NSString *)entityName desc:(NSString *)recordDesc sourcePath:(NSString *)recordPath;
@end
@implementation IGKScraper
NSString *const kIGKDocsetPrefixPath = @"Contents/Resources/Documents/documentation";
- (id)initWithDocsetURL:(NSURL *)theDocsetURL managedObjectContext:(NSManagedObjectContext *)moc launchController:(IGKLaunchController*)lc dbQueue:(dispatch_queue_t)dbq developerDirectory:(NSString *)devDir
{
if (self = [super init])
{
docsetURL = [theDocsetURL copy];
docsetpath = [docsetURL path];
url = [docsetURL URLByAppendingPathComponent:kIGKDocsetPrefixPath];
ctx = moc;
developerDirectory = devDir;
launchController = lc;
dbQueue = dbq;
}
return self;
}
- (BOOL)findPaths
{
//Get the info.plist
NSDictionary *infoPlist = [[NSDictionary alloc] initWithContentsOfURL:[docsetURL URLByAppendingPathComponent:@"Contents/Info.plist"]];
NSLog(@"Finding paths for %@", docsetURL);
NSString *bundleIdentifier = [infoPlist objectForKey:@"CFBundleIdentifier"];
//Reject Xcode documentation
if (!bundleIdentifier || [bundleIdentifier isEqual:@"com.apple.adc.documentation.AppleXcode.DeveloperTools"])
return NO;
NSString *localizedUserInterfaceName = IGKDocSetLocalizedUserInterfaceName([infoPlist objectForKey:@"DocSetPlatformFamily"], [infoPlist objectForKey:@"DocSetPlatformVersion"]);
//Register it with preferences
int result = [[NSClassFromString(@"IGKPreferencesController") sharedPreferencesController] addDocsetWithPath:[docsetURL path]
localizedUserInterfaceName:localizedUserInterfaceName
developerDirectory:developerDirectory];
/*
if result == -1
No docset already exists
if result == 0
Docset already exists but is disabled
if result == 1
Docset already exists and is enable
*/
if (result == 0)
{
return NO;
}
NSString *version = [infoPlist objectForKey:@"CFBundleVersion"];
if (bundleIdentifier && version)
{
//Find out if we've already parsed
NSPredicate *countPredicate = [NSPredicate predicateWithFormat:@"bundleIdentifier == %@ and version == %@", bundleIdentifier, version];
NSError *error = nil;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"Docset" inManagedObjectContext:ctx]];
[fetch setPredicate:countPredicate];
NSUInteger recordCount = [ctx countForFetchRequest:fetch error:&error];
if (!error && recordCount > 0)
{
//There's already some records - don't parse
NSLog(@"Docset already exists: %@ / %@", version, bundleIdentifier);
return NO;
}
}
//*** Create a docset object ***
NSEntityDescription *docsetEntity = [NSEntityDescription entityForName:@"Docset" inManagedObjectContext:ctx];
NSManagedObject *docset = [[IGKDocRecordManagedObject alloc] initWithEntity:docsetEntity insertIntoManagedObjectContext:ctx];
if (bundleIdentifier)
[docset setValue:bundleIdentifier forKey:@"bundleIdentifier"];
if (version)
[docset setValue:version forKey:@"version"];
if ([infoPlist objectForKey:@"DocSetDescription"])
[docset setValue:[infoPlist objectForKey:@"DocSetDescription"] forKey:@"docsetDescription"];
if ([infoPlist objectForKey:@"DocSetFeedName"])
[docset setValue:[infoPlist objectForKey:@"DocSetFeedName"] forKey:@"feedName"];
if ([infoPlist objectForKey:@"DocSetFeedURL"])
[docset setValue:[infoPlist objectForKey:@"DocSetFeedURL"] forKey:@"feedURL"];
if ([infoPlist objectForKey:@"DocSetPlatformFamily"])
[docset setValue:[infoPlist objectForKey:@"DocSetPlatformFamily"] forKey:@"platformFamily"];
else if ([infoPlist objectForKey:@"DocSetFeedName"])
[docset setValue:[infoPlist objectForKey:@"DocSetFeedName"] forKey:@"platformFamily"];
if ([infoPlist objectForKey:@"DocSetPlatformVersion"])
[docset setValue:[infoPlist objectForKey:@"DocSetPlatformVersion"] forKey:@"platformVersion"];
else if ([infoPlist objectForKey:@"CFBundleVersion"])
[docset setValue:[infoPlist objectForKey:@"CFBundleVersion"] forKey:@"platformVersion"];
if ([infoPlist objectForKey:@"DocSetFallbackURL"])
[docset setValue:[infoPlist objectForKey:@"DocSetFallbackURL"] forKey:@"fallbackURL"];
[docset setValue:[docsetURL absoluteString] forKey:@"url"];
[docset setValue:[docsetURL path] forKey:@"path"];
scraperDocset = docset;
paths = [[NSMutableArray alloc] init];
return YES;
}
- (void)findPathCount
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
pathsCount = [self backgroundSearch:scraperDocset];
dispatch_async(dispatch_get_main_queue(), ^{
[launchController reportPathCount:pathsCount];
});
});
}
- (NSUInteger)backgroundSearch:(NSManagedObject *)docset
{
NSFileManager *manager = [NSFileManager defaultManager];
NSString *urlpath = [url path];
NSError *error = nil;
NSArray *subpaths = [manager subpathsOfDirectoryAtPath:[url path] error:&error];
if (error)
return 0;
unsigned count = 0;
NSLog(@"subpaths = %d for %@", [subpaths count], docsetURL);
for (NSString *subpath in subpaths)
{
//Ignore non-html files
if (![[subpath pathExtension] isEqual:@"html"])
continue;
//Paths to exclude are added in order from most common to least common
NSString *lastPathComponent = [subpath lastPathComponent];
if ([lastPathComponent isEqual:@"toc.html"] ||
[lastPathComponent isEqual:@"History.html"] ||
[lastPathComponent isEqual:@"index_of_book.html"] ||
[lastPathComponent isEqual:@"RevisionHistory.html"] ||
[lastPathComponent isEqual:@"revision_history.html"] ||
[subpath containsString:@"RefUpdate/"])
{
continue;
}
NSArray *pathcomps = [subpath pathComponents];
NSSet *pathset = [NSSet setWithArray:pathcomps];
if ([pathset member:@"Conceptual"] ||
[pathset member:@"History"] ||
[pathset member:@"DeveloperTools"] ||
[pathset member:@"gcc"] ||
[pathset member:@"qa"] ||
[pathset member:@"samplecode"] ||
[pathset member:@"gdb"] ||
[pathset member:@"SafariWebContent"] ||
[pathset member:@"FoundationRefUpdate"])
{
continue;
}
//If the path ends with index.html and Reference/Reference.html already exists, ignore
//This is because some index.html files _should_ be parsed, but if a Reference/Reference.html exists, then it should not
if ([lastPathComponent isEqual:@"index.html"])
{
NSString *dir = [urlpath stringByAppendingPathComponent:[subpath stringByDeletingLastPathComponent]];
if ([manager fileExistsAtPath:[dir stringByAppendingPathComponent:@"Reference/Reference.html"]])
continue;
if ([manager fileExistsAtPath:[dir stringByAppendingPathComponent:@"CompositePage.html"]])
continue;
}
count++;
[paths addObject:subpath];
}
NSLog(@"\t Found paths = %d", [paths count]);
return [paths count];
}
- (void)index
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSString *docsetPathWithPrefix = [docsetpath stringByAppendingPathComponent:kIGKDocsetPrefixPath];
for (NSString *relativeExtractPath in paths)
{
NSString *indexPath = [docsetPathWithPrefix stringByAppendingPathComponent:relativeExtractPath];
NSManagedObject *mainObject = [self extractPath:indexPath relativeExtractPath:relativeExtractPath docset:scraperDocset isDeprecationAppendix:NO mainObjectIn:nil];
//Try to find matching deprecated appendicies
if (mainObject)
{
NSArray *deprecationAppendicies = [[self class] pathOfDeprecationAppendiciesForPath:indexPath];
for (NSString *deprecationAppendixPath in deprecationAppendicies)
{
[self extractPath:[[[indexPath stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByAppendingPathComponent:deprecationAppendixPath]
relativeExtractPath:[[[relativeExtractPath stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByAppendingPathComponent:deprecationAppendixPath]
docset:scraperDocset
isDeprecationAppendix:YES
mainObjectIn:mainObject];
}
}
pathsCounter += 1;
dispatch_async(dispatch_get_main_queue(), ^{
[launchController reportPath];
});
}
});
}
+ (NSArray *)pathOfDeprecationAppendiciesForPath:(NSString *)indexPath
{
if (![[indexPath pathComponents] containsObject:@"Reference"])
return nil;
NSString *deprecationAppendiciesFolder = [[[indexPath stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"DeprecationAppendix"];
NSError *err = nil;
NSArray *appendixPaths = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:deprecationAppendiciesFolder error:&err];
if (![appendixPaths count])
return nil;
NSMutableArray *deprecationAppendicies = [[NSMutableArray alloc] initWithCapacity:[appendixPaths count]];
for (NSString *deprecationAppendixPath in appendixPaths)
{
[deprecationAppendicies addObject:[@"DeprecationAppendix" stringByAppendingPathComponent:deprecationAppendixPath]];
}
return deprecationAppendicies;
}
- (NSManagedObject *)extractPath:(NSString *)extractPath relativeExtractPath:(NSString *)relativeExtractPath docset:(NSManagedObject *)docset isDeprecationAppendix:(BOOL)isDeprecationAppendix mainObjectIn:(NSManagedObject *)mainObjectIn
{
//Let's try to extract the class's name (assuming it is a class of course)
NSError *error = nil;
NSString *contents = [NSString stringWithContentsOfFile:extractPath encoding:NSUTF8StringEncoding error:&error];
NSUInteger contentsLength = [contents length];
if (error || !contents)
{
return nil;
}
//Parse the item's name and kind
NSString *regex_className = @"<a name=\"//apple_ref/(occ/([a-z_]+)/([a-zA-Z_][a-zA-Z0-9_\\(\\)]*)|c/([a-zA-Z_][a-zA-Z0-9_]*))";
NSArray *className_captures = [contents captureComponentsMatchedByRegex:regex_className];
if ([className_captures count] < 3)
{
return nil;
}
NSString *type = [className_captures objectAtIndex:2];
NSString *name = [className_captures objectAtIndex:3];
NSString *ctype = [className_captures objectAtIndex:4];
/* Common types
cl - class
intf - protocol
instm -
intfm -
cat - category
binding - bindings listing
*/
enum {
ParentItemType_ObjCClass,
ParentItemType_ObjCCategory,
ParentItemType_ObjCProtocol,
ParentItemType_ObjCBindingsListing,
ParentItemType_GenericCListing,
} parentItemType;
NSString *entityName = nil;
if ([type isEqual:@"cl"])
{
entityName = @"ObjCClass";
parentItemType = ParentItemType_ObjCClass;
}
else if ([type isEqual:@"cat"])
{
entityName = @"ObjCCategory";
parentItemType = ParentItemType_ObjCCategory;
}
else if ([type isEqual:@"intf"])
{
entityName = @"ObjCProtocol";
parentItemType = ParentItemType_ObjCCategory;
}
else if ([type isEqual:@"binding"])
{
entityName = @"ObjCBindingsListing";
parentItemType = ParentItemType_ObjCBindingsListing;
}
//Otherwise we may have a listing of C functions, structs, typedefs, etc
else if ([ctype length])
{
entityName = nil;
parentItemType = ParentItemType_GenericCListing;
}
//Nothing of note matched
else if (!isDeprecationAppendix)
{
// bail
return nil;
}
//Superclass
NSString *superclass = nil;
if (parentItemType == ParentItemType_ObjCClass)
{
//Find the superclass
NSString *superclassRegex = @"Inherits from.+?>([^<]+)<";
NSArray *superclassCaptureSet = [contents captureComponentsMatchedByRegex:superclassRegex];
if ([superclassCaptureSet count] >= 2)
{
superclass = [superclassCaptureSet objectAtIndex:1];
}
}
//Conforms to
NSMutableSet *conformsTo = nil;
if (parentItemType == ParentItemType_ObjCClass || parentItemType == ParentItemType_ObjCProtocol)
{
NSString *conformsToRegex = @"Conforms to.+?</td>(.+?)</td>";
NSArray *conformsToCaptureSet = [contents captureComponentsMatchedByRegex:conformsToRegex];
if ([conformsToCaptureSet count] >= 2)
{
NSString *conformsToSubstring = [conformsToCaptureSet objectAtIndex:1];
NSString *conformsToSubregex = @">([A-Za-z0-9_$]+)<";
NSArray *arrayOfMatchesCaptures = [conformsToSubstring arrayOfCaptureComponentsMatchedByRegex:conformsToSubregex];
if ([arrayOfMatchesCaptures count])
{
conformsTo = [[NSMutableSet alloc] initWithCapacity:[arrayOfMatchesCaptures count]];
for (NSArray *conformsToCaptures in arrayOfMatchesCaptures)
{
if ([conformsToCaptures count] < 2)
continue;
NSString *n = [conformsToCaptures objectAtIndex:1];
[conformsTo addObject:n];
}
}
if ([conformsTo count] == 0)
conformsTo = nil;
}
}
//Availability to
NSString *availability = nil;
if (parentItemType == ParentItemType_ObjCClass || parentItemType == ParentItemType_ObjCProtocol)
{
NSString *availabilityRegex = @"<strong>Availability</strong>.+?<div>(.+?)</div>";
NSArray *availabilityCaptureSet = [contents captureComponentsMatchedByRegex:availabilityRegex];
if ([availabilityCaptureSet count] >= 2)
{
availability = [availabilityCaptureSet objectAtIndex:1];
}
}
//Declared in
NSString *declaredIn = nil;
NSString *declaredInRegex = @"Declared in.+?<span class=\"content_text\">([^<]+)<";
NSArray *declaredInCaptureSet = [contents captureComponentsMatchedByRegex:declaredInRegex];
if ([declaredInCaptureSet count] >= 2)
{
declaredIn = [declaredInCaptureSet objectAtIndex:1];
}
NSString *linkRegex = @"name=\"//apple_ref/((occ/(instm|clm|intfm|intfcm|intfp|instp)/[a-zA-Z_:][a-zA-Z0-9:_]*/([a-zA-Z:_][a-zA-Z0-9:_]*))|(c/([a-zA-Z0-9_]+)/([a-zA-Z:_][a-zA-Z0-9:_]*)))\"([^<>]+role=\"([a-zA-Z0-9_]+)\")?";
/* The interesting captures are 3 & 4, and 5 & 6 */
NSArray *items = [contents arrayOfCaptureComponentsMatchedByRegex:linkRegex];
__block NSManagedObject *obj = mainObjectIn;
dispatch_sync(dbQueue, ^{
NSEntityDescription *propertyEntity = [NSEntityDescription entityForName:@"ObjCProperty" inManagedObjectContext:ctx];
NSEntityDescription *methodEntity = [NSEntityDescription entityForName:@"ObjCMethod" inManagedObjectContext:ctx];
NSEntityDescription *notificationEntity = nil;
NSEntityDescription *globalVariableEntity = nil;
NSEntityDescription *constantEntity = nil;
NSEntityDescription *functionEntity = nil;
NSEntityDescription *macroEntity = nil;
NSEntityDescription *typedefEntity = nil;
NSEntityDescription *enumEntity = nil;
NSEntityDescription *structEntity = nil;
NSEntityDescription *unionEntity = nil;
//If this isn't a deprecation appendix, create a parent object
if (entityName && isDeprecationAppendix == NO)
{
obj = [self addRecordNamed:name entityName:entityName desc:@"" sourcePath:relativeExtractPath];
[obj setValue:docset forKey:@"docset"];
[obj setValue:[NSNumber numberWithUnsignedInteger:contentsLength] forKey:@"contentsLength"];
if ([superclass length])
{
[obj setValue:superclass forKey:@"superclassName"];
}
if ([availability length])
[obj setValue:availability forKey:@"availability"];
if ([declaredIn length])
[obj setValue:declaredIn forKey:@"declared_in_header"];
if ([conformsTo count])
{
NSString *conformsToString = [NSString stringWithFormat:@"=%@=", [[conformsTo allObjects] componentsJoinedByString:@"="]];
[obj setValue:conformsToString forKey:@"conformsto"];
}
}
int lastWasProperty = 0;
for (NSArray *captures in items)
{
if ([captures count] > 4)
{
NSString *itemType = [captures objectAtIndex:3];
NSString *itemName = [captures objectAtIndex:4];
if ([itemType length] && [itemName length])
{
//Method
BOOL isProperty = [itemType isEqual:@"intfp"] || [itemType isEqual:@"instp"];
BOOL isInstanceMethod = isProperty || [itemType isEqual:@"instm"] || [itemType isEqual:@"intfm"];
if (isProperty)
{
lastWasProperty = 1;
}
else if (lastWasProperty == 1)
{
lastWasProperty = 2;
continue;
}
else if (lastWasProperty == 2)
{
lastWasProperty = 0;
continue;
}
IGKDocRecordManagedObject *newMethod = [[IGKDocRecordManagedObject alloc] initWithEntity:isProperty ? propertyEntity : methodEntity insertIntoManagedObjectContext:ctx];
[newMethod setValue:[itemName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"name"];
[newMethod setValue:obj forKey:@"container"];
[newMethod setValue:obj forKey:@"globalContainer"];
[newMethod setValue:docset forKey:@"docset"];
[newMethod setValue:relativeExtractPath forKey:@"documentPath"];
if (isDeprecationAppendix)
[newMethod setValue:[NSNumber numberWithBool:YES] forKey:@"isDeprecated"];
if (!isProperty)
[newMethod setValue:[NSNumber numberWithBool:isInstanceMethod] forKey:@"isInstanceMethod"];
continue;
}
}
if ([captures count] > 6)
{
NSString *itemType = [captures objectAtIndex:6];
NSString *itemName = [captures objectAtIndex:7];
NSString *itemRole = nil;
if ([captures count] > 9)
itemRole = [captures objectAtIndex:9];
if ([itemType length] && [itemName length])
{
IGKDocRecordManagedObject *newSubobject = nil;
/* Item types and examples:
tdef: vDSP_Length
cl: IOFireWireAVCLibConsumerInterface
econst: kFFTDirection_Forward
macro: vDSP_Version0
tag: kAXErrorSuccess
func: AXNotificationHIObjectNotify
instm: devicePairingConnecting:
data: kAXAttachmentTextAttribute
*/
if ([itemType isEqual:@"tdef"])
{
NSEntityDescription *entity = nil;
if ([itemRole isEqual:@"Enum"])
{
if (!enumEntity)
enumEntity = [NSEntityDescription entityForName:@"CEnum" inManagedObjectContext:ctx];
entity = enumEntity;
}
//These two don't actually exists... yet. The only role= attribute used is "Enum" (and "Macro", but that's kind of redundant but that's kind of redundant)
else if ([itemRole isEqual:@"Struct"])
{
if (!structEntity)
structEntity = [NSEntityDescription entityForName:@"CStruct" inManagedObjectContext:ctx];
entity = structEntity;
}
else if ([itemRole isEqual:@"Union"])
{
if (!unionEntity)
unionEntity = [NSEntityDescription entityForName:@"CUnion" inManagedObjectContext:ctx];
entity = unionEntity;
}
else
{
if (!typedefEntity)
typedefEntity = [NSEntityDescription entityForName:@"CTypedef" inManagedObjectContext:ctx];
entity = typedefEntity;
}
newSubobject = [[IGKDocRecordManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:ctx];
}
else if ([itemType isEqual:@"func"])
{
if (!functionEntity)
functionEntity = [NSEntityDescription entityForName:@"CFunction" inManagedObjectContext:ctx];
newSubobject = [[IGKDocRecordManagedObject alloc] initWithEntity:functionEntity insertIntoManagedObjectContext:ctx];
}
else if ([itemType isEqual:@"macro"])
{
if (!macroEntity)
macroEntity = [NSEntityDescription entityForName:@"CMacro" inManagedObjectContext:ctx];
newSubobject = [[IGKDocRecordManagedObject alloc] initWithEntity:macroEntity insertIntoManagedObjectContext:ctx];
}
//Weirdly, "constant_group" is Apple's code for a global and "data" is Apple's code for a constant *facepalm*
else if ([itemType isEqual:@"constant_group"])
{
if (!globalVariableEntity)
globalVariableEntity = [NSEntityDescription entityForName:@"CGlobal" inManagedObjectContext:ctx];
newSubobject = [[IGKDocRecordManagedObject alloc] initWithEntity:globalVariableEntity insertIntoManagedObjectContext:ctx];
}
else if ([itemType isEqual:@"econst"] || [itemType isEqual:@"data"] ||
[itemType isEqual:@"tag"]) //TODO: An item type of "tag" should really be a CEnumRecord entity
{
//This is such a hacky way to find out if an element is a notification, but it seems the most accurate way
BOOL isNotification = ([itemType isEqual:@"data"] && [itemName hasSuffix:@"Notification"]);
if (isNotification)
{
if (!notificationEntity)
notificationEntity = [NSEntityDescription entityForName:@"ObjCNotification" inManagedObjectContext:ctx];
newSubobject = [[IGKDocRecordManagedObject alloc] initWithEntity:notificationEntity insertIntoManagedObjectContext:ctx];
[newSubobject setValue:obj forKey:@"container"];
[newSubobject setValue:obj forKey:@"globalContainer"];
}
else
{
if (!constantEntity)
constantEntity = [NSEntityDescription entityForName:@"CConstant" inManagedObjectContext:ctx];
newSubobject = [[IGKDocRecordManagedObject alloc] initWithEntity:constantEntity insertIntoManagedObjectContext:ctx];
}
}
if (newSubobject)
{
[newSubobject setValue:[itemName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"name"];
[newSubobject setValue:docset forKey:@"docset"];
[newSubobject setValue:obj forKey:@"miscContainer"];
[newSubobject setValue:relativeExtractPath forKey:@"documentPath"];
if (isDeprecationAppendix)
[newSubobject setValue:[NSNumber numberWithBool:YES] forKey:@"isDeprecated"];
}
continue;
}
}
}
});
return obj;
}
- (NSManagedObject *)addRecordNamed:(NSString *)recordName entityName:(NSString *)entityName desc:(NSString *)recordDesc sourcePath:(NSString *)recordPath
{
NSEntityDescription *ed = [NSEntityDescription entityForName:entityName inManagedObjectContext:ctx];
NSManagedObject *newRecord = [[IGKDocRecordManagedObject alloc] initWithEntity:ed insertIntoManagedObjectContext:ctx];
[newRecord setValue:[recordName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"name"];
[newRecord setValue:recordDesc forKey:@"overview"];
[newRecord setValue:recordPath forKey:@"documentPath"];
return newRecord;
}
@end
@interface IGKFullScraper ()
+ (NSArray *)splitArray:(NSArray *)array byBlock:(NSString* (^)(id a))block;
+ (NSArray *)array:(NSArray *)array findObjectByBlock:(BOOL (^)(id a))block;
- (void)createMethodNamed:(NSString *)name description:(NSString *)description prototype:(NSString *)prototype
methodEntity:(NSEntityDescription *)methodEntity parent:(NSManagedObject*)parent docset:(NSManagedObject*)theDocset;
- (void)scrape;
- (void)scrapeTransientObject;
- (void)scrapeMethod;
- (void)scrapeAbstractMethodContainer;
- (void)scrapeMethodChildren:(NSArray *)children index:(NSUInteger)index managedObject:(NSManagedObject *)object;
- (void)scrapeBindings:(NSArray *)children index:(NSUInteger)index managedObject:(NSManagedObject *)object;
- (void)scrapeApplecode:(NSString *)applecode;
- (void)scrapeApplecodes:(NSArray *)applecodes;;
@end
@implementation IGKFullScraper
@synthesize transientObject;
@synthesize transientContext;
- (id)initWithManagedObject:(IGKDocRecordManagedObject *)persistentObject
{
if (self = [super init])
{
persistobj = persistentObject;
}
return self;
}
- (void)start
{
//Create a new managed object context to put the results of the full scrape into
//We don't want to actually -save: the results
transientContext = [[NSManagedObjectContext alloc] init];
[transientContext setPersistentStoreCoordinator:[[persistobj managedObjectContext] persistentStoreCoordinator]];
[transientContext setUndoManager:nil];
//Scrape
[self scrape];
}
- (void)cleanUp
{
//Reset the context
[transientContext rollback];
[transientContext reset];
}
- (void)scrape
{
NSManagedObjectContext *persistmoc = [persistobj managedObjectContext];
NSError *err = nil;
NSString *docsetPath = [[persistobj valueForKey:@"docset"] valueForKey:@"path"];
NSString *docsetPathWithPrefix = [docsetPath stringByAppendingPathComponent:kIGKDocsetPrefixPath];
//Fetch the deprecated methods
NSFetchRequest *deprecatedObjectsFetch = [[NSFetchRequest alloc] init];
[deprecatedObjectsFetch setEntity:[NSEntityDescription entityForName:@"DocRecord" inManagedObjectContext:persistmoc]];
[deprecatedObjectsFetch setPredicate:[NSPredicate predicateWithFormat:@"isDeprecated=TRUE && globalContainer=%@", persistobj]];
NSArray *deprecatedObjects = [persistmoc executeFetchRequest:deprecatedObjectsFetch error:&err];
NSMutableSet *deprecatedAppendices = [[NSMutableSet alloc] initWithCapacity:1];
for (NSManagedObject *deprecatedObject in deprecatedObjects)
{
NSString *deprecatedAppendixPath = [[deprecatedObject valueForKeyPath:@"heavyNonQueryables"] valueForKey:@"documentPath"];
if (deprecatedAppendixPath)
[deprecatedAppendices addObject:[docsetPathWithPrefix stringByAppendingPathComponent:deprecatedAppendixPath]];
}
//Get persistobj's equivalent in transientContext
transientObject = (IGKDocRecordManagedObject *)[transientContext objectWithID:[persistobj objectID]];
docset = [transientObject valueForKey:@"docset"];
[self scrapeInPath:[docsetPathWithPrefix stringByAppendingPathComponent:[persistobj valueForKey:@"documentPath"]]];
isParsingDeprecatedAppendix = YES;
for (NSString *deprecatedAppendix in deprecatedAppendices)
{
[self scrapeInPath:deprecatedAppendix];
}
isParsingDeprecatedAppendix = NO;
}
- (void)scrapeInPath:(NSString *)extractPath
{
//NSString *relativeExtractPath = [transientObject valueForKey:@"documentPath"];
//NSString *extractPath = [docsetPathWithPrefix stringByAppendingPathComponent:relativeExtractPath];
NSURL *fileurl = [NSURL fileURLWithPath:extractPath];
NSError *err = nil;
NSCache *xmlDocCache = [[[NSApp delegate] kitController] xmlDocumentCache];
doc = [xmlDocCache objectForKey:fileurl];
if (!doc)
{
doc = [[NSXMLDocument alloc] initWithContentsOfURL:fileurl options:NSXMLDocumentTidyHTML error:&err];
[xmlDocCache setObject:doc forKey:fileurl cost:0];
if (!doc)
return;
}
methodNodes = nil;
[self scrapeTransientObject];
}
- (NSArray *)methodNodes
{
if (methodNodes)
return methodNodes;
methodNodes = [[doc rootElement] nodesMatchingPredicate:^BOOL(NSXMLNode *node) {
return [[node name] isEqual:@"a"];
}];
return methodNodes;
}
- (void)scrapeTransientObject
{
//Depending on the type of obj, we will need to parse it differently
if ([transientObject isKindOfEntityNamed:@"ObjCAbstractMethodContainer"])
{
[self scrapeAbstractMethodContainer];
//Hacky way to also read new data for misc items
if (!isParsingDeprecatedAppendix)
{
id oldTransientObject = transientObject;
for (IGKDocRecordManagedObject *miscItem in [oldTransientObject valueForKey:@"miscitems"])
{
transientObject = miscItem;
[self scrapeTransientObject];
}
transientObject = oldTransientObject;
}
return;
}
if ([transientObject isKindOfEntityNamed:@"ObjCMethod"] || [transientObject isKindOfEntityNamed:@"ObjCProperty"])
{
[self scrapeMethod];
}
else if ([transientObject isKindOfEntityNamed:@"CFunction"])
{
[self scrapeApplecode:@"c/func"];
}
else if ([transientObject isKindOfEntityNamed:@"CTypedef"])
{
[self scrapeApplecode:@"c/tdef"];
}
else if ([transientObject isKindOfEntityNamed:@"CStruct"])
{
[self scrapeApplecode:@"c/tdef"];
}
else if ([transientObject isKindOfEntityNamed:@"CEnum"])
{
[self scrapeApplecode:@"c/tdef"];
}
else if ([transientObject isKindOfEntityNamed:@"CMacro"])
{
[self scrapeApplecode:@"c/macro"];
}
else if ([transientObject isKindOfEntityNamed:@"CConstant"])
{
[self scrapeApplecodes:[NSArray arrayWithObjects:@"c/econst", @"c/data", @"c/tag", nil]];
}
else if ([transientObject isKindOfEntityNamed:@"CGlobal"])
{
[self scrapeApplecode:@"c/constant_group"];
}
else if ([transientObject isKindOfEntityNamed:@"ObjCNotification"])
{
[self scrapeApplecode:@"c/data"];
}
else if ([transientObject isKindOfEntityNamed:@"ObjCBindingsListing"])
{
[self scrapeBindingsListing];
}
}
- (void)scrapeApplecode:(NSString *)applecode
{
[self scrapeApplecodes:[NSArray arrayWithObject:applecode]];
}
- (void)scrapeApplecodes:(NSArray *)applecodes
{
NSMutableArray *fullApplecodePatterns = [[NSMutableArray alloc] init];
for (NSString *applecode in applecodes)
{
[fullApplecodePatterns addObject:[NSString stringWithFormat:@"//apple_ref/%@", applecode]];
}
//Search through all anchors in the document, and record their parent elements
NSArray *mnodes = [self methodNodes];
//NSMutableSet *containersSet = [[NSMutableSet alloc] initWithCapacity:[mnodes count]];
NSHashTable *containersSet = [[NSHashTable alloc] initWithOptions:NSPointerFunctionsStrongMemory | NSPointerFunctionsOpaquePersonality capacity:[mnodes count]];
for (NSXMLElement *a in mnodes)
{
if ([containersSet containsObject:[a parent]])
continue;
if (![a isKindOfClass:[NSXMLElement class]])
continue;
NSXMLNode *el = [a attributeForLocalName:@"name"];
NSString *strval = [el commentlessStringValue];
//(instm|clm|intfm|intfcm|intfp|instp)
for (NSString *fullApplecodePattern in fullApplecodePatterns)
{
if ([strval hasPrefix:fullApplecodePattern])
{
NSString *methodName = [transientObject valueForKey:@"name"];
//This is a bit ropey
if ([strval hasSuffix:methodName])
{
[containersSet addObject:[a parent]];
NSArray *children = [[a parent] children];
NSInteger index = [children indexOfObject:a];
if (index != -1)
{
[self scrapeMethodChildren:children index:index managedObject:transientObject];
}
break;
}
}
}
}
}
- (void)scrapeMethod
{
NSError *err = nil;
//NSArray *methodNodes1 = [[doc rootElement] nodesForXPath:@"//a" error:&err];
//Search through all anchors in the document, and record their parent elements
NSArray *mnodes = [self methodNodes];
NSHashTable *containersSet = [[NSHashTable alloc] initWithOptions:NSPointerFunctionsStrongMemory | NSPointerFunctionsOpaquePersonality capacity:[mnodes count]];
for (NSXMLElement *a in mnodes)
{
if ([containersSet containsObject:[a parent]])
continue;
if (![a isKindOfClass:[NSXMLElement class]])
continue;
NSXMLNode *el = [a attributeForLocalName:@"name"];
NSString *strval = [el commentlessStringValue];
//(instm|clm|intfm|intfcm|intfp|instp)
if ([strval hasPrefix:@"//apple_ref/occ/instm"] || [strval hasPrefix:@"//apple_ref/occ/clm"] ||
[strval hasPrefix:@"//apple_ref/occ/intfm"] || [strval hasPrefix:@"//apple_ref/occ/intfcm"] ||
[strval hasPrefix:@"//apple_ref/occ/intfp"] || [strval hasPrefix:@"//apple_ref/occ/instp"])
{
NSString *methodName = [transientObject valueForKey:@"name"];
//This is a bit ropey
if ([strval length] >= [methodName length] && [[strval substringFromIndex:[strval length] - [methodName length]] isEqual:methodName])
{
[containersSet addObject:[a parent]];
NSArray *children = [[a parent] children];
NSInteger index = [children indexOfObject:a];
if (index != -1)
{
[self scrapeMethodChildren:children index:index managedObject:transientObject];
}
}
}
}
}
- (void)scrapeMethodChildren:(NSArray *)children index:(NSUInteger)index managedObject:(NSManagedObject *)object
{
/* Things we need to scrape
* name
* overview
* parameters
* returnType
* returnDescription
* availability
* seealsos
* samplecode
*/
BOOL hasRecordedMethod = NO;
NSUInteger i = 0;
NSUInteger count = [children count];
BOOL isOnlyAElements = YES;
if (count == 0)
isOnlyAElements = NO;
NSString *objlowername = [[object valueForKey:@"name"] lowercaseString];
for (i = index; i < count; i++)
{
NSXMLElement *n = [children objectAtIndex:i];
if (![n isKindOfClass:[NSXMLElement class]])
continue;
NSString *nName = [[n name] lowercaseString];
NSArray *nClass = [[[[n attributeForLocalName:@"class"] commentlessStringValue] lowercaseString] componentsSeparatedByString:@" "];
if (![nName isEqual:@"a"])
isOnlyAElements = NO;
//name
// <h3 class="*jump*"> ... </h3>
if ([nName isEqual:@"h3"] && [nClass containsObject:@"jump"])
{
//If we've already recorded a method, then we're done
if (hasRecordedMethod)
break;
hasRecordedMethod = YES;
[object setValue:[[n commentlessStringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"name"];
if (isParsingDeprecatedAppendix)
[object setValue:[NSNumber numberWithBool:YES] forKey:@"isDeprecated"];
continue;
}
//constants
//This is what it SHOULD look like
/* <a name="//apple_ref/c/econst/NSJapaneseEUCStringEncoding" title="NSJapaneseEUCStringEncoding"></a>
<a name="//apple_ref/doc/c_ref/NSJapaneseEUCStringEncoding" title="NSJapaneseEUCStringEncoding"></a>
<a name="//apple_ref/doc/uid/20000154-SW64" title="NSJapaneseEUCStringEncoding"></a>