forked from tomaz/appledoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXMLOutputGenerator.m
1475 lines (1331 loc) · 64.2 KB
/
XMLOutputGenerator.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
//
// XMLOutputGenerator.m
// appledoc
//
// Created by Tomaz Kragelj on 11.6.09.
// Copyright (C) 2009, Tomaz Kragelj. All rights reserved.
//
#import "XMLOutputGenerator.h"
#import "CommandLineParser.h"
#import "LoggingProvider.h"
#import "Systemator.h"
@implementation XMLOutputGenerator
//////////////////////////////////////////////////////////////////////////////////////////
#pragma mark OutputInfoProvider protocol implementation
//////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------
- (NSString*) outputFilesExtension
{
return @".xml";
}
//----------------------------------------------------------------------------------------
- (NSString*) outputBasePath
{
return [cmd.outputPath stringByAppendingPathComponent:@"cxml"];
}
//////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Specific output generation entry points
//////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------
- (void) generateSpecificOutput
{
if (!self.doxygenInfoProvider)
[Systemator throwExceptionWithName:kTKConverterException
withDescription:@"doxygenInfoProvider not set"];
[self createCleanObjectDocumentationMarkup];
[self mergeCleanCategoriesToKnownObjects];
[self updateCleanObjectsDatabase];
[self createCleanIndexDocumentationFile];
[self createCleanHierarchyDocumentationFile];
[self fixCleanObjectDocumentation];
[self saveCleanObjectDocumentationFiles];
}
//////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Clean XML handling
//////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------
- (void) createCleanObjectDocumentationMarkup
{
logNormal(@"Creating clean object XML files...");
NSAutoreleasePool* loopAutoreleasePool = nil;
NSError* error = nil;
// First get the list of all files (and directories) at the doxygen output path. Note
// that we only handle certain files, based on their names.
NSString* searchPath = [self.doxygenInfoProvider outputBasePath];
NSArray* files = [manager contentsOfDirectoryAtPath:searchPath error:&error];
if (!files)
{
logError(@"Failed enumerating files at '%@'!", searchPath);
[Systemator throwExceptionWithName:kTKConverterException basedOnError:error];
}
for (NSString* filename in files)
{
// Setup the autorelease pool for this iteration. Note that we are releasing the
// previous iteration pool here as well. This is because we use continue to
// skip certain iterations, so releasing at the end of the loop would not work...
// Also note that after the loop ends, we are releasing the last iteration loop.
[loopAutoreleasePool drain];
loopAutoreleasePool = [[NSAutoreleasePool alloc] init];
// (1) First check if the file is .xml and starts with correct name.
BOOL parse = [filename hasSuffix:@".xml"];
parse &= [filename hasPrefix:@"class_"] ||
[filename hasPrefix:@"interface_"] ||
[filename hasPrefix:@"protocol_"];
if (!parse)
{
logDebug(@"- Skipping '%@' because it doesn't describe known object.", filename);
continue;
}
// (2) Parse the XML and check if the file is documented or not. Basically
// we check if at least one brief or detailed description contains a
// para tag. If so, the document is considered documented... If parsing
// fails, log and skip the file.
NSString* inputFilename = [searchPath stringByAppendingPathComponent:filename];
NSURL* originalURL = [NSURL fileURLWithPath:inputFilename];
NSXMLDocument* originalDocument = [[[NSXMLDocument alloc] initWithContentsOfURL:originalURL
options:0
error:&error] autorelease];
if (!originalDocument)
{
logError(@"Skipping '%@' because parsing failed with error %@!",
filename,
[error localizedDescription]);
continue;
}
// (3) If at least one item is documented, run the document through the
// xslt converter to get clean XML. Then use the clean XML to get
// further object information and finally add the object to the data
// dictionary.
if ([[originalDocument nodesForXPath:@"//briefdescription/para" error:NULL] count] == 0 &&
[[originalDocument nodesForXPath:@"//detaileddescription/para" error:NULL] count] == 0)
{
logVerbose(@"- Skipping '%@' because it contains non-documented object...", filename);
continue;
}
// (4) Prepare file names and run the xslt converter. Catch any exception
// and log it, then continue with the next file.
@try
{
// (A) Run the xslt converter.
NSString* stylesheetFile = [cmd.templatesPath stringByAppendingPathComponent:@"object.xslt"];
NSXMLDocument* cleanDocument = [Systemator applyXSLTFromFile:stylesheetFile
toDocument:originalDocument
error:&error];
if (!cleanDocument)
{
logError(@"Skipping '%@' because creating clean XML failed with error %@!",
filename,
[error localizedDescription]);
continue;
}
// (B) If object node is not present, exit. This means the convertion failed...
NSArray* objectNodes = [cleanDocument nodesForXPath:@"/object" error:NULL];
if ([objectNodes count] == 0)
{
logError(@"Skipping '%@' because object node not found!", filename);
continue;
}
// (C) Get object name node and append utility version to xml. If not found, exit.
NSXMLElement* objectNode = [objectNodes objectAtIndex:0];
NSArray* objectNameNodes = [objectNode nodesForXPath:@"name" error:NULL];
if ([objectNameNodes count] == 0)
{
logError(@"Skipping '%@' because object name node not found!", filename);
continue;
}
[objectNode addAttribute:[NSXMLNode attributeWithName:@"generator" stringValue:cmd.generator]];
// (D) Now we have all information, get the data and add the object to the list.
NSXMLElement* objectNameNode = [objectNameNodes objectAtIndex:0];
NSString* objectName = [objectNameNode stringValue];
NSString* objectKind = [[objectNode attributeForName:@"kind"] stringValue];
if ([objectName length] == 0 || [objectKind length] == 0)
{
logError(@"Skipping '%@' because data cannot be collected (name %@, kind %@)!",
filename,
objectName,
objectKind);
continue;
}
// (D.1) Prepare the object's parent. If the object doesn't have parent,
// just assume it's derived from NSObject, as long it's not NSObject itself.
// There's a bug in doxygen implementation which doesn't list some super
// classes - NSManagedObject for example...
// Although this doesn't properly work, at least the objects appear on the
// hierarchy. Note that we only do this for classes!
NSString* objectParent = nil;
NSArray* baseNodes = [objectNode nodesForXPath:@"base" error:nil];
if ([baseNodes count] == 0 && [objectKind isEqualToString:@"class"])
{
if (![objectName isEqualToString:@"NSObject"]) {
logInfo(@"- %@ class marked with no base, assuming NSObject!", objectName);
NSXMLElement* baseNode = [NSXMLElement elementWithName:@"base" stringValue:@"NSObject"];
[objectNode addChild:baseNode];
baseNodes = [objectNode nodesForXPath:@"base" error:nil];
}
}
if ([baseNodes count] > 0) objectParent = [[baseNodes objectAtIndex:0] stringValue];
// (E) Prepare the object relative directory and relative path to the index.
// Also set the class "link" for categories.
NSString* objectClass = nil;
NSString* objectRelativeDirectory = nil;
if ([objectKind isEqualToString:@"category"])
{
objectRelativeDirectory = kTKDirCategories;
NSRange categoryNameRange = [objectName rangeOfString:@"("];
if (categoryNameRange.location != NSNotFound)
{
objectClass = [objectName substringToIndex:categoryNameRange.location];
}
}
else if ([objectKind isEqualToString:@"protocol"])
{
objectRelativeDirectory = kTKDirProtocols;
}
else
{
objectRelativeDirectory = kTKDirClasses;
}
NSString* objectRelativePath = [objectRelativeDirectory stringByAppendingPathComponent:objectName];
objectRelativePath = [objectRelativePath stringByAppendingString:kTKPlaceholderExtension];
// (F) OK, now really add the node to the database... ;) First create the
// object's description dictionary. Then add the object to the Objects
// dictionary. Then check if the object's relative directory key already
// exists in the directories dictionary. If not, create it, then add the
// object to the end of the list.
NSMutableDictionary* objectData = [[NSMutableDictionary alloc] init];
[objectData setObject:objectName forKey:kTKDataObjectNameKey];
[objectData setObject:objectKind forKey:kTKDataObjectKindKey];
[objectData setObject:cleanDocument forKey:kTKDataObjectMarkupKey];
[objectData setObject:objectRelativeDirectory forKey:kTKDataObjectRelDirectoryKey];
[objectData setObject:objectRelativePath forKey:kTKDataObjectRelPathKey];
[objectData setObject:inputFilename forKey:kTKDataObjectDoxygenFilenameKey];
if (objectParent) [objectData setObject:objectParent forKey:kTKDataObjectParentKey];
if (objectClass) [objectData setObject:objectClass forKey:kTKDataObjectClassKey];
// Add the object to the object's dictionary.
NSMutableDictionary* objectsDict = [database objectForKey:kTKDataMainObjectsKey];
[objectsDict setObject:objectData forKey:objectName];
// Add the object to the directories list.
NSMutableDictionary* directoriesDict = [database objectForKey:kTKDataMainDirectoriesKey];
NSMutableArray* directoryArray = [directoriesDict objectForKey:objectRelativeDirectory];
if (directoryArray == nil)
{
directoryArray = [NSMutableArray array];
[directoriesDict setObject:directoryArray forKey:objectRelativeDirectory];
}
[directoryArray addObject:objectData];
// Log the object.
logVerbose(@"- Found '%@' of type '%@' in file '%@'...",
objectName,
objectKind,
filename);
}
@catch (NSException* e)
{
logError(@"Skipping '%@' because converting to clean documentation failed with error %@!",
filename,
[e reason]);
continue;
}
}
// Release the last iteration pool.
[loopAutoreleasePool drain];
logInfo(@"Finished creating clean object documentation files.");
}
//----------------------------------------------------------------------------------------
- (void) mergeCleanCategoriesToKnownObjects
{
if (cmd.mergeKnownCategoriesToClasses)
{
logNormal(@"Merging categories documentation to known classes...");
// Go through all categories and check if they belong to a known class. If so
// merge the documentation as a new section at the end of the class documentation.
// Then remember the category name so we can later remove it from the database.
NSMutableArray* removedCategories = [NSMutableArray array];
NSMutableDictionary* objects = [database objectForKey:kTKDataMainObjectsKey];
NSDictionary* directoriesDict = [database objectForKey:kTKDataMainDirectoriesKey];
NSMutableArray* categoriesArray = [directoriesDict objectForKey:kTKDirCategories];
for (NSDictionary* categoryData in categoriesArray)
{
NSString* categoryName = [categoryData objectForKey:kTKDataObjectNameKey];
NSString* className = [categoryData objectForKey:kTKDataObjectClassKey];
if (!className)
{
logVerbose(@"- Skipping '%@' because it belongs to unknown class.", categoryName);
continue;
}
logVerbose(@"- Merging category '%@' documentation to class '%@'...",
categoryName,
className);
// Get the main class XML.
NSDictionary* classData = [objects objectForKey:className];
NSXMLDocument* classDocument = [classData objectForKey:kTKDataObjectMarkupKey];
// Get the main class <sections> container element. If not found, exit.
// (this should not really happen, since the xslt adds "Others" node by
// default, but let's keep it safe). If there's more than one sections node,
// use the first one (also should not happen).
NSXMLElement* classSectionsNode = nil;
NSArray* classSectionsNodes = [classDocument nodesForXPath:@"/object/sections" error:nil];
if ([classSectionsNodes count] == 0)
{
logInfo(@"Skipping '%@' because class doesn't contain sections node!", categoryName);
continue;
}
classSectionsNode = (NSXMLElement*)[classSectionsNodes objectAtIndex:0];
// Get the category clean document markup. Next step depends on the category
// merging optios. If sections need to be preserved, we should copy all
// sections. Otherwise we should create one section for each category which
// includes members from all sections.
NSXMLDocument* categoryDocument = [categoryData objectForKey:kTKDataObjectMarkupKey];
if (cmd.keepMergedCategorySections)
{
// Get the array of all category sections and append them in the same
// order to the main class. The new section name should have the category
// name prepended.
NSArray* categorySectionNodes = [categoryDocument nodesForXPath:@"/object/sections/section" error:nil];
for (NSXMLElement* categorySectionNode in categorySectionNodes)
{
// Get category section name. Use empty string by default just in case...
NSString* categorySectionName = @"";
NSArray* categorySectionNameNodes = [categorySectionNode nodesForXPath:@"name" error:nil];
if ([categorySectionNameNodes count] > 0)
{
NSXMLNode* nameNode = [categorySectionNameNodes objectAtIndex:0];
categorySectionName = [nameNode stringValue];
}
// Merge the section data to the main class document. We need to prepend
// the category name before the section description before... Note that
// we handle the cases where no category name is defined by simply using
// the category section name.
logDebug(@" - Merging documentation for section '%@'...");
NSXMLElement* classSectionNode = [categorySectionNode copy];
NSArray* classSectionNameNodes = [classSectionNode nodesForXPath:@"name" error:nil];
if ([classSectionNameNodes count] > 0)
{
NSString* extensionName = [categoryName substringFromIndex:[className length]];
extensionName = [extensionName substringWithRange:NSMakeRange(1, [extensionName length]-2)];
NSString* classSectionName = categorySectionName;
if ([extensionName length] > 0)
classSectionName = [NSString stringWithFormat:@"%@ / %@",
extensionName,
categorySectionName];
NSXMLNode* nameNode = [classSectionNameNodes objectAtIndex:0];
[nameNode setStringValue:classSectionName];
}
[classSectionsNode addChild:classSectionNode];
[classSectionNode release];
}
}
else
{
logDebug(@" - Merging all sections to '%@'...", categoryName);
// Create the class section element.
NSXMLElement* sectionNode = [NSXMLNode elementWithName:@"section"];
NSXMLElement* sectionNameNode = [NSXMLNode elementWithName:@"name" stringValue:categoryName];
[sectionNode addChild:sectionNameNode];
// Get all member documentation for all sections and add each one to the
// class section element.
NSArray* memberNodes = [categoryDocument nodesForXPath:@"/object/sections/section/member" error:nil];
for (NSXMLElement* memberNode in memberNodes)
{
NSXMLElement* classMemberNode = [memberNode copy];
[sectionNode addChild:classMemberNode];
[classMemberNode release];
}
// Append the section data to the main class document.
[classSectionsNode addChild:sectionNode];
}
// After the category was added, add it's <file> tag to the end of the
// last one. This will be used in actual output generation to show all
// source files from which documentation was extracted. Note that we skip
// all files which were already added.
NSArray* categoryFileNodes = [categoryDocument nodesForXPath:@"object/file" error:nil];
if ([categoryFileNodes count] > 0)
{
NSArray* classFileNodes = [classDocument nodesForXPath:@"object/file" error:nil];
if ([classFileNodes count] > 0)
{
NSXMLElement* lastClassFileNode = [classFileNodes lastObject];
NSXMLElement* parentNode = (NSXMLElement*)[lastClassFileNode parent];
NSUInteger index = [lastClassFileNode index];
for (NSXMLElement* categoryFileNode in categoryFileNodes)
{
NSString* testQuery = [NSString stringWithFormat:@"object/file[%@]",
[categoryFileNode stringValue]];
if ([[classDocument nodesForXPath:testQuery error:nil] count] == 0)
{
logDebug(@" - Inserting file '%@' from category to index %d...",
[categoryFileNode stringValue],
index);
NSXMLElement* insertedNode = [categoryFileNode copy];
[parentNode insertChild:insertedNode atIndex:index + 1];
[insertedNode release];
index++;
}
}
}
}
// Remember the category name which was removed. Note that we use category
// data because we can get all information from there and we need the
// instance to properly remove from the directories array.
[removedCategories addObject:categoryData];
}
// Remove all category "stand alone" documentation from the database. We'll
// lose the category description this way, but this usually doesn't provide
// much information (at least not in my documentation... ;-)).
for (NSDictionary* categoryData in removedCategories)
{
NSString* categoryName = [categoryData objectForKey:kTKDataObjectNameKey];
logDebug(@" - Removing category '%@' documentation...", categoryName);
[categoriesArray removeObject:categoryData];
[objects removeObjectForKey:categoryName];
}
logInfo(@"Finished merging categories documentation to known classes...");
}
}
//----------------------------------------------------------------------------------------
- (void) updateCleanObjectsDatabase
{
logNormal(@"Updating clean objects database...");
// Prepare common variables to optimize loop a bit.
NSAutoreleasePool* loopAutoreleasePool = nil;
// Handle all files in the database.
NSDictionary* objects = [database objectForKey:kTKDataMainObjectsKey];
for (NSString* objectName in objects)
{
// Setup the autorelease pool for this iteration. Note that we are releasing the
// previous iteration pool here as well. This is because we use continue to
// skip certain iterations, so releasing at the end of the loop would not work...
// Also note that after the loop ends, we are releasing the last iteration loop.
[loopAutoreleasePool drain];
loopAutoreleasePool = [[NSAutoreleasePool alloc] init];
// Get the required object data.
NSMutableDictionary* objectData = [objects objectForKey:objectName];
logVerbose(@"- Handling '%@'...", objectName);
[self createMembersDataForObject:objectName objectData:objectData];
}
// Release last iteration pool.
[loopAutoreleasePool drain];
logInfo(@"Finished updating clean objects database.");
}
//----------------------------------------------------------------------------------------
- (void) createCleanIndexDocumentationFile
{
logNormal(@"Creating clean index documentation file...");
NSAutoreleasePool* loopAutoreleasePool = [[NSAutoreleasePool alloc] init];
// Create the default markup.
NSXMLDocument* document = [[NSXMLDocument alloc] init];
NSXMLElement* projectElement = [NSXMLElement elementWithName:@"project"];
[projectElement addAttribute:[NSXMLNode attributeWithName:@"generator" stringValue:cmd.generator]];
[document setVersion:@"1.0"];
[document addChild:projectElement];
// Enumerate through all the enumerated objects and create the markup. Note that
// we use directory structure so that we get proper enumeration.
NSDictionary* objects = [database objectForKey:kTKDataMainObjectsKey];
NSArray* sortedObjectNames = [[objects allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSString* objectName in sortedObjectNames)
{
logVerbose(@"- Handling '%@'...", objectName);
NSDictionary* objectData = [objects valueForKey:objectName];
NSString* objectKind = [objectData valueForKey:kTKDataObjectKindKey];
NSString* objectRef = [objectData valueForKey:kTKDataObjectRelPathKey];
// Create the object element and the kind and id attributes.
NSXMLElement* objectElement = [NSXMLElement elementWithName:@"object"];
NSXMLNode* kindAttribute = [NSXMLNode attributeWithName:@"kind" stringValue:objectKind];
NSXMLNode* idAttribute = [NSXMLNode attributeWithName:@"id" stringValue:objectRef];
[objectElement addAttribute:kindAttribute];
[objectElement addAttribute:idAttribute];
[projectElement addChild:objectElement];
// Create the name element.
NSXMLElement* nameElement = [NSXMLElement elementWithName:@"name"];
[nameElement setStringValue:objectName];
[objectElement addChild:nameElement];
}
// Store the cleaned markup to the application data.
[database setObject:document forKey:kTKDataMainIndexKey];
// Save the markup.
NSError* error = nil;
NSData* markupData = [document XMLDataWithOptions:NSXMLNodePrettyPrint];
[document release];
NSString* filename = [self outputBasePath];
filename = [filename stringByAppendingPathComponent:[self outputIndexFilename]];
if (![markupData writeToFile:filename options:0 error:&error])
{
logError(@"Failed writting clean Index.xml to '%@'!", filename);
[Systemator throwExceptionWithName:kTKConverterException basedOnError:error];
}
[loopAutoreleasePool drain];
logInfo(@"Finished creating clean index documentation file.");
}
//----------------------------------------------------------------------------------------
- (void) createCleanHierarchyDocumentationFile
{
logNormal(@"Creating clean hierarchy documentation file...");
// Prepare common variables.
NSAutoreleasePool* loopAutoreleasePool = nil;
// Go through all the objects in the database and prepare the hierarchy. Note that
// this is done in two steps. In the first step the objects are stored in the
// hierarchy in proper structure, except that the root level contains ALL of the
// objects. However all objects which place is not in the root will have their
// temporary flag set. These will be removed in the second pass. This way allows
// us to simplify hieararchy generation - when adding a new object, get it's parent
// and check if the parent already exists in the root. If not, add the parent, add
// the object to it's children and then also add the object to the root but marked
// with temporary...
NSMutableDictionary* hierarchies = [database objectForKey:kTKDataMainHierarchiesKey];
NSDictionary* objects = [database objectForKey:kTKDataMainObjectsKey];
for (NSString* objectName in objects)
{
// Release all autoreleased objects from the previous iteration.
[loopAutoreleasePool drain];
loopAutoreleasePool = [[NSAutoreleasePool alloc] init];
// Get the object data from the objects database. If parent data exists, add the
// object to the hierarchy. Note that this adds both, the parent and the object
// to the root.
NSMutableDictionary* objectData = [objects objectForKey:objectName];
NSString* parentName = [objectData objectForKey:kTKDataObjectParentKey];
if (parentName)
{
logDebug(@" - Handling '%@' as child of '%@'...", objectName, parentName);
// Check the hierarchy database to see if object has already been added - this
// can happen in the code below if the object is found as a parent of another
// object. In such case we need to add object's data to the existing entry,
// otherwise we need to create the data.
NSMutableDictionary* objectHierarchyData = [hierarchies objectForKey:objectName];
if (!objectHierarchyData)
{
objectHierarchyData = [NSMutableDictionary dictionary];
[objectHierarchyData setObject:objectName forKey:kTKDataHierarchyObjectNameKey];
[objectHierarchyData setObject:[NSMutableDictionary dictionary] forKey:kTKDataHierarchyChildrenKey];
[hierarchies setObject:objectHierarchyData forKey:objectName];
}
// Add the pointer to the object's data dictionary and set it's temporary
// key so that it will be removed later on - this object has a parent, so
// it's place is not in the root.
[objectHierarchyData setObject:objectData forKey:kTKDataHierarchyObjectDataKey];
[objectHierarchyData setObject:[NSNumber numberWithBool:YES] forKey:kTKDataHierarchyTempKey];
// Check the hierarchy database to see if parent was already handled - if
// we find it in the root, add the object to it's children. Otherwise create
// the data for it now (note that at this point we don't prepare full data,
// this will be handled in above code when (if) parent object is found in
// documented data).
NSMutableDictionary* parentHierarchyData = [hierarchies objectForKey:parentName];
if (!parentHierarchyData)
{
parentHierarchyData = [NSMutableDictionary dictionary];
[parentHierarchyData setObject:parentName forKey:kTKDataHierarchyObjectNameKey];
[parentHierarchyData setObject:[NSMutableDictionary dictionary] forKey:kTKDataHierarchyChildrenKey];
[hierarchies setObject:parentHierarchyData forKey:parentName];
}
// Add the object to it's parent children. Note that we don't set parent's
// temporary key - if the parent is still unknown, it may be the root object,
// however if we find it as a child of another object later on, we'll set it's
// temporary key at that point (see above).
NSMutableDictionary* parentChildren = [parentHierarchyData objectForKey:kTKDataHierarchyChildrenKey];
[parentChildren setObject:objectHierarchyData forKey:objectName];
}
}
// Create the default markup. Then handle all root level objects. This in turn will
// handle their children and these their and so on in the recursive method. Note that
// all root level nodes with temporary flag set, should not be handled. These will
// eventually be removed from the database root level, at the end of the clean XML
// generation. However for the moment they are left here, so that code generation
// is simpler - to find an object and it's hierarchy, simply search for it in the
// root...
NSXMLDocument* document = [[NSXMLDocument alloc] init];
NSXMLElement* projectElement = [NSXMLElement elementWithName:@"project"];
[projectElement addAttribute:[NSXMLNode attributeWithName:@"generator" stringValue:cmd.generator]];
[document setVersion:@"1.0"];
[document addChild:projectElement];
NSArray* sortedObjects = [[hierarchies allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSString* objectName in sortedObjects)
{
NSDictionary* objectData = [hierarchies objectForKey:objectName];
NSNumber* temporaryFlag = [objectData objectForKey:kTKDataHierarchyTempKey];
if (!temporaryFlag || ![temporaryFlag boolValue])
{
[self createHierarchyDataForObject:objectData withinNode:projectElement];
}
}
// Store the cleaned markup to the application data.
[database setObject:document forKey:kTKDataMainHierarchyKey];
// Save the markup.
NSError* error = nil;
NSData* markupData = [document XMLDataWithOptions:NSXMLNodePrettyPrint];
[document release];
NSString* filename = [self outputBasePath];
filename = [filename stringByAppendingPathComponent:[self outputHierarchyFilename]];
if (![markupData writeToFile:filename options:0 error:&error])
{
logError(@"Failed writting clean Hierarchy.xml to '%@'!", filename);
[Systemator throwExceptionWithName:kTKConverterException basedOnError:error];
}
[loopAutoreleasePool drain];
logInfo(@"Finished creating clean hierarchy documentation file.");
}
//----------------------------------------------------------------------------------------
- (void) fixCleanObjectDocumentation
{
logNormal(@"Fixing clean objects documentation links...");
// Prepare common variables to optimize loop a bit.
NSAutoreleasePool* loopAutoreleasePool = nil;
// Handle all files in the database.
NSDictionary* objects = [database objectForKey:kTKDataMainObjectsKey];
for (NSString* objectName in objects)
{
// Setup the autorelease pool for this iteration. Note that we are releasing the
// previous iteration pool here as well. This is because we use continue to
// skip certain iterations, so releasing at the end of the loop would not work...
// Also note that after the loop ends, we are releasing the last iteration loop.
[loopAutoreleasePool drain];
loopAutoreleasePool = [[NSAutoreleasePool alloc] init];
// Get the required object data.
NSMutableDictionary* objectData = [objects objectForKey:objectName];
logVerbose(@"- Handling '%@'...", objectName);
[self fixInheritanceForObject:objectName objectData:objectData objects:objects];
[self fixLocationForObject:objectName objectData:objectData objects:objects];
[self fixReferencesForObject:objectName objectData:objectData objects:objects];
[self fixParaLinksForObject:objectName objectData:objectData objects:objects];
[self fixEmptyParaForObject:objectName objectData:objectData objects:objects];
}
// When all fixes are applied, we can remove temporary objects from the hierarchies
// root level. The outside code relies on the fact that the hierarchies is "clean"
// and only contains objects on the places where they belong.
NSMutableDictionary* hierarchies = [database objectForKey:kTKDataMainHierarchiesKey];
for (int i = 0; i < [hierarchies count]; i++)
{
NSString* objectName = [[hierarchies allKeys] objectAtIndex:i];
NSDictionary* data = [hierarchies objectForKey:objectName];
NSNumber* temporary = [data objectForKey:kTKDataHierarchyTempKey];
if (temporary && [temporary boolValue])
{
logDebug(@" - Removing temporary object '%@' from root...", objectName);
[hierarchies removeObjectForKey:objectName];
i--;
}
}
// Release last iteration pool.
[loopAutoreleasePool drain];
logInfo(@"Finished fixing clean objects documentation links.");
}
//----------------------------------------------------------------------------------------
- (void) saveCleanObjectDocumentationFiles
{
logNormal(@"Saving clean object documentation files...");
// Save all objects.
NSDictionary* objects = [database objectForKey:kTKDataMainObjectsKey];
for (NSString* objectName in objects)
{
NSAutoreleasePool* loopAutoreleasePool = [[NSAutoreleasePool alloc] init];
NSDictionary* objectData = [objects objectForKey:objectName];
// Prepare the file name.
NSString* filename = [self outputBasePath];
filename = [filename stringByAppendingPathComponent:[self outputObjectFilenameForObject:objectData]];
// Save the document.
logVerbose(@"- Saving '%@' to '%@'...", objectName, filename);
NSXMLDocument* document = [objectData objectForKey:kTKDataObjectMarkupKey];
NSData* documentData = [document XMLDataWithOptions:NSXMLNodePrettyPrint];
if (![documentData writeToFile:filename atomically:NO])
{
logError(@"Failed saving '%@' to '%@'!", objectName, filename);
}
[loopAutoreleasePool drain];
}
logInfo(@"Finished saving clean object documentation files...");
}
//////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Clean XML "makeup" handling
//////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------
- (void) createMembersDataForObject:(NSString*) objectName
objectData:(NSMutableDictionary*) objectData
{
// Add the empty dictionary to the object data.
NSMutableDictionary* members = [NSMutableDictionary dictionary];
[objectData setObject:members forKey:kTKDataObjectMembersKey];
// Get the array of all member nodes.
NSXMLDocument* document = [objectData objectForKey:kTKDataObjectMarkupKey];
NSArray* memberNodes = [document nodesForXPath:@"object/sections/section/member" error:nil];
for (NSXMLElement* memberNode in memberNodes)
{
NSXMLNode* kindAttr = [memberNode attributeForName:@"kind"];
if (kindAttr)
{
NSArray* nameNodes = [memberNode nodesForXPath:@"name" error:nil];
if ([nameNodes count] > 0)
{
// Get member data.
NSString* memberName = [[nameNodes objectAtIndex:0] stringValue];
NSString* memberKind = [kindAttr stringValue];
// Prepare member prefix.
NSString* memberPrefix = @"";
if ([memberKind isEqualToString:@"class-method"])
memberPrefix = @"+";
else if ([memberKind isEqualToString:@"instance-method"])
memberPrefix = @"-";
// Prepare member selector. Note that we use the template to allow the
// users specify their desired format. If prefix is used, we should use
// the template, otherwise we stick to the name only. This avoids the
// empty spaces in front of properties for example.
NSString* memberSelector = nil;
if ([memberPrefix length] > 0)
{
memberSelector = cmd.memberReferenceTemplate;
memberSelector = [memberSelector stringByReplacingOccurrencesOfString:@"$PREFIX" withString:memberPrefix];
memberSelector = [memberSelector stringByReplacingOccurrencesOfString:@"$MEMBER" withString:memberName];
}
else
{
memberSelector = memberName;
}
logDebug(@" - Generating '%@' member data...", memberSelector);
// Create member data dictionary.
NSMutableDictionary* memberData = [NSMutableDictionary dictionary];
[memberData setObject:memberName forKey:kTKDataMemberNameKey];
[memberData setObject:memberPrefix forKey:kTKDataMemberPrefixKey];
[memberData setObject:memberSelector forKey:kTKDataMemberSelectorKey];
// Add the dictionary to the members data.
[members setObject:memberData forKey:memberName];
// Add the member selector to the XML.
NSXMLElement* selectorNode = [NSXMLNode elementWithName:@"selector" stringValue:memberSelector];
[memberNode addChild:selectorNode];
}
}
}
}
//----------------------------------------------------------------------------------------
- (void) createHierarchyDataForObject:(NSDictionary*) objectHierarchyData
withinNode:(NSXMLElement*) node
{
// Get the object data.
NSDictionary* objectData = [objectHierarchyData objectForKey:kTKDataHierarchyObjectDataKey];
NSDictionary* children = [objectHierarchyData objectForKey:kTKDataHierarchyChildrenKey];
NSString* objectName = [objectHierarchyData objectForKey:kTKDataHierarchyObjectNameKey];
NSString* objectKind = [objectData objectForKey:kTKDataObjectKindKey];
NSString* objectRef = [objectData valueForKey:kTKDataObjectRelPathKey];
if (!objectKind) objectKind = @"class";
logVerbose(@"- Handling '%@'...", objectName);
// Create the node that will represent the object itself.
NSXMLElement* objectNode = [NSXMLNode elementWithName:@"object"];
[objectNode addAttribute:[NSXMLNode attributeWithName:@"kind" stringValue:objectKind]];
if (objectRef) [objectNode addAttribute:[NSXMLNode attributeWithName:@"id" stringValue:objectRef]];
[node addChild:objectNode];
// Create the name subnode.
NSXMLElement* nameNode = [NSXMLNode elementWithName:@"name" stringValue:objectName];
[objectNode addChild:nameNode];
// If there are any children, process them. First create the children node, then
// add all children to it.
if ([children count] > 0)
{
NSXMLElement* childrenNode = [NSXMLNode elementWithName:@"children"];
[objectNode addChild:childrenNode];
NSArray* sortedChildrenNames = [[children allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSString* childName in sortedChildrenNames)
{
NSDictionary* childData = [children objectForKey:childName];
[self createHierarchyDataForObject:childData
withinNode:childrenNode];
}
}
}
//----------------------------------------------------------------------------------------
- (void) fixInheritanceForObject:(NSString*) objectName
objectData:(NSMutableDictionary*) objectData
objects:(NSDictionary*) objects
{
NSCharacterSet* whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
// Fix the base class link. If the base class is one of the known objects,
// add the id attribute so we can link to it when creating xhtml. Note that
// we need to handle protocols here too - if a class conforms to protocols,
// we should change the name of the node from <base> to <conforms> so that we
// have easier job while generating html. We should also create the link to
// the known protocols.
NSXMLDocument* cleanDocument = [objectData objectForKey:kTKDataObjectMarkupKey];
NSArray* baseNodes = [cleanDocument nodesForXPath:@"/object/base" error:nil];
for (NSXMLElement* baseNode in baseNodes)
{
NSString* refValue = [baseNode stringValue];
if ([objects objectForKey:refValue])
{
NSString* linkReference = [self objectReferenceFromObject:objectName toObject:refValue];
NSXMLNode* idAttribute = [NSXMLNode attributeWithName:@"id" stringValue:linkReference];
[baseNode addAttribute:idAttribute];
logDebug(@" - Found base class reference to '%@' at '%@'.", refValue, linkReference);
}
else
{
refValue = [refValue stringByTrimmingCharactersInSet:whitespaceSet];
if ([refValue hasPrefix:@"<"] && [refValue hasSuffix:@">"])
{
NSRange protocolNameRange = NSMakeRange(1, [refValue length] - 2);
refValue = [refValue substringWithRange:protocolNameRange];
refValue = [refValue stringByTrimmingCharactersInSet:whitespaceSet];
NSXMLElement* protocolNode = [NSXMLNode elementWithName:@"protocol"];
[protocolNode setStringValue:refValue];
if ([objects objectForKey:refValue])
{
NSString* linkReference = [self objectReferenceFromObject:objectName toObject:refValue];
NSXMLNode* idAttribute = [NSXMLNode attributeWithName:@"id" stringValue:linkReference];
[protocolNode addAttribute:idAttribute];
logDebug(@" - Found protocol reference to '%@' at '%@'.", refValue, linkReference);
}
else
{
logDebug(@" - Found protocol reference to '%@'.", refValue);
}
NSUInteger index = [baseNode index];
NSXMLElement* parentNode = (NSXMLElement*)[baseNode parent];
[parentNode replaceChildAtIndex:index withNode:protocolNode];
}
}
}
// Now prepare the object full hierarchy. This will add additional <base> nodes after
// the main one for classes which have "deep" inheritance. All known bases will also
// be documented. Note that we only handle objects that are contained in the hierarchy.
// Also note that we need to fetch base nodes again (we should only have one now,
// however we play safe and start adding after the last one).
NSString* parentName = [objectData objectForKey:kTKDataObjectParentKey];
if (parentName)
{
// We need the object node in case there's non base node - then we should just
// add additional base nodes directly to the object node.
NSArray* objectNodes = [cleanDocument nodesForXPath:@"object" error:nil];
NSXMLElement* objectNode = [objectNodes lastObject];
// Prepare default insertion index. If object node contains less than 4 subnodes
// (name, file, base), we should insert to the end, otherwise we should insert
// after the third (after the base node). However, if the node contains base
// subnodes, we will properly setup the insertion index after the last one.
NSUInteger insertionIndex = ([objectNode childCount] < 4) ? [objectNode childCount] - 1 : 3;
NSArray* baseNodes = [objectNode nodesForXPath:@"base" error:nil];
if ([baseNodes count] > 0)
{
insertionIndex = [[baseNodes lastObject] index] + 1;
}
// Note that this loop will skip the immediate object's parent since this one is
// already documented. However to avoid code repetition, this is not handled
// outside, and therefore requires a conditional within the loop.
int parentLevel = 0;
while (parentName)
{
// Only handle second level inheritance...
NSDictionary* parentData = [objects objectForKey:parentName];
if (parentLevel > 0)
{
NSXMLElement* baseNode = [NSXMLNode elementWithName:@"base" stringValue:parentName];
if (parentData)
{
NSString* linkReference = [self objectReferenceFromObject:objectName toObject:parentName];
NSXMLNode* idAttribute = [NSXMLNode attributeWithName:@"id" stringValue:linkReference];
[baseNode addAttribute:idAttribute];
}
[objectNode insertChild:baseNode atIndex:insertionIndex];
insertionIndex++;
}
// Continue with the next parent.
parentName = [parentData objectForKey:kTKDataObjectParentKey];
parentLevel++;
}
}
}
//----------------------------------------------------------------------------------------
- (void) fixLocationForObject:(NSString*) objectName
objectData:(NSMutableDictionary*) objectData
objects:(NSDictionary*) objects
{
// We only need to check this for classes and only if this is enabled.
if (cmd.fixClassLocations && [[objectData objectForKey:kTKDataObjectKindKey] isEqualToString:@"class"])
{
NSXMLDocument* cleanDocument = [objectData objectForKey:kTKDataObjectMarkupKey];
NSArray* fileNodes = [cleanDocument nodesForXPath:@"object/file" error:nil];
if ([fileNodes count] > 0)
{
for (NSXMLElement* fileNode in fileNodes)
{
// If path extension is not .h, check further.
NSString* path = [fileNode stringValue];
NSString* extension = [path pathExtension];
if ([extension isEqualToString:@"m"] ||
[extension isEqualToString:@"mm"])
{
// If the path contains other parts, besides extension and file name,
// or it doesn't start with the object name, replace it...
if (![path hasPrefix:objectName] ||
[path length] != [extension length] + [objectName length] + 1)
{
NSString* newPath = [NSString stringWithFormat:@"%@.h", objectName];
logDebug(@" - Fixing strange looking class file '%@' to '%@'...",
path,
newPath);
[fileNode setStringValue:newPath];
}
}
}
}
}
}
//----------------------------------------------------------------------------------------
- (void) fixReferencesForObject:(NSString*) objectName
objectData:(NSMutableDictionary*) objectData
objects:(NSDictionary*) objects
{
NSCharacterSet* whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
NSCharacterSet* classStartSet = [NSCharacterSet characterSetWithCharactersInString:@"("];
NSCharacterSet* classEndSet = [NSCharacterSet characterSetWithCharactersInString:@")"];
NSCharacterSet* invalidSet = [NSCharacterSet characterSetWithCharactersInString:@" -+"];
// Now look for all <ref> nodes. Then determine the type of link from the link
// text. The link can either be internal, within the same object or it can be
// to a member of another object.
NSXMLDocument* cleanDocument = [objectData objectForKey:kTKDataObjectMarkupKey];
NSArray* refNodes = [cleanDocument nodesForXPath:@"//ref" error:nil];
for (NSXMLElement* refNode in refNodes)
{
// Get the reference (link) object and member components. The links from
// doxygen have the format "memberName (ClassName)". The member name includes
// all the required objective-c colons for methods. Note that some links may
// only contain member and some only object components! The links that only
// contain object component don't encapsulate the object name within the
// parenthesis! However these are all links to the current object, so we can
// easily determine the type by comparing to the current object name.
NSString* refValue = [refNode stringValue];
if ([refValue length] > 0)
{
NSString* refObject = nil;
NSString* refMember = nil;
NSScanner* scanner = [NSScanner scannerWithString:refValue];