-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
monodocer.cs
5009 lines (4405 loc) · 151 KB
/
monodocer.cs
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
// Updater program for syncing Mono's ECMA-style documentation files
// with an assembly.
// By Joshua Tauberer <tauberer@for.net>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Mono.Cecil;
using Mono.Options;
using MyXmlNodeList = System.Collections.Generic.List<System.Xml.XmlNode>;
using StringList = System.Collections.Generic.List<string>;
using StringToStringMap = System.Collections.Generic.Dictionary<string, string>;
using StringToXmlNodeMap = System.Collections.Generic.Dictionary<string, System.Xml.XmlNode>;
namespace Mono.Documentation {
class MDocUpdater : MDocCommand
{
string srcPath;
List<AssemblyDefinition> assemblies;
readonly DefaultAssemblyResolver assemblyResolver = new DefaultAssemblyResolver();
bool delete;
bool show_exceptions;
bool no_assembly_versions, ignore_missing_types;
ExceptionLocations? exceptions;
internal int additions = 0, deletions = 0;
List<DocumentationImporter> importers = new List<DocumentationImporter> ();
DocumentationEnumerator docEnum;
string since;
static readonly MemberFormatter docTypeFormatter = new DocTypeMemberFormatter ();
static readonly MemberFormatter filenameFormatter = new FileNameMemberFormatter ();
static MemberFormatter[] typeFormatters = new MemberFormatter[]{
new CSharpMemberFormatter (),
new ILMemberFormatter (),
};
static MemberFormatter[] memberFormatters = new MemberFormatter[]{
new CSharpFullMemberFormatter (),
new ILFullMemberFormatter (),
};
internal static readonly MemberFormatter slashdocFormatter = new SlashDocMemberFormatter ();
MyXmlNodeList extensionMethods = new MyXmlNodeList ();
HashSet<string> forwardedTypes = new HashSet<string> ();
public override void Run (IEnumerable<string> args)
{
show_exceptions = DebugOutput;
var types = new List<string> ();
var p = new OptionSet () {
{ "delete",
"Delete removed members from the XML files.",
v => delete = v != null },
{ "exceptions:",
"Document potential exceptions that members can generate. {SOURCES} " +
"is a comma-separated list of:\n" +
" asm Method calls in same assembly\n" +
" depasm Method calls in dependent assemblies\n" +
" all Record all possible exceptions\n" +
" added Modifier; only create <exception/>s\n" +
" for NEW types/members\n" +
"If nothing is specified, then only exceptions from the member will " +
"be listed.",
v => exceptions = ParseExceptionLocations (v) },
{ "f=",
"Specify a {FLAG} to alter behavior. See later -f* options for available flags.",
v => {
switch (v) {
case "ignore-missing-types":
ignore_missing_types = true;
break;
case "no-assembly-versions":
no_assembly_versions = true;
break;
default:
throw new Exception ("Unsupported flag `" + v + "'.");
}
} },
{ "fignore-missing-types",
"Do not report an error if a --type=TYPE type\nwas not found.",
v => ignore_missing_types = v != null },
{ "fno-assembly-versions",
"Do not generate //AssemblyVersion elements.",
v => no_assembly_versions = v != null },
{ "i|import=",
"Import documentation from {FILE}.",
v => AddImporter (v) },
{ "L|lib=",
"Check for assembly references in {DIRECTORY}.",
v => assemblyResolver.AddSearchDirectory (v) },
{ "library=",
"Ignored for compatibility with update-ecma-xml.",
v => {} },
{ "o|out=",
"Root {DIRECTORY} to generate/update documentation.",
v => srcPath = v },
{ "r=",
"Search for dependent assemblies in the directory containing {ASSEMBLY}.\n" +
"(Equivalent to '-L `dirname ASSEMBLY`'.)",
v => assemblyResolver.AddSearchDirectory (Path.GetDirectoryName (v)) },
{ "since=",
"Manually specify the assembly {VERSION} that new members were added in.",
v => since = v },
{ "type=",
"Only update documentation for {TYPE}.",
v => types.Add (v) },
};
var assemblies = Parse (p, args, "update",
"[OPTIONS]+ ASSEMBLIES",
"Create or update documentation from ASSEMBLIES.");
if (assemblies == null)
return;
if (assemblies.Count == 0)
Error ("No assemblies specified.");
foreach (var dir in assemblies
.Where (a => a.Contains (Path.DirectorySeparatorChar))
.Select (a => Path.GetDirectoryName (a)))
assemblyResolver.AddSearchDirectory (dir);
// PARSE BASIC OPTIONS AND LOAD THE ASSEMBLY TO DOCUMENT
if (srcPath == null)
throw new InvalidOperationException("The --out option is required.");
this.assemblies = assemblies.Select (a => LoadAssembly (a)).ToList ();
// Store types that have been forwarded to avoid duplicate generation
GatherForwardedTypes ();
docEnum = docEnum ?? new DocumentationEnumerator ();
// PERFORM THE UPDATES
if (types.Count > 0) {
types.Sort ();
DoUpdateTypes (srcPath, types, srcPath);
}
#if false
else if (opts.@namespace != null)
DoUpdateNS (opts.@namespace, Path.Combine (opts.path, opts.@namespace),
Path.Combine (dest_dir, opts.@namespace));
#endif
else
DoUpdateAssemblies (srcPath, srcPath);
Console.WriteLine("Members Added: {0}, Members Deleted: {1}", additions, deletions);
}
void AddImporter (string path)
{
try {
XmlReader r = new XmlTextReader (path);
if (r.Read ()) {
while (r.NodeType != XmlNodeType.Element) {
if (!r.Read ())
Error ("Unable to read XML file: {0}.", path);
}
if (r.LocalName == "doc") {
importers.Add (new MsxdocDocumentationImporter (path));
}
else if (r.LocalName == "Libraries") {
var ecmadocs = new XmlTextReader (path);
docEnum = new EcmaDocumentationEnumerator (this, ecmadocs);
importers.Add (new EcmaDocumentationImporter (ecmadocs));
}
else
Error ("Unsupported XML format within {0}.", path);
}
r.Close ();
} catch (Exception e) {
Environment.ExitCode = 1;
Error ("Could not load XML file: {0}.", e.Message);
}
}
void GatherForwardedTypes ()
{
foreach (var asm in assemblies)
foreach (var type in asm.MainModule.ExportedTypes.Where (t => t.IsForwarder).Select (t => t.FullName))
forwardedTypes.Add (type);
}
static ExceptionLocations ParseExceptionLocations (string s)
{
ExceptionLocations loc = ExceptionLocations.Member;
if (s == null)
return loc;
foreach (var type in s.Split (',')) {
switch (type) {
case "added": loc |= ExceptionLocations.AddedMembers; break;
case "all": loc |= ExceptionLocations.Assembly | ExceptionLocations.DependentAssemblies; break;
case "asm": loc |= ExceptionLocations.Assembly; break;
case "depasm": loc |= ExceptionLocations.DependentAssemblies; break;
default: throw new NotSupportedException ("Unsupported --exceptions value: " + type);
}
}
return loc;
}
internal void Warning (string format, params object[] args)
{
Message (TraceLevel.Warning, "mdoc: " + format, args);
}
private AssemblyDefinition LoadAssembly (string name)
{
AssemblyDefinition assembly = null;
try {
assembly = AssemblyDefinition.ReadAssembly (name, new ReaderParameters { AssemblyResolver = assemblyResolver });
} catch (System.IO.FileNotFoundException) { }
if (assembly == null)
throw new InvalidOperationException("Assembly " + name + " not found.");
return assembly;
}
private static void WriteXml(XmlElement element, System.IO.TextWriter output) {
OrderTypeAttributes (element);
XmlTextWriter writer = new XmlTextWriter(output);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.IndentChar = ' ';
element.WriteTo(writer);
output.WriteLine();
}
private static void WriteFile (string filename, FileMode mode, Action<TextWriter> action)
{
Action<string> creator = file => {
using (var writer = OpenWrite (file, mode))
action (writer);
};
MdocFile.UpdateFile (filename, creator);
}
private static void OrderTypeAttributes (XmlElement e)
{
foreach (XmlElement type in e.SelectNodes ("//Type")) {
OrderTypeAttributes (type.Attributes);
}
}
static readonly string[] TypeAttributeOrder = {
"Name", "FullName", "FullNameSP", "Maintainer"
};
private static void OrderTypeAttributes (XmlAttributeCollection c)
{
XmlAttribute[] attrs = new XmlAttribute [TypeAttributeOrder.Length];
for (int i = 0; i < c.Count; ++i) {
XmlAttribute a = c [i];
for (int j = 0; j < TypeAttributeOrder.Length; ++j) {
if (a.Name == TypeAttributeOrder [j]) {
attrs [j] = a;
break;
}
}
}
for (int i = attrs.Length-1; i >= 0; --i) {
XmlAttribute n = attrs [i];
if (n == null)
continue;
XmlAttribute r = null;
for (int j = i+1; j < attrs.Length; ++j) {
if (attrs [j] != null) {
r = attrs [j];
break;
}
}
if (r == null)
continue;
c.Remove (n);
c.InsertBefore (n, r);
}
}
private XmlDocument CreateIndexStub()
{
XmlDocument index = new XmlDocument();
XmlElement index_root = index.CreateElement("Overview");
index.AppendChild(index_root);
if (assemblies.Count == 0)
throw new Exception ("No assembly");
XmlElement index_assemblies = index.CreateElement("Assemblies");
index_root.AppendChild(index_assemblies);
XmlElement index_remarks = index.CreateElement("Remarks");
index_remarks.InnerText = "To be added.";
index_root.AppendChild(index_remarks);
XmlElement index_copyright = index.CreateElement("Copyright");
index_copyright.InnerText = "To be added.";
index_root.AppendChild(index_copyright);
XmlElement index_types = index.CreateElement("Types");
index_root.AppendChild(index_types);
return index;
}
private static void WriteNamespaceStub(string ns, string outdir) {
XmlDocument index = new XmlDocument();
XmlElement index_root = index.CreateElement("Namespace");
index.AppendChild(index_root);
index_root.SetAttribute("Name", ns);
XmlElement index_docs = index.CreateElement("Docs");
index_root.AppendChild(index_docs);
XmlElement index_summary = index.CreateElement("summary");
index_summary.InnerText = "To be added.";
index_docs.AppendChild(index_summary);
XmlElement index_remarks = index.CreateElement("remarks");
index_remarks.InnerText = "To be added.";
index_docs.AppendChild(index_remarks);
WriteFile (outdir + "/ns-" + ns + ".xml", FileMode.CreateNew,
writer => WriteXml (index.DocumentElement, writer));
}
public void DoUpdateTypes (string basepath, List<string> typenames, string dest)
{
var index = CreateIndexForTypes (dest);
var found = new HashSet<string> ();
foreach (AssemblyDefinition assembly in assemblies) {
foreach (TypeDefinition type in docEnum.GetDocumentationTypes (assembly, typenames)) {
string relpath = DoUpdateType (type, basepath, dest);
if (relpath == null)
continue;
found.Add (type.FullName);
if (index == null)
continue;
index.Add (assembly);
index.Add (type);
}
}
if (index != null)
index.Write ();
if (ignore_missing_types)
return;
var notFound = from n in typenames where !found.Contains (n) select n;
if (notFound.Any ())
throw new InvalidOperationException("Type(s) not found: " + string.Join (", ", notFound.ToArray ()));
}
class IndexForTypes {
MDocUpdater app;
string indexFile;
XmlDocument index;
XmlElement index_types;
XmlElement index_assemblies;
public IndexForTypes (MDocUpdater app, string indexFile, XmlDocument index)
{
this.app = app;
this.indexFile = indexFile;
this.index = index;
index_types = WriteElement (index.DocumentElement, "Types");
index_assemblies = WriteElement (index.DocumentElement, "Assemblies");
}
public void Add (AssemblyDefinition assembly)
{
if (index_assemblies.SelectSingleNode ("Assembly[@Name='" + assembly.Name.Name + "']") != null)
return;
app.AddIndexAssembly (assembly, index_assemblies);
}
public void Add (TypeDefinition type)
{
app.AddIndexType (type, index_types);
}
public void Write ()
{
SortIndexEntries (index_types);
WriteFile (indexFile, FileMode.Create,
writer => WriteXml (index.DocumentElement, writer));
}
}
IndexForTypes CreateIndexForTypes (string dest)
{
string indexFile = Path.Combine (dest, "index.xml");
if (File.Exists (indexFile))
return null;
return new IndexForTypes (this, indexFile, CreateIndexStub ());
}
public string DoUpdateType (TypeDefinition type, string basepath, string dest)
{
if (type.Namespace == null)
Warning ("warning: The type `{0}' is in the root namespace. This may cause problems with display within monodoc.",
type.FullName);
if (!IsPublic (type))
return null;
// Must get the A+B form of the type name.
string typename = GetTypeFileName(type);
string reltypefile = DocUtils.PathCombine (DocUtils.GetNamespace (type), typename + ".xml");
string typefile = Path.Combine (basepath, reltypefile);
System.IO.FileInfo file = new System.IO.FileInfo(typefile);
string output = null;
if (dest == null) {
output = typefile;
} else if (dest == "-") {
output = null;
} else {
output = Path.Combine (dest, reltypefile);
}
if (file.Exists) {
// Update
XmlDocument basefile = new XmlDocument();
try {
basefile.Load(typefile);
} catch (Exception e) {
throw new InvalidOperationException("Error loading " + typefile + ": " + e.Message, e);
}
DoUpdateType2("Updating", basefile, type, output, false);
} else {
// Stub
XmlElement td = StubType(type, output);
if (td == null)
return null;
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo (DocUtils.PathCombine (dest, type.Namespace));
if (!dir.Exists) {
dir.Create();
Console.WriteLine("Namespace Directory Created: " + type.Namespace);
}
}
return reltypefile;
}
public void DoUpdateNS (string ns, string nspath, string outpath)
{
Dictionary<TypeDefinition, object> seenTypes = new Dictionary<TypeDefinition,object> ();
AssemblyDefinition assembly = assemblies [0];
foreach (System.IO.FileInfo file in new System.IO.DirectoryInfo(nspath).GetFiles("*.xml")) {
XmlDocument basefile = new XmlDocument();
string typefile = Path.Combine(nspath, file.Name);
try {
basefile.Load(typefile);
} catch (Exception e) {
throw new InvalidOperationException("Error loading " + typefile + ": " + e.Message, e);
}
string typename =
GetTypeFileName (basefile.SelectSingleNode("Type/@FullName").InnerText);
TypeDefinition type = assembly.GetType(typename);
if (type == null) {
Warning ("Type no longer in assembly: " + typename);
continue;
}
seenTypes[type] = seenTypes;
DoUpdateType2("Updating", basefile, type, Path.Combine(outpath, file.Name), false);
}
// Stub types not in the directory
foreach (TypeDefinition type in docEnum.GetDocumentationTypes (assembly, null)) {
if (type.Namespace != ns || seenTypes.ContainsKey(type))
continue;
XmlElement td = StubType(type, Path.Combine(outpath, GetTypeFileName(type) + ".xml"));
if (td == null) continue;
}
}
private static string GetTypeFileName (TypeReference type)
{
return filenameFormatter.GetName (type);
}
public static string GetTypeFileName (string typename)
{
StringBuilder filename = new StringBuilder (typename.Length);
int numArgs = 0;
int numLt = 0;
bool copy = true;
for (int i = 0; i < typename.Length; ++i) {
char c = typename [i];
switch (c) {
case '<':
copy = false;
++numLt;
break;
case '>':
--numLt;
if (numLt == 0) {
filename.Append ('`').Append ((numArgs+1).ToString());
numArgs = 0;
copy = true;
}
break;
case ',':
if (numLt == 1)
++numArgs;
break;
default:
if (copy)
filename.Append (c);
break;
}
}
return filename.ToString ();
}
private void AddIndexAssembly (AssemblyDefinition assembly, XmlElement parent)
{
XmlElement index_assembly = parent.OwnerDocument.CreateElement("Assembly");
index_assembly.SetAttribute ("Name", assembly.Name.Name);
index_assembly.SetAttribute ("Version", assembly.Name.Version.ToString());
AssemblyNameDefinition name = assembly.Name;
if (name.HasPublicKey) {
XmlElement pubkey = parent.OwnerDocument.CreateElement ("AssemblyPublicKey");
var key = new StringBuilder (name.PublicKey.Length*3 + 2);
key.Append ("[");
foreach (byte b in name.PublicKey)
key.AppendFormat ("{0,2:x2} ", b);
key.Append ("]");
pubkey.InnerText = key.ToString ();
index_assembly.AppendChild (pubkey);
}
if (!string.IsNullOrEmpty (name.Culture)) {
XmlElement culture = parent.OwnerDocument.CreateElement ("AssemblyCulture");
culture.InnerText = name.Culture;
index_assembly.AppendChild (culture);
}
MakeAttributes (index_assembly, GetCustomAttributes (assembly.CustomAttributes, ""));
parent.AppendChild(index_assembly);
}
private void AddIndexType (TypeDefinition type, XmlElement index_types)
{
string typename = GetTypeFileName(type);
// Add namespace and type nodes into the index file as needed
string ns = DocUtils.GetNamespace (type);
XmlElement nsnode = (XmlElement) index_types.SelectSingleNode ("Namespace[@Name='" + ns + "']");
if (nsnode == null) {
nsnode = index_types.OwnerDocument.CreateElement("Namespace");
nsnode.SetAttribute ("Name", ns);
index_types.AppendChild (nsnode);
}
string doc_typename = GetDocTypeName (type);
XmlElement typenode = (XmlElement) nsnode.SelectSingleNode ("Type[@Name='" + typename + "']");
if (typenode == null) {
typenode = index_types.OwnerDocument.CreateElement ("Type");
typenode.SetAttribute ("Name", typename);
nsnode.AppendChild (typenode);
}
if (typename != doc_typename)
typenode.SetAttribute("DisplayName", doc_typename);
else
typenode.RemoveAttribute("DisplayName");
typenode.SetAttribute ("Kind", GetTypeKind (type));
}
private void DoUpdateAssemblies (string source, string dest)
{
string indexfile = dest + "/index.xml";
XmlDocument index;
if (System.IO.File.Exists(indexfile)) {
index = new XmlDocument();
index.Load(indexfile);
// Format change
ClearElement(index.DocumentElement, "Assembly");
ClearElement(index.DocumentElement, "Attributes");
} else {
index = CreateIndexStub();
}
string defaultTitle = "Untitled";
if (assemblies.Count == 1)
defaultTitle = assemblies[0].Name.Name;
WriteElementInitialText(index.DocumentElement, "Title", defaultTitle);
XmlElement index_types = WriteElement(index.DocumentElement, "Types");
XmlElement index_assemblies = WriteElement(index.DocumentElement, "Assemblies");
index_assemblies.RemoveAll ();
HashSet<string> goodfiles = new HashSet<string> (StringComparer.OrdinalIgnoreCase);
foreach (AssemblyDefinition assm in assemblies) {
AddIndexAssembly (assm, index_assemblies);
DoUpdateAssembly (assm, index_types, source, dest, goodfiles);
}
SortIndexEntries (index_types);
CleanupFiles (dest, goodfiles);
CleanupIndexTypes (index_types, goodfiles);
CleanupExtensions (index_types);
WriteFile (indexfile, FileMode.Create,
writer => WriteXml(index.DocumentElement, writer));
}
private static char[] InvalidFilenameChars = {'\\', '/', ':', '*', '?', '"', '<', '>', '|'};
private void DoUpdateAssembly (AssemblyDefinition assembly, XmlElement index_types, string source, string dest, HashSet<string> goodfiles)
{
foreach (TypeDefinition type in docEnum.GetDocumentationTypes (assembly, null)) {
string typename = GetTypeFileName(type);
if (!IsPublic (type) || typename.IndexOfAny (InvalidFilenameChars) >= 0 || forwardedTypes.Contains (type.FullName))
continue;
string reltypepath = DoUpdateType (type, source, dest);
if (reltypepath == null)
continue;
// Add namespace and type nodes into the index file as needed
AddIndexType (type, index_types);
// Ensure the namespace index file exists
string onsdoc = DocUtils.PathCombine (dest, type.Namespace + ".xml");
string nsdoc = DocUtils.PathCombine (dest, "ns-" + type.Namespace + ".xml");
if (File.Exists (onsdoc)) {
File.Move (onsdoc, nsdoc);
}
if (!File.Exists (nsdoc)) {
Console.WriteLine("New Namespace File: " + type.Namespace);
WriteNamespaceStub(type.Namespace, dest);
}
goodfiles.Add (reltypepath);
}
}
private static void SortIndexEntries (XmlElement indexTypes)
{
XmlNodeList namespaces = indexTypes.SelectNodes ("Namespace");
XmlNodeComparer c = new AttributeNameComparer ();
SortXmlNodes (indexTypes, namespaces, c);
for (int i = 0; i < namespaces.Count; ++i)
SortXmlNodes (namespaces [i], namespaces [i].SelectNodes ("Type"), c);
}
private static void SortXmlNodes (XmlNode parent, XmlNodeList children, XmlNodeComparer comparer)
{
MyXmlNodeList l = new MyXmlNodeList (children.Count);
for (int i = 0; i < children.Count; ++i)
l.Add (children [i]);
l.Sort (comparer);
for (int i = l.Count - 1; i > 0; --i) {
parent.InsertBefore (parent.RemoveChild ((XmlNode) l [i-1]), (XmlNode) l [i]);
}
}
abstract class XmlNodeComparer : IComparer, IComparer<XmlNode>
{
public abstract int Compare (XmlNode x, XmlNode y);
public int Compare (object x, object y)
{
return Compare ((XmlNode) x, (XmlNode) y);
}
}
class AttributeNameComparer : XmlNodeComparer {
string attribute;
public AttributeNameComparer ()
: this ("Name")
{
}
public AttributeNameComparer (string attribute)
{
this.attribute = attribute;
}
public override int Compare (XmlNode x, XmlNode y)
{
return x.Attributes [attribute].Value.CompareTo (y.Attributes [attribute].Value);
}
}
class VersionComparer : XmlNodeComparer {
public override int Compare (XmlNode x, XmlNode y)
{
// Some of the existing docs use e.g. 1.0.x.x, which Version doesn't like.
string a = GetVersion (x.InnerText);
string b = GetVersion (y.InnerText);
return new Version (a).CompareTo (new Version (b));
}
static string GetVersion (string v)
{
int n = v.IndexOf ("x");
if (n < 0)
return v;
return v.Substring (0, n-1);
}
}
private static string GetTypeKind (TypeDefinition type)
{
if (type.IsEnum)
return "Enumeration";
if (type.IsValueType)
return "Structure";
if (type.IsInterface)
return "Interface";
if (DocUtils.IsDelegate (type))
return "Delegate";
if (type.IsClass || type.FullName == "System.Enum") // FIXME
return "Class";
throw new ArgumentException ("Unknown kind for type: " + type.FullName);
}
private static bool IsPublic (TypeDefinition type)
{
TypeDefinition decl = type;
while (decl != null) {
if (!(decl.IsPublic || decl.IsNestedPublic ||
decl.IsNestedFamily || decl.IsNestedFamily || decl.IsNestedFamilyOrAssembly)) {
return false;
}
decl = (TypeDefinition) decl.DeclaringType;
}
return true;
}
private void CleanupFiles (string dest, HashSet<string> goodfiles)
{
// Look for files that no longer correspond to types
foreach (System.IO.DirectoryInfo nsdir in new System.IO.DirectoryInfo(dest).GetDirectories("*")) {
foreach (System.IO.FileInfo typefile in nsdir.GetFiles("*.xml")) {
string relTypeFile = Path.Combine(nsdir.Name, typefile.Name);
if (!goodfiles.Contains (relTypeFile)) {
XmlDocument doc = new XmlDocument ();
doc.Load (typefile.FullName);
XmlElement e = doc.SelectSingleNode("/Type") as XmlElement;
if (e != null && !no_assembly_versions && UpdateAssemblyVersions(e, GetAssemblyVersions(), false)) {
using (TextWriter writer = OpenWrite (typefile.FullName, FileMode.Truncate))
WriteXml(doc.DocumentElement, writer);
goodfiles.Add (relTypeFile);
continue;
}
string newname = typefile.FullName + ".remove";
try { System.IO.File.Delete(newname); } catch (Exception) { }
try { typefile.MoveTo(newname); } catch (Exception) { }
Console.WriteLine("Class no longer present; file renamed: " + Path.Combine(nsdir.Name, typefile.Name));
}
}
}
}
private static TextWriter OpenWrite (string path, FileMode mode)
{
var w = new StreamWriter (
new FileStream (path, mode),
new UTF8Encoding (false)
);
w.NewLine = "\n";
return w;
}
private string[] GetAssemblyVersions ()
{
return (from a in assemblies select GetAssemblyVersion (a)).ToArray ();
}
private static void CleanupIndexTypes (XmlElement index_types, HashSet<string> goodfiles)
{
// Look for type nodes that no longer correspond to types
MyXmlNodeList remove = new MyXmlNodeList ();
foreach (XmlElement typenode in index_types.SelectNodes("Namespace/Type")) {
string fulltypename = Path.Combine (((XmlElement)typenode.ParentNode).GetAttribute("Name"), typenode.GetAttribute("Name") + ".xml");
if (!goodfiles.Contains (fulltypename)) {
remove.Add (typenode);
}
}
foreach (XmlNode n in remove)
n.ParentNode.RemoveChild (n);
}
private void CleanupExtensions (XmlElement index_types)
{
XmlNode e = index_types.SelectSingleNode ("/Overview/ExtensionMethods");
if (extensionMethods.Count == 0) {
if (e == null)
return;
index_types.SelectSingleNode ("/Overview").RemoveChild (e);
return;
}
if (e == null) {
e = index_types.OwnerDocument.CreateElement ("ExtensionMethods");
index_types.SelectSingleNode ("/Overview").AppendChild (e);
}
else
e.RemoveAll ();
extensionMethods.Sort (DefaultExtensionMethodComparer);
foreach (XmlNode m in extensionMethods) {
e.AppendChild (index_types.OwnerDocument.ImportNode (m, true));
}
}
class ExtensionMethodComparer : XmlNodeComparer {
public override int Compare (XmlNode x, XmlNode y)
{
XmlNode xLink = x.SelectSingleNode ("Member/Link");
XmlNode yLink = y.SelectSingleNode ("Member/Link");
int n = xLink.Attributes ["Type"].Value.CompareTo (
yLink.Attributes ["Type"].Value);
if (n != 0)
return n;
n = xLink.Attributes ["Member"].Value.CompareTo (
yLink.Attributes ["Member"].Value);
if (n == 0 && !object.ReferenceEquals (x, y))
throw new InvalidOperationException ("Duplicate extension method found!");
return n;
}
}
static readonly XmlNodeComparer DefaultExtensionMethodComparer = new ExtensionMethodComparer ();
public void DoUpdateType2 (string message, XmlDocument basefile, TypeDefinition type, string output, bool insertSince)
{
Console.WriteLine(message + ": " + type.FullName);
StringToXmlNodeMap seenmembers = new StringToXmlNodeMap ();
// Update type metadata
UpdateType(basefile.DocumentElement, type);
// Update existing members. Delete member nodes that no longer should be there,
// and remember what members are already documented so we don't add them again.
if (true) {
MyXmlNodeList todelete = new MyXmlNodeList ();
foreach (DocsNodeInfo info in docEnum.GetDocumentationMembers (basefile, type)) {
XmlElement oldmember = info.Node;
MemberReference oldmember2 = info.Member;
string sig = oldmember2 != null ? memberFormatters [0].GetDeclaration (oldmember2) : null;
// Interface implementations and overrides are deleted from the docs
// unless the overrides option is given.
if (oldmember2 != null && sig == null)
oldmember2 = null;
// Deleted (or signature changed)
if (oldmember2 == null) {
if (!no_assembly_versions && UpdateAssemblyVersions (oldmember, new string[]{ GetAssemblyVersion (type.Module.Assembly) }, false))
continue;
DeleteMember ("Member Removed", output, oldmember, todelete);
continue;
}
// Duplicated
if (seenmembers.ContainsKey (sig)) {
if (object.ReferenceEquals (oldmember, seenmembers [sig])) {
// ignore, already seen
}
else if (DefaultMemberComparer.Compare (oldmember, seenmembers [sig]) == 0)
DeleteMember ("Duplicate Member Found", output, oldmember, todelete);
else
Warning ("TODO: found a duplicate member '{0}', but it's not identical to the prior member found!", sig);
continue;
}
// Update signature information
UpdateMember(info);
seenmembers.Add (sig, oldmember);
}
foreach (XmlElement oldmember in todelete)
oldmember.ParentNode.RemoveChild (oldmember);
}
if (!DocUtils.IsDelegate (type)) {
XmlNode members = WriteElement (basefile.DocumentElement, "Members");
foreach (MemberReference m in type.GetMembers()) {
if (m is TypeDefinition) continue;
string sig = memberFormatters [0].GetDeclaration (m);
if (sig == null) continue;
if (seenmembers.ContainsKey(sig)) continue;
XmlElement mm = MakeMember(basefile, new DocsNodeInfo (null, m));
if (mm == null) continue;
members.AppendChild( mm );
Console.WriteLine("Member Added: " + mm.SelectSingleNode("MemberSignature/@Value").InnerText);
additions++;
}
}
// Import code snippets from files
foreach (XmlNode code in basefile.GetElementsByTagName("code")) {
if (!(code is XmlElement)) continue;
string file = ((XmlElement)code).GetAttribute("src");
string lang = ((XmlElement)code).GetAttribute("lang");
if (file != "") {
string src = GetCodeSource (lang, Path.Combine (srcPath, file));
if (src != null)
code.InnerText = src;
}
}
if (insertSince && since != null) {
XmlNode docs = basefile.DocumentElement.SelectSingleNode("Docs");
docs.AppendChild (CreateSinceNode (basefile));
}
do {
XmlElement d = basefile.DocumentElement ["Docs"];
XmlElement m = basefile.DocumentElement ["Members"];
if (d != null && m != null)
basefile.DocumentElement.InsertBefore (
basefile.DocumentElement.RemoveChild (d), m);
SortTypeMembers (m);
} while (false);
if (output == null)
WriteXml(basefile.DocumentElement, Console.Out);
else {
FileInfo file = new FileInfo (output);
if (!file.Directory.Exists) {
Console.WriteLine("Namespace Directory Created: " + type.Namespace);
file.Directory.Create ();
}
WriteFile (output, FileMode.Create,
writer => WriteXml(basefile.DocumentElement, writer));
}
}
private string GetCodeSource (string lang, string file)
{
int anchorStart;
if (lang == "C#" && (anchorStart = file.IndexOf (".cs#")) >= 0) {
// Grab the specified region
string region = "#region " + file.Substring (anchorStart + 4);
file = file.Substring (0, anchorStart + 3);
try {
using (StreamReader reader = new StreamReader (file)) {
string line;
StringBuilder src = new StringBuilder ();
int indent = -1;
while ((line = reader.ReadLine ()) != null) {
if (line.Trim() == region) {
indent = line.IndexOf (region);
continue;
}
if (indent >= 0 && line.Trim().StartsWith ("#endregion")) {
break;