-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
1536 lines (1229 loc) · 59.2 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
namespace DocFXYAMLToMarkdown
{
class Program
{
/// <summary>
/// Formats a string so that it can safely appear in a table,
/// removing newlines and escaping HTML entities.
/// </summary>
/// <param name="input">The string to be formatted.</param>
/// <returns>The formatted string.</returns>
public static string FormatForTable(string input)
{
if (input == null)
{
return "";
}
return input.Replace('\n', ' ');
}
/// <summary>
/// Replaces XML-like cross references with a markdown link to the
/// appropriate <see cref="Item"/>'s page, if possible.
/// </summary>
/// <remarks>
/// This method does two things:
///
/// <![CDATA[
///
/// 1. It replaces the string `{{|` and `|}}` with `{{<` and `>}}`,
/// which are used by Hugo to indicate shortcodes.
///
/// ]]>
///
/// 2. It converts any `xref` element in the string, which is a
/// cross-reference to another <see cref="Item"/>, to an
/// appropriately formatted link to the <see cref="Item"/>.
/// </remarks>
/// <param name="input">The text to check for cross
/// references.</param>
/// <returns>The updated text, ready to be used in a markdown
/// document.</returns>
public static string FormatCrossReferences(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
input = input.Replace("{{|", "{{<");
input = input.Replace("|}}", ">}}");
input = System.Web.HttpUtility.HtmlDecode(input);
var selfClosedTagRegex = new Regex(@"<xref .*?href=""(.*?)"".*?></xref>", RegexOptions.Multiline);
return selfClosedTagRegex.Replace(input, m =>
{
var type = m.Groups[1].Value;
type = type.Replace("%2c", ",");
return LinkToType(type);
});
}
/// <summary>
/// The collection of types that we have seen in the code, and are
/// generating documentation for.
/// </summary>
internal static Dictionary<string, Item> Items { get; set; } = new Dictionary<string, Item>();
/// <summary>
/// The collection of types we have seen referred to in the code.
/// Not all of these types will have documentation available.
/// </summary>
/// <remarks>
/// This collection may include <see cref="Item"/>s that appear in
/// the <see cref="Items"/> collection.
/// </remarks>
internal static Dictionary<string, Item> References { get; set; } = new Dictionary<string, Item>();
/// <summary>
/// Maps ItemTypes to an English plural version of the name.
/// </summary>
public static readonly Dictionary<Item.ItemType, string> PluralItemTypes = new Dictionary<Item.ItemType, string>() {
{Item.ItemType.Namespace, "Namespaces"},
{Item.ItemType.Enum, "Enums"},
{Item.ItemType.Field, "Fields"},
{Item.ItemType.Method, "Methods"},
{Item.ItemType.Class, "Classes"},
{Item.ItemType.Struct, "Structs"},
{Item.ItemType.Constructor, "Constructors"},
{Item.ItemType.Property, "Properties"},
{Item.ItemType.Delegate, "Delegates"},
{Item.ItemType.Operator, "Operators"},
{Item.ItemType.Interface, "Interfaces"},
};
/// <summary>
/// Maps UIDs like "System.String" to C#-style identifiers like
/// "string"
/// </summary>
public static readonly Dictionary<string, string> BuiltInTypeMapping = new Dictionary<string, string> {
{"System.String", "string"},
{"System.Boolean", "bool"},
{"System.Single", "float"},
{"System.Double", "double"},
};
/// <summary>
/// Items with this type will appear in the menu. This is done to
/// prevent member methods, fields and properties from appearing in
/// the menu.
/// </summary>
public static readonly List<Item.ItemType> MenuEntryItemTypes = new List<Item.ItemType>() {
Item.ItemType.Namespace,
Item.ItemType.Class,
Item.ItemType.Struct,
Item.ItemType.Enum,
Item.ItemType.Interface,
Item.ItemType.Delegate,
};
/// <summary>
/// The collection of paths that this process has written to (so
/// that we can detect writing to the same place twice)
/// </summary>
static readonly HashSet<string> WrittenPaths = new HashSet<string>();
/// <summary>
/// Generates Markdown documentation from DocFX YAML metadata
/// files.
/// </summary>
/// <param name="inputDirectory">The directory containing
/// DocFX-generated YAML metadata.</param>
/// <param name="outputDirectory">The directory in which to create
/// Markdown documentation.</param>
/// <param name="overwriteFileDirectory">The directory containing
/// overwrite files, which can be used to add or replace content
/// found in the YAML metadata.</param>
public static void Main(DirectoryInfo inputDirectory, DirectoryInfo outputDirectory, DirectoryInfo overwriteFileDirectory = null)
{
foreach (var dir in new[] { inputDirectory, outputDirectory })
{
if (dir == null)
{
Console.WriteLine("Error: Both --input-directory and --output-directory must be specified.");
Environment.Exit(1);
return;
}
if (dir.Exists == false)
{
Console.WriteLine($"Error: {dir} is not a directory.");
Environment.Exit(1);
return;
}
}
IDeserializer deserializer = GetDeserializer();
// Read the TOC, which will direct us to the rest of the files
// that we care about
var tocPath = Path.Combine(inputDirectory.FullName, "toc.yml");
var document = File.ReadAllText(tocPath);
var input = new StringReader(document);
var tableOfContents = deserializer.Deserialize<List<TOCEntry>>(input);
// Read the YAML file for each entry in the table of contents.
foreach (var item in tableOfContents)
{
// Get the list of UIDs that we want to document.
IEnumerable<string> documentableUIDs =
item.Items.Select(i => i.UID) // UIDs of children
.Append(item.UID); // UID of this namespace
// Read the YAML file for each of these UIDs.
foreach (var childItemUID in documentableUIDs)
{
var fileName = childItemUID.Replace("`", "-");
var childItemPath = Path.Combine(inputDirectory.FullName, fileName + ".yml");
var childItemContents = File.ReadAllText(childItemPath);
var childItems = deserializer.Deserialize<ItemCollection>(childItemContents);
// Gather each of the types that is defined in this
// UID...
foreach (var childItem in childItems.Items)
{
Items[childItem.UID] = childItem;
}
// And each of the (possibly external to this source)
// types that is referred to in this UID.
foreach (var childItem in childItems.References)
{
References[childItem.UID] = childItem;
}
}
}
foreach (var item in Items.Values)
{
// Generate a short UID for each item
item.ShortUID = GenerateShortUID(item);
}
if (overwriteFileDirectory?.Exists ?? false)
{
// TODO: read the contents of the files in this directory
// and apply changes in it to the data that we're reading
foreach (var child in overwriteFileDirectory.GetFiles("*.md", SearchOption.AllDirectories))
{
Item overwriteItem = ParseOverwriteFile(child);
if (Items.ContainsKey(overwriteItem.UID) == false)
{
Console.WriteLine($"⚠️ WARNING: Overwrite item {child.FullName} overwrites item {overwriteItem.UID}, but no such item exists in the documentation");
continue;
}
var existingItem = Items[overwriteItem.UID];
existingItem.OverwriteStringPropertiesWithItem(overwriteItem);
}
}
int documentIndexNumber = 0;
// Generate the documentation for each item
foreach (var item in Items.Values.OrderBy(i => i.UID).Where(i => i.DoNotDocument == false))
{
string markdown;
documentIndexNumber += 1;
if (item.Type == Item.ItemType.Namespace)
{
markdown = GenerateMarkdownForNamespace(item, documentIndexNumber);
}
else
{
markdown = GenerateMarkdownForItem(item, documentIndexNumber);
}
string itemOutputPath;
if (item.Type != Item.ItemType.Namespace)
{
itemOutputPath = Path.Combine(outputDirectory.FullName, item.Namespace, PathForItem(item));
}
else
{
itemOutputPath = Path.Combine(outputDirectory.FullName, PathForItem(item));
}
var itemOutputDirectory = Path.GetDirectoryName(itemOutputPath);
if (string.IsNullOrEmpty(itemOutputDirectory) == false)
{
Directory.CreateDirectory(itemOutputDirectory);
}
File.WriteAllText(itemOutputPath, markdown);
Console.WriteLine($"📝 Writing {Path.GetRelativePath(outputDirectory.FullName, itemOutputPath)}");
CheckForWriteCollisions(itemOutputPath);
}
// Generate the index file, which links to all namespaces
var namespaces = Items.Values.Where(t => t.Type == Item.ItemType.Namespace);
var indexMarkdown = GenerateMarkdownForIndex(namespaces);
var indexOutputPath = Path.Combine(outputDirectory.FullName, "_index.md");
Console.WriteLine($"📝 Writing {Path.GetRelativePath(outputDirectory.FullName, indexOutputPath)}");
File.WriteAllText(indexOutputPath, indexMarkdown);
CheckForWriteCollisions(indexOutputPath);
}
private static IDeserializer GetDeserializer()
{
// Create our deserializer, which we'll configure to ignore any
// YAML fields that we don't have properties for.
return new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.IgnoreUnmatchedProperties()
.Build();
}
/// <summary>
/// Parses the overwrite file specified by <paramref
/// name="child"/>, and produces an <see cref="Item"/> that
/// contains fields that should be merged with another <see
/// cref="Item"/>.
/// </summary>
/// <param name="child">A <see cref="FileInfo"/> that represents an
/// overwrite file on disk.</param>
/// <returns>The parsed <see cref="Item"/>.</returns>
private static Item ParseOverwriteFile(FileInfo child)
{
var lines = new Queue<string>(File.ReadAllLines(child.FullName));
var yamlBuffer = new StringBuilder();
// Overwrite files are required to start with a YAML header
if (lines.Dequeue() != "---")
{
Console.WriteLine($"ERROR: Expected overwrite file {child.FullName} to start with '---'");
Environment.Exit(1);
}
// The DocFX Overwrite File Spec
// (https://dotnet.github.io/docfx/tutorial/intro_overwrite_files.html)
// specifies that the marker that indicates that content should
// come from the markdown in the document should be "*content",
// but this causes the YAML parser to fail because no such
// anchor exists in the document. As a workaround, we'll
// replace "*content" with this value instead.
const string contentAnchorPlaceholder = "__content__";
// Read lines until we hit the end of the header
while (lines.Peek() != "---")
{
try
{
string line = lines.Dequeue();
yamlBuffer.AppendLine(line.Replace("*content", contentAnchorPlaceholder));
}
catch (InvalidOperationException)
{
Console.WriteLine($"ERROR: Unexpected end of file in overwrite file {child.FullName}");
Environment.Exit(1);
}
}
// Remove the end of the header
lines.Dequeue();
// Scoop up the remainder into a new string variable
var markdown = string.Join("\n", lines);
// Parse the YAML we collected as an Item
var deserializer = GetDeserializer();
var item = deserializer.Deserialize<Item>(yamlBuffer.ToString());
if (string.IsNullOrWhiteSpace(item.UID))
{
Console.WriteLine($"ERROR: Overwrite file {child.FullName} does not specify a UID");
Environment.Exit(1);
}
// Overwrite any field of this Item that contains the anchor
// placeholder with our markdown
item.ApplyOverwriteMarkdown(markdown, contentAnchorPlaceholder);
// It's ready to go!
return item;
}
private static void CheckForWriteCollisions(string path)
{
if (WrittenPaths.Contains(path.ToLowerInvariant()))
{
Console.WriteLine($"ERROR: {path} has already been written to.");
Environment.Exit(1);
}
WrittenPaths.Add(path.ToLowerInvariant());
}
private static string GenerateShortUID(Item item)
{
// If the Overload for this item is unique, use that
if (Items.Values.Count(i => i.Overload == item.Overload) == 1)
{
return item.Overload.TrimEnd('*');
}
// It's not unqiue. Use the full UID instead.
return item.UID;
}
private static string LinkToType(string UID)
{
var isArray = UID.EndsWith("[]");
if (isArray)
{
UID = UID.Replace("[]", "");
}
var matchedItem = Items.Values.Where(i => i.UID == UID).FirstOrDefault();
if (matchedItem == null)
{
// We have have a reference to this instead
var matchedReference = References.Values.Where(i => i.UID == UID).FirstOrDefault();
// If the UID begins with System, link to Microsoft's .NET
// documentation.
//
// TODO: This doesn't work for UIDs that represent generic
// types, like Dictionary<T, U>.
if (UID.StartsWith("System."))
{
// trim parameters off, if any
var linkUID = Regex.Replace(UID, @"\(.*\)$", "");
var url = $"https://docs.microsoft.com/dotnet/api/{linkUID}";
// get the last part of the name for display
string displayElement;
if (BuiltInTypeMapping.ContainsKey(UID))
{
// If this is a built-in type, don't use the UID,
// because it isn't what the user is used to
// thinking in terms of - they type "string", not
// "System.String", and "float", not
// "System.Single". In these cases, perform a
// mapping.
displayElement = BuiltInTypeMapping[UID];
}
else
{
// Otherwise, use the last component of the UID (eg
// "System.Action" -> "Action")
displayElement = UID.Split(".").Last();
}
return $"[`{FormatForTable(displayElement)}{(isArray ? "[]" : "")}`]({url})";
}
// If the UID begins with "UnityEngine.UI", link to Unity
// UI's documentation
//
// Note that we link to their manual, not to their API
// docs, because the manual carries a lot more useful
// information. This may result in some of the links that
// this code generates not being valid.
//
// TODO: Verify links work by querying them and checking
// for an HTTP 2xx or 3xx status?
if (UID.StartsWith("UnityEngine.UI."))
{
// trim parameters off, if any
UID = Regex.Replace(UID, @"\(.*\)$", "");
// trim the first two part of the namespace off
// ("UnityEngine.UI")
var parts = UID.Split(".").Skip(2);
var docsID = string.Join(".", parts);
var url = $"https://docs.unity3d.com/Packages/[email protected]/manual/script-{docsID}.html";
// get the last part of the name for display
var displayElement = UID.Split(".").Last();
return $"[`{FormatForTable(displayElement)}{(isArray ? "[]" : "")}`]({url})";
}
// If the UID begins with "UnityEngine", link to Unity's
// documentation
if (UID.StartsWith("UnityEngine."))
{
// trim parameters off, if any
UID = Regex.Replace(UID, @"\(.*\)$", "");
// trim the first part of the namespace off
// ("UnityEngine")
var parts = UID.Split(".").Skip(1);
var docsID = string.Join(".", parts);
var url = $"https://docs.unity3d.com/ScriptReference/{docsID}.html";
// get the last part of the name for display
var displayElement = UID.Split(".").Last();
return $"[`{FormatForTable(displayElement)}{(isArray ? "[]" : "")}`]({url})";
}
// It's something else, and we don't have a link to it. The
// best we can do is render a slightly prettier version of
// the type (i.e. Dictionary<string,int> rather than
// System.Collections.Generic.Dictionary etc etc)
if (matchedReference != null)
{
return $"`{matchedReference.Name ?? matchedReference.UID}{(isArray ? "[]" : "")}`";
}
// No idea. Give up and just render the UID as-is.
return $"`{UID}{(isArray ? "[]" : "")}`";
}
else
{
// This Item came from the source code we're documenting,
// so we can link directly to our internal docs for this
// type.
return $"[`{FormatForTable(matchedItem.Name)}{(isArray ? "[]" : "")}`]({XRef(matchedItem)})";
}
}
private static string XRef(Item item)
{
string path = PathForItem(item);
return $"{{{{<ref \"/{Path.Combine("api", item.Namespace ?? "", path)}\">}}}}";
}
/// <summary>
/// Returns the path to the markdown file used for the Item,
/// relative to the output directory.
/// </summary>
/// <param name="item">The Item to get the path for.</param>
/// <returns>The path.</returns>
private static string PathForItem(Item item)
{
string path;
string caseIndex = GetCaseSensitivitySuffixForItem(item);
switch (item.Type)
{
case Item.ItemType.Namespace:
path = item.UID + caseIndex + "/_index.md";
break;
case Item.ItemType.Constructor:
case Item.ItemType.Field:
case Item.ItemType.Method:
case Item.ItemType.Operator:
case Item.ItemType.Property:
var parent = Items[item.Parent];
if (parent.Type == Item.ItemType.Namespace)
{
throw new InvalidOperationException($"Parent of item {item.UID} (a {item.Type}) is a namespace - this shouldn't be possible in C#? Bailing out because something more confusing is afoot here.");
}
var parentUIDWithoutNamespace = GetUIDWithoutNamespace(parent);
path = Path.Combine(parentUIDWithoutNamespace, item.ShortUID + caseIndex + ".md");
break;
default:
string UIDWithoutNamespace = GetUIDWithoutNamespace(item);
path = Path.Combine(UIDWithoutNamespace + caseIndex, "_index.md");
break;
}
path = path.Replace("#", "_");
path = path.Replace("`", "-");
return path;
}
/// <summary>
/// Returns a string that can be appended to the UID of an Item to
/// disambiguate Items that have the same UID as others when
/// case-insensitivity is needed (such as on case-insensitive
/// filesystems.)
/// </summary>
/// <remarks>
/// If UID is unique and has no other case-insensitive candidates
/// to disambiguate, this method returns the empty string.
/// </remarks>
/// <param name="item">The Item to compute a disambiguation suffix
/// to.</param>
/// <returns>A string that can be appended to the end of <paramref
/// name="item"/>'s UID which uniquely identifies it among other
/// UIDs that may be case-insensitively the same. </returns>
private static string GetCaseSensitivitySuffixForItem(Item item)
{
// There might exist multiple Items that have the same UID when
// compared case-insensitively. To handle this, we modify the
// UID in this way:
// 1. Build a collection of all (originally-cased) UIDs that
// are lowercase-identical to this one.
// 2. Sort this list lexicographically.
// 3. Determine the position of this UID in that list, as an
// integer.
// 4. Append this integer to the UID.
var caseCollisions = Items.Values
.Where(other => other.UID.ToLowerInvariant() == item.UID.ToLowerInvariant())
.OrderBy(i => i.UID)
.ToList();
if (caseCollisions.Count > 1)
{
return caseCollisions.IndexOf(item).ToString();
}
else
{
return String.Empty;
}
}
/// <summary>
/// Gets a modified version of <paramref name="item"/>'s UID, with
/// the namespace removed from the start.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private static string GetUIDWithoutNamespace(Item item)
{
string UIDWithoutNamespace = item.UID;
string namespacePrefix = item.Namespace + ".";
if (UIDWithoutNamespace.StartsWith(namespacePrefix))
{
UIDWithoutNamespace = UIDWithoutNamespace.Replace(namespacePrefix, "");
}
UIDWithoutNamespace = UIDWithoutNamespace.Replace("#", "_");
return UIDWithoutNamespace;
}
/// <summary>
/// Generates the Markdown for the index file for the
/// documentation.
/// </summary>
/// <param name="namespaces">A collection of <see cref="Item"/>
/// objects that represent the namespaces that should be
/// documented.</param>
/// <returns></returns>
private static string GenerateMarkdownForIndex(IEnumerable<Item> namespaces)
{
// generate links to all namespaces
StringBuilder stringBuilder = new StringBuilder();
// front-matter
stringBuilder.AppendLine($"---");
stringBuilder.AppendLine($"title: API Documentation");
stringBuilder.AppendLine($"draft: false");
stringBuilder.AppendLine($"toc: true");
stringBuilder.AppendLine($"hide_contents: true");
// This menu entry is the top-level API entry
stringBuilder.AppendLine($"menu: ");
stringBuilder.AppendLine($" docs:");
stringBuilder.AppendLine(@" identifier: ""api""");
stringBuilder.AppendLine($"---");
stringBuilder.AppendLine();
stringBuilder.AppendLine("{{% readfile \"/assets/api_landing.md\" %}}");
stringBuilder.AppendLine();
stringBuilder.AppendLine("|Namespace|Description|");
stringBuilder.AppendLine("|:---|:---|");
foreach (var @namespace in namespaces)
{
stringBuilder.Append("|");
stringBuilder.Append($"[{@namespace.ID}]({XRef(@namespace)})");
stringBuilder.Append("|");
stringBuilder.Append(@namespace.Summary);
stringBuilder.Append("|");
stringBuilder.AppendLine();
}
// Find all items without summaries, or with syntaxes with
// parameters or returns that have no description
var itemsWithoutSummaries = Items.Values
.Where(i => i.Type != Item.ItemType.Namespace)
.Where(
i =>
// The summary is empty
string.IsNullOrEmpty(i.Summary) ||
// It takes parameters, and at least one has no
// description
(i.Syntax?.Parameters.Any(p => string.IsNullOrEmpty(p.Description)) ?? false) ||
// It's a method, and its return is not documented
(i.Type == Item.ItemType.Method && i.Syntax?.Return != null &&
string.IsNullOrEmpty(i.Syntax?.Return?.Description))
).Distinct();
if (itemsWithoutSummaries.Count() > 0)
{
// Uncomment to generate a list of items that lack
// documentation
stringBuilder.AppendLine("## Items Needing Work");
foreach (var item in itemsWithoutSummaries)
{
stringBuilder.AppendLine($"* [`{item.NameWithType}`]({XRef(item)})");
}
}
return stringBuilder.ToString();
}
public static string GenerateMarkdownForNamespace(Item item, int documentIndexNumber)
{
StringBuilder stringBuilder = new StringBuilder();
// front-matter
stringBuilder.AppendLine($"---");
stringBuilder.AppendLine($"title: {item.Name} Namespace");
stringBuilder.AppendLine($"draft: false");
stringBuilder.AppendLine($"toc: true");
stringBuilder.AppendLine($"hide_contents: true");
// Build the menu item
stringBuilder.AppendLine($"menu:");
stringBuilder.AppendLine($" docs:");
// This menu entry is a child of the root API entry
stringBuilder.AppendLine(@" parent: ""api""");
stringBuilder.AppendLine($@" identifier: ""api.{item.UID + GetCaseSensitivitySuffixForItem(item)}""");
stringBuilder.AppendLine($@" title: ""{item.Name}""");
stringBuilder.AppendLine($@" weight: {documentIndexNumber}");
stringBuilder.AppendLine($"---");
var childItemGroups = item.Children
// Exclude inherited members
.Where(uid => item.InheritedMembers.Contains(uid) == false)
// Get full child item by UID
.Select(childUID => Items[childUID])
// Group by child item's type
.GroupBy(i => i.Type);
stringBuilder.AppendLine(item.Summary);
foreach (var group in childItemGroups)
{
stringBuilder.AppendLine($"## {PluralItemTypes[group.Key]}");
stringBuilder.AppendLine($"|Name|Description|");
stringBuilder.AppendLine("|:---|:---|");
foreach (var childItem in group)
{
stringBuilder.Append("|");
stringBuilder.Append($"[{FormatForTable(childItem.Name)}]");
stringBuilder.Append($"({XRef(childItem)})");
stringBuilder.Append("|");
stringBuilder.Append($"{FormatForTable(FormatCrossReferences(childItem.Summary))}");
stringBuilder.Append("|");
stringBuilder.AppendLine();
}
}
return stringBuilder.ToString();
}
public static string GenerateMarkdownForItem(Item item, int documentIndexNumber)
{
StringBuilder stringBuilder = new StringBuilder();
var contentDate = item.Source?.Remote?.Commit?.Author?.Date ?? DateTime.UtcNow;
// front-matter
stringBuilder.AppendLine($"---");
stringBuilder.AppendLine($"title: {item.DisplayName} {item.Type}");
stringBuilder.AppendLine($"draft: false");
stringBuilder.AppendLine($"toc: true");
stringBuilder.AppendLine($"hide_contents: true");
stringBuilder.AppendLine($"menu:");
stringBuilder.AppendLine($" docs:");
stringBuilder.AppendLine($" identifier: \"api.{item.UID + GetCaseSensitivitySuffixForItem(item)}\"");
stringBuilder.AppendLine($" parent: \"api.{item.Parent + GetCaseSensitivitySuffixForItem(Items[item.Parent])}\"");
stringBuilder.AppendLine($" title: \"{item.Name}\"");
stringBuilder.AppendLine($" weight: {documentIndexNumber}");
stringBuilder.AppendLine($"---");
// Generate the class metadata, which appears at the top of the
// page in custom formatting
stringBuilder.AppendLine(@"<div class=""class-metadata"">");
stringBuilder.AppendLine();
var metadata = new List<string>();
// Link to the parent if that's not a namespace
if (item.Parent != null && Items.ContainsKey(item.Parent) && Items[item.Parent].Type != Item.ItemType.Namespace)
{
metadata.Add($"Parent: {LinkToType(item.Parent)}");
}
// Show namespace info
metadata.Add($"Namespace: {LinkToType(item.Namespace)}");
var assemblyList = string.Join(", ", item.Assemblies.Select(s => s + ".dll"));
// Show assembly info
metadata.Add($"Assembly: {assemblyList}");
// Output this as a single comma-separated line
stringBuilder.AppendLine(string.Join(", ", metadata));
stringBuilder.AppendLine("</div>");
stringBuilder.AppendLine();
// Now for the body of the documentation:
// Is this item marked as [Obsolete] in the source?
var obsoleteMessage = item.Attributes.Where(a => a.Type == "System.ObsoleteAttribute")
.Select(a => a.Arguments.FirstOrDefault()?.Value)
.FirstOrDefault();
// Then add a note explaining it.
if (obsoleteMessage != null)
{
stringBuilder.AppendLine("{{<note>}}");
stringBuilder.AppendLine($"This {item.Type.ToString().ToLowerInvariant()} is **obsolete** and may be removed from a future version of Yarn Spinner. {obsoleteMessage}");
stringBuilder.AppendLine("{{</note>}}");
stringBuilder.AppendLine();
}
// Show the summary
stringBuilder.AppendLine(FormatCrossReferences(item.Summary));
stringBuilder.AppendLine();
// Show the source code for the attached Syntax
if (item.Syntax != null)
{
stringBuilder.AppendLine("```csharp");
stringBuilder.AppendLine(item.Syntax.Content);
stringBuilder.AppendLine("```");
}
// Generate the remarks, if present
if (item.Remarks != null)
{
stringBuilder.AppendLine("## Remarks");
stringBuilder.AppendLine(FormatCrossReferences(item.Remarks));
}
// Generate the examples, if present
if (item.Example.Count > 0)
{
stringBuilder.AppendLine($"## Example{(item.Example.Count == 1 ? "" : "s")}");
foreach (var example in item.Example)
{
stringBuilder.AppendLine(FormatCrossReferences(example));
stringBuilder.AppendLine();
}
}
// Generate the explanation for the syntax (parameters, return
// type, etc)
if (item.Syntax != null)
{
stringBuilder.AppendLine();
GenerateMarkdownForSyntax(item, item.Syntax, stringBuilder, 2);
}
stringBuilder.AppendLine();
// Generate documentation for child items (methods, fields,
// properties, etc)
if (item.Children != null)
{
var childItemGroups = item.Children
// // Exclude inherited members .Where(uid =>
// item.InheritedMembers.Contains(uid) == false) Get
// full child item by UID
.Select(childUID => Items[childUID])
// Group by child item's type
.GroupBy(i => i.Type);
foreach (var group in childItemGroups)
{
stringBuilder.AppendLine($"## {PluralItemTypes[group.Key]}");
stringBuilder.AppendLine("|Name|Description|");
stringBuilder.AppendLine("|:---|:---|");
foreach (var childItem in group)
{
stringBuilder.Append($"|");
stringBuilder.Append($"[{FormatForTable(childItem.Name)}]");
stringBuilder.Append($"({XRef(childItem)})");
stringBuilder.Append($"|");
var isObsolete = childItem.Attributes.Any(a => a.Type == "System.ObsoleteAttribute");
if (isObsolete)
{
stringBuilder.Append("*Obsolete*");
if (string.IsNullOrEmpty(childItem.Summary) == false)
{
stringBuilder.Append(": ");
}
}
stringBuilder.Append($"{FormatForTable(FormatCrossReferences(childItem.Summary))}");
stringBuilder.Append($"|");
stringBuilder.AppendLine();
}
}
}
// Generate documentation for the exceptions
if (item.Exceptions.Count > 0)
{
stringBuilder.AppendLine("## Exceptions");
stringBuilder.AppendLine("|Exception|Description|");
stringBuilder.AppendLine("|:---|:---|");
foreach (var exception in item.Exceptions)
{
stringBuilder.Append("|");
stringBuilder.Append($"{LinkToType(exception.Type)}");
stringBuilder.Append("|");
if (string.IsNullOrEmpty(exception.Description) == false)
{
stringBuilder.AppendLine($"{FormatForTable(FormatCrossReferences(exception.Description))}");
}
stringBuilder.Append("|");
stringBuilder.AppendLine();
};
}
// Build the list of see-also entries, from the
// manually-authored <seealso> tags, the parent type, the list
// of parameters this item may take, and the return type.
// Filter out external types from System and UnityEngine, and
// namespaces.
var seeAlsoIDs = item.SeeAlso?.Select(s => s.LinkID);
// If this is a field or property, we want to add 'see-also'
// references to the parameters and return type.
if (item.Syntax != null &&
new[] { Item.ItemType.Property, Item.ItemType.Field }.Contains(item.Type))
{
// Start with the manually authored see-also references
seeAlsoIDs = seeAlsoIDs
// Add the types of this item's parameters
.Concat(item.Syntax.Parameters?.Select(p => p.Type)
// Add the return type of this item
.Append(item.Syntax.Return?.Type)
// Remove any nulls
.Where(i => i != null)
// Only include items where we know about the type
// (i.e. it has been defined in this source code)
.Where(i => Items.ContainsKey(i))
// Ensure that any times are not a namespace
.Where(i => Items[i].Type != Item.ItemType.Namespace)
// Ensure they are not a System or UnityEngine type
.Where(i => i.StartsWith("System.") == false)
.Where(i => i.StartsWith("UnityEngine.") == false)
)
// Remove duplicates
.Distinct();
}