-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathMDocUpdater.cs
More file actions
4559 lines (3988 loc) · 196 KB
/
MDocUpdater.cs
File metadata and controls
4559 lines (3988 loc) · 196 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Mono.Cecil;
using Mono.Documentation.Updater;
using Mono.Documentation.Updater.Formatters;
using Mono.Documentation.Updater.Frameworks;
using Mono.Documentation.Updater.Statistics;
using Mono.Documentation.Util;
using Mono.Options;
using SchwabenCode.QuickIO;
using MyXmlNodeList = System.Collections.Generic.List<System.Xml.XmlNode>;
using StringList = System.Collections.Generic.List<string>;
using StringToXmlNodeMap = System.Collections.Generic.Dictionary<string, System.Xml.XmlNode>;
namespace Mono.Documentation
{
public partial class MDocUpdater : MDocCommand
{
string srcPath;
List<AssemblySet> assemblies = new List<AssemblySet> ();
StringList globalSearchPaths = new StringList ();
string apistyle = string.Empty;
bool isClassicRun;
bool verbose;
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 MemberFormatter docTypeFormatterField;
static MemberFormatter filenameFormatterField;
static MemberFormatter docTypeFormatter
{
get
{
if (docTypeFormatterField == null)
docTypeFormatterField = new DocTypeMemberFormatter(MDocUpdater.Instance.TypeMap);
return docTypeFormatterField;
}
}
static MemberFormatter filenameFormatter
{
get
{
if (filenameFormatterField == null)
filenameFormatterField = new FileNameMemberFormatter(MDocUpdater.Instance.TypeMap);
return filenameFormatterField;
}
}
private readonly List<string> CustomAttributeNamesToSkip = new List<string>()
{
Consts.CompilerGeneratedAttribute,
"System.Runtime.InteropServices.TypeIdentifierAttribute"
};
internal static MemberFormatter csharpSlashdocFormatterField;
internal static MemberFormatter csharpSlashdocFormatter
{
get
{
if (csharpSlashdocFormatterField == null)
csharpSlashdocFormatterField = new SlashDocCSharpMemberFormatter(MDocUpdater.Instance.TypeMap);
return csharpSlashdocFormatterField;
}
}
internal static MemberFormatter msxdocxSlashdocFormatterField;
internal static MemberFormatter msxdocxSlashdocFormatter
{
get
{
if (msxdocxSlashdocFormatterField == null)
msxdocxSlashdocFormatterField = new MsxdocSlashDocMemberFormatter(MDocUpdater.Instance.TypeMap);
return msxdocxSlashdocFormatterField;
}
}
MyXmlNodeList extensionMethods = new MyXmlNodeList ();
public static string droppedNamespace = string.Empty;
private HashSet<string> memberSet;
public static bool HasDroppedNamespace (TypeDefinition forType)
{
return HasDroppedNamespace (forType.Module);
}
public static bool HasDroppedNamespace (MemberReference forMember)
{
return HasDroppedNamespace (forMember.Module);
}
public static bool HasDroppedNamespace (AssemblyDefinition forAssembly)
{
return HasDroppedNamespace (forAssembly.MainModule);
}
public static bool HasDroppedNamespace (ModuleDefinition forModule)
{
return HasDroppedNamespace (forModule?.Assembly?.Name);
}
public static bool HasDroppedNamespace (AssemblyNameReference assemblyRef)
{
return assemblyRef != null && !string.IsNullOrWhiteSpace (droppedNamespace) && droppedAssemblies.Any (da => Path.GetFileNameWithoutExtension(da) == assemblyRef.Name);
}
public static bool HasDroppedAnyNamespace ()
{
return !string.IsNullOrWhiteSpace (droppedNamespace);
}
/// <summary>Logic flag to signify that we should list assemblies at the method level, since there are multiple
/// assemblies for a given type/method.</summary>
public bool IsMultiAssembly
{
get
{
return apistyle == "classic" || apistyle == "unified" || !string.IsNullOrWhiteSpace (FrameworksPath);
}
}
bool writeIndex = true;
/// <summary>Path which contains multiple folders with assemblies. Each folder contained will represent one framework.</summary>
string FrameworksPath = string.Empty;
FrameworkIndex frameworks;
FrameworkIndex frameworksCache;
IEnumerable<XDocument> oldFrameworkXmls;
/// <summary>For unit tests to initialize the cache</summary>
public void InitializeFrameworksCache (FrameworkIndex fi) => frameworksCache = fi;
private StatisticsCollector statisticsCollector = new StatisticsCollector();
static List<string> droppedAssemblies = new List<string> ();
public string PreserveTag { get; set; }
public bool DisableSearchDirectoryRecurse = false;
private bool statisticsEnabled = false;
private string statisticsFilePath;
private static MDocUpdater instanceField;
public static MDocUpdater Instance
{
get
{
if (instanceField == null)
instanceField = new MDocUpdater();
return instanceField;
}
private set => instanceField = value;
}
public static bool SwitchingToMagicTypes { get; private set; }
public TypeMap TypeMap { get; private set; }
public override void Run (IEnumerable<string> args)
{
Console.WriteLine ("mdoc {0}", Consts.MonoVersion);
Instance = this;
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 => globalSearchPaths.Add (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 => globalSearchPaths.Add (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) },
{ "dropns=",
"When processing assembly {ASSEMBLY}, strip off leading namespace {PREFIX}:\n" +
" e.g. --dropns ASSEMBLY=PREFIX",
v => {
var parts = v.Split ('=');
if (parts.Length != 2) { Console.Error.WriteLine ("Invalid dropns input"); return; }
var assembly = Path.GetFileName (parts [0].Trim ());
var prefix = parts [1].Trim();
droppedAssemblies.Add (assembly);
droppedNamespace = prefix;
} },
{ "ntypes",
"If the new assembly is switching to 'magic types', then this switch should be defined.",
v => SwitchingToMagicTypes = true },
{ "preserve",
"Do not delete members that don't exist in the assembly, but rather mark them as preserved.",
v => PreserveTag = "true" },
{ "api-style=",
"Denotes the apistyle. Currently, only `classic` and `unified` are supported. `classic` set of assemblies should be run first, immediately followed by 'unified' assemblies with the `dropns` parameter.",
v => apistyle = v.ToLowerInvariant () },
{ "fx|frameworks=",
"Configuration XML file, that points to directories which contain libraries that span multiple frameworks.",
v => FrameworksPath = v },
{ "use-docid",
"Add 'DocId' to the list of type and member signatures",
v =>
{
FormatterManager.AddFormatter(Consts.DocId);
} },
{ "lang=",
"Add languages to the list of type and member signatures (DocId, VB.NET). Values can be coma separated",
v =>
{
FormatterManager.AddFormatter(v);
} },
{ "disable-searchdir-recurse",
"Default behavior for adding search directories ('-L') is to recurse them and search in all subdirectories. This disables that",
v => DisableSearchDirectoryRecurse = true },
{
"statistics=",
"Save statistics to the specified file",
v =>
{
statisticsEnabled = true;
if (!string.IsNullOrEmpty(v))
statisticsFilePath = v;
} },
{ "verbose",
"Adds extra output to the log",
v => verbose = true },
{ "index=",
"Lets you choose to disable index.xml (true by default)",
v => bool.TryParse(v, out writeIndex) },
{ "nocollapseinterfaces",
"All interfaces listed in type signatures",
v => Consts.CollapseInheritedInterfaces = false },
};
var assemblyPaths = Parse (p, args, "update",
"[OPTIONS]+ ASSEMBLIES",
"Create or update documentation from ASSEMBLIES.");
int fxCount = 1;
if (!string.IsNullOrWhiteSpace (FrameworksPath))
{
var configPath = FrameworksPath;
var frameworksDir = FrameworksPath;
if (!configPath.EndsWith ("frameworks.xml", StringComparison.InvariantCultureIgnoreCase))
configPath = Path.Combine (configPath, "frameworks.xml");
else
frameworksDir = Path.GetDirectoryName (configPath);
// check for typemap file
string typeMapPath = Path.Combine(frameworksDir, "TypeMap.xml");
if (File.Exists(typeMapPath))
{
Console.WriteLine($"Loading typemap file at {typeMapPath}");
if (!Directory.Exists(srcPath))
Directory.CreateDirectory(srcPath);
File.Copy(typeMapPath, Path.Combine(srcPath, "TypeMap.xml"), true);
TypeMap map = TypeMap.FromXml(typeMapPath);
this.TypeMap = map;
FormatterManager.UpdateTypeMap(map);
}
Console.WriteLine($"Opening frameworks file '{configPath}'");
var fxconfig = XDocument.Load (configPath);
var fxd = fxconfig.Root
.Elements ("Framework")
.Select (f => new
{
Name = f.Attribute ("Name").Value,
Path = Path.Combine (frameworksDir, f.Attribute ("Source").Value),
SearchPaths = f.Elements ("assemblySearchPath")
.Select (a => Path.Combine (frameworksDir, a.Value))
.ToArray (),
Imports = f.Elements ("import")
.Select (a => Path.Combine (frameworksDir, a.Value))
.ToArray (),
Version = f.Elements("package")
?.FirstOrDefault()?.Attribute("Version")?.Value,
Id = f.Elements("package")
?.FirstOrDefault()?.Attribute("Id")?.Value
})
.Where (f => Directory.Exists (f.Path))
.ToArray();
fxCount = fxd.Count ();
oldFrameworkXmls = fxconfig.Root
.Elements("Framework")
.Select(f => new
{
Name = f.Attribute("Name").Value,
Source = f.Attribute("Source").Value,
XmlPath = Path.Combine(srcPath, Consts.FrameworksIndex, f.Attribute("Source").Value + ".xml"),
})
.Where(f => File.Exists(f.XmlPath))
.Select(f => XDocument.Load(f.XmlPath));
Func<string, string, IEnumerable<string>> getFiles = (string path, string filters) =>
{
var assemblyFiles = filters.Split('|').SelectMany(v => Directory.GetFiles(path, v));
// Directory.GetFiles method returned file names is not sort,
// this makes the order of the assembly elements of our generated XML files is inconsistent in different environments,
// so we need to sort it.
return new SortedSet<string>(assemblyFiles);
};
var sets = fxd.Select (d => new AssemblySet (
d.Name,
getFiles (d.Path, "*.dll|*.exe|*.winmd"),
d.SearchPaths.Union(this.globalSearchPaths),
d.Imports,
d.Version,
d.Id
));
this.assemblies.AddRange (sets);
assemblyPaths.AddRange (sets.SelectMany (s => s.AssemblyPaths));
Console.WriteLine($"Frameworks Configuration contains {assemblyPaths.Count} assemblies");
if (!DisableSearchDirectoryRecurse)
{
// unless it's been explicitly disabled, let's
// add all of the subdirectories to the resolver
// search paths.
foreach (var assemblySet in this.assemblies)
assemblySet.RecurseSearchDirectories();
}
// Create a cache of all frameworks, so we can look up
// members that may exist only other frameworks before deleting them
Console.Write ("Creating frameworks cache: ");
FrameworkIndex cacheIndex = new FrameworkIndex (FrameworksPath, fxCount, cachedfx:null);
foreach (var assemblySet in this.assemblies)
{
using (assemblySet)
{
foreach (var assembly in assemblySet.Assemblies)
{
Console.WriteLine($"Caching {assembly.MainModule.FileName}");
try
{
var a = cacheIndex.StartProcessingAssembly(assemblySet, assembly, assemblySet.Importers, assemblySet.Id, assemblySet.Version);
foreach (var type in assembly.GetTypes().Where(t => DocUtils.IsPublic(t)))
{
var t = a.ProcessType(type, assembly);
foreach (var member in type.GetMembers().Where(i => !DocUtils.IsIgnored(i) && IsMemberNotPrivateEII(i)))
t.ProcessMember(member);
}
}
catch(Exception ex)
{
throw new MDocAssemblyException(assembly.FullName, $"Error caching {assembly.FullName} from {assembly.MainModule.FileName}", ex);
}
}
}
}
Console.WriteLine ($"{Environment.NewLine}done caching.");
this.frameworksCache = cacheIndex;
}
else
{
this.assemblies.Add (new AssemblySet ("Default", assemblyPaths, this.globalSearchPaths));
}
if (assemblyPaths == null)
return;
if (assemblyPaths.Count == 0)
Error ("No assemblies specified.");
// validation for the api-style parameter
if (apistyle == "classic")
isClassicRun = true;
else if (apistyle == "unified")
{
if (!droppedAssemblies.Any ())
Error ("api-style 'unified' must also supply the 'dropns' parameter with at least one assembly and dropped namespace.");
}
else if (!string.IsNullOrWhiteSpace (apistyle))
Error ("api-style '{0}' is not currently supported", apistyle);
// PARSE BASIC OPTIONS AND LOAD THE ASSEMBLY TO DOCUMENT
if (srcPath == null)
throw new InvalidOperationException ("The --out option is required.");
docEnum = docEnum ?? new DocumentationEnumerator ();
// PERFORM THE UPDATES
frameworks = new FrameworkIndex (FrameworksPath, fxCount, cachedfx: this.frameworksCache?.Frameworks);
if (types.Count > 0)
{
types.Sort ();
DoUpdateTypes (srcPath, types, srcPath);
}
else
DoUpdateAssemblies (srcPath, srcPath);
if (!string.IsNullOrWhiteSpace (FrameworksPath))
frameworks.WriteToDisk (srcPath);
if (statisticsEnabled)
{
try
{
StatisticsSaver.Save(statisticsCollector, statisticsFilePath);
}
catch (Exception exception)
{
Warning($"Unable to save statistics file: {exception.Message}");
}
}
Console.WriteLine ("Members Added: {0}, Members Deleted: {1}", additions, deletions);
}
public static bool IsInAssemblies (string name)
{
return Instance?.assemblies != null ? Instance.assemblies.Any (a => a.Contains (name)) : true;
}
void AddImporter (string path)
{
var importer = GetImporter (path, supportsEcmaDoc: true);
if (importer != null)
importers.Add (importer);
}
internal DocumentationImporter GetImporter (string path, bool supportsEcmaDoc)
{
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")
{
return new MsxdocDocumentationImporter (path);
}
else if (r.LocalName == "Libraries")
{
if (!supportsEcmaDoc)
throw new NotSupportedException ($"Ecma documentation not supported in this mode: {path}");
var ecmadocs = new XmlTextReader (path);
docEnum = new EcmaDocumentationEnumerator (this, ecmadocs);
return 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);
}
return null;
}
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);
}
internal AssemblyDefinition LoadAssembly (string name, IMetadataResolver resolver, IAssemblyResolver assemblyResolver)
{
AssemblyDefinition assembly = null;
try
{
assembly = AssemblyDefinition.ReadAssembly (name, new ReaderParameters { AssemblyResolver = assemblyResolver, MetadataResolver = resolver });
}
catch (Exception ex)
{
Warning ($"Unable to load assembly '{name}': {ex.Message}");
}
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;
if (c[n.Name] != null)
{
c.RemoveNamedItem (n.Name);
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);
var nsDocPath = DocUtils.PathCombine(outdir, $"ns-{ns}.xml");
WriteFile (nsDocPath, 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 (var assemblySet in this.assemblies)
{
using (assemblySet)
{
foreach (AssemblyDefinition assembly in assemblySet.Assemblies)
{
using (assembly)
{
try
{
var typeSet = new HashSet<string>();
var namespacesSet = new HashSet<string>();
memberSet = new HashSet<string>();
var frameworkEntry = frameworks.StartProcessingAssembly(assemblySet, assembly, assemblySet.Importers, assemblySet.Id, assemblySet.Version);
assemblySet.Framework = frameworkEntry;
foreach (TypeDefinition type in docEnum.GetDocumentationTypes(assembly, typenames))
{
var typeEntry = frameworkEntry.ProcessType(type, assembly);
string relpath = DoUpdateType(assemblySet, assembly, type, typeEntry, basepath, dest);
if (relpath == null)
continue;
found.Add(type.FullName);
if (index == null)
continue;
index.Add(assemblySet, assembly);
index.Add(type);
namespacesSet.Add(type.Namespace);
typeSet.Add(type.FullName);
}
statisticsCollector.AddMetric(frameworkEntry.Name, StatisticsItem.Types, StatisticsMetrics.Total, typeSet.Count);
statisticsCollector.AddMetric(frameworkEntry.Name, StatisticsItem.Namespaces, StatisticsMetrics.Total, namespacesSet.Count);
statisticsCollector.AddMetric(frameworkEntry.Name, StatisticsItem.Members, StatisticsMetrics.Total, memberSet.Count);
}
catch (Exception ex)
{
throw new MDocAssemblyException(assembly.FullName, $"Error processing {assembly.FullName} from {assembly.MainModule.FileName}", ex);
}
}
}
}
}
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 (AssemblySet set, AssemblyDefinition assembly)
{
if (index_assemblies.SelectSingleNode ("Assembly[@Name='" + assembly.Name.Name + "']") != null)
return;
app.AddIndexAssembly (assembly, index_assemblies, set.Framework);
}
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 ());
}
/// <summary>Constructs the presumed path to the type's documentation file</summary>
/// <returns><c>true</c>, if the type file was found, <c>false</c> otherwise.</returns>
/// <param name="result">A typle that contains 1) the 'reltypefile', 2) the 'typefile', and 3) the file info</param>
bool TryFindTypeFile (string nsname, string typename, string basepath, out Tuple<string, string, FileInfo> result)
{
string reltypefile = DocUtils.PathCombine (nsname, typename + ".xml");
string typefile = Path.Combine (basepath, reltypefile);
System.IO.FileInfo file = new System.IO.FileInfo (typefile);
result = new Tuple<string, string, FileInfo> (reltypefile, typefile, file);
return file.Exists;
}
public string DoUpdateType (AssemblySet set, AssemblyDefinition assembly, TypeDefinition type, FrameworkTypeEntry typeEntry, 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 (!DocUtils.IsPublic (type))
return null;
if (type.HasCustomAttributes && CustomAttributeNamesToSkip.All(x => type.CustomAttributes.Any(y => y.AttributeType.FullName == x)))
{
Console.WriteLine(string.Format("Embedded Type: {0}. Skip it.", type.FullName));
return null;
}
// Must get the A+B form of the type name.
string typename = GetTypeFileName (type);
string nsname = DocUtils.GetNamespace (type);
// Find the file, if it exists
string[] searchLocations = new string[] {
nsname
};
if (MDocUpdater.HasDroppedNamespace (type))
{
// If dropping namespace, types may have moved into a couple of different places.
var newSearchLocations = searchLocations.Union (new string[] {
string.Format ("{0}.{1}", droppedNamespace, nsname),
nsname.Replace (droppedNamespace + ".", string.Empty),
MDocUpdater.droppedNamespace
});
searchLocations = newSearchLocations.ToArray ();
}
string reltypefile = "", typefile = "";
System.IO.FileInfo file = null;
foreach (var f in searchLocations)
{
Tuple<string, string, FileInfo> result;
bool fileExists = TryFindTypeFile (f, typename, basepath, out result);
if (fileExists)
{
reltypefile = result.Item1;
typefile = result.Item2;
file = result.Item3;
break;
}
}
if (file == null || !file.Exists)
{
// we were not able to find a file, let's use the original type informatio.
// so that we create the stub in the right place.
Tuple<string, string, FileInfo> result;
TryFindTypeFile (nsname, typename, basepath, out result);
reltypefile = result.Item1;
typefile = result.Item2;
file = result.Item3;
}
string output = null;
if (dest == null)
{
output = typefile;
}
else if (dest == "-")
{
output = null;
}
else
{
output = Path.Combine (dest, reltypefile);
}
if (file != null && 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, typeEntry, output, false);
}
else
{
// Stub
XmlElement td = StubType (set, assembly, type, typeEntry, output, typeEntry.Framework.Importers, typeEntry.Framework.Id, typeEntry.Framework.Version);
if (td == null)
return null;
}
return reltypefile;
}
private static string GetTypeFileName (TypeReference type)
{
return filenameFormatter.GetName (type, useTypeProjection: false);
}
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, FrameworkEntry fx)
{
XmlElement index_assembly = null;
if (IsMultiAssembly)
index_assembly = (XmlElement)parent.SelectSingleNode ("Assembly[@Name='" + assembly.Name.Name + "']");
if (index_assembly == null)
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 = WriteElement (index_assembly, "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);
}