Skip to content

Commit

Permalink
refactor: strongly type plantuml config
Browse files Browse the repository at this point in the history
  • Loading branch information
yufeih committed Jan 3, 2024
1 parent 0cfc17f commit 0d56f79
Show file tree
Hide file tree
Showing 12 changed files with 133 additions and 178 deletions.
16 changes: 1 addition & 15 deletions src/Docfx.MarkdigEngine.Extensions/MarkdownContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,6 @@ public class MarkdownContext
/// <returns>Image url bound to the path</returns>
public delegate string GetImageLinkDelegate(string path, MarkdownObject origin, string altText);

/// <summary>
/// Allows configuration of extensions
/// </summary>
/// <param name="extension">Name of the extension being configured</param>
/// <returns>Object representing the configuration for the extension</returns>
public delegate object GetExtensionConfigurationDelegate(string extension);

/// <summary>
/// Reads a file as text.
/// </summary>
Expand All @@ -58,11 +51,6 @@ public class MarkdownContext
/// </summary>
public GetImageLinkDelegate GetImageLink { get; }

/// <summary>
/// Get the configuration for a given extension
/// </summary>
public GetExtensionConfigurationDelegate GetExtensionConfiguration { get; }

/// <summary>
/// Log info
/// </summary>
Expand Down Expand Up @@ -98,14 +86,12 @@ public MarkdownContext(
LogActionDelegate logError = null,
ReadFileDelegate readFile = null,
GetLinkDelegate getLink = null,
GetImageLinkDelegate getImageLink = null,
GetExtensionConfigurationDelegate getConfig = null)
GetImageLinkDelegate getImageLink = null)
{
_getToken = getToken ?? (_ => null);
ReadFile = readFile ?? ((a, b) => (a, a));
GetLink = getLink ?? ((a, b) => a);
GetImageLink = getImageLink ?? ((a, b, c) => a);
GetExtensionConfiguration = getConfig ?? (_ => null);
LogInfo = logInfo ?? ((a, b, c, d) => { });
LogSuggestion = logSuggestion ?? ((a, b, c, d) => { });
LogWarning = logWarning ?? ((a, b, c, d) => { });
Expand Down
16 changes: 9 additions & 7 deletions src/Docfx.MarkdigEngine.Extensions/MarkdownExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ namespace Docfx.MarkdigEngine.Extensions;

public static class MarkdownExtensions
{
public static MarkdownPipelineBuilder UseDocfxExtensions(this MarkdownPipelineBuilder pipeline, MarkdownContext context)
public static MarkdownPipelineBuilder UseDocfxExtensions(
this MarkdownPipelineBuilder pipeline, MarkdownContext context,
Dictionary<string, string> notes = null, PlantUmlOptions plantUml = null)
{
return pipeline
.UseMathematics()
Expand All @@ -24,7 +26,7 @@ public static MarkdownPipelineBuilder UseDocfxExtensions(this MarkdownPipelineBu
.UseIncludeFile(context)
.UseCodeSnippet(context)
.UseDFMCodeInfoPrefix()
.UseQuoteSectionNote(context)
.UseQuoteSectionNote(context, notes)
.UseXref()
.UseEmojiAndSmiley(false)
.UseTabGroup(context)
Expand All @@ -35,7 +37,7 @@ public static MarkdownPipelineBuilder UseDocfxExtensions(this MarkdownPipelineBu
.UseTripleColon(context)
.UseNoloc()
.UseResolveLink(context)
.UsePlantUml(context)
.UsePlantUml(context, plantUml)
.RemoveUnusedExtensions();
}

Expand Down Expand Up @@ -100,9 +102,9 @@ public static MarkdownPipelineBuilder UseDFMCodeInfoPrefix(this MarkdownPipeline
return pipeline;
}

public static MarkdownPipelineBuilder UseQuoteSectionNote(this MarkdownPipelineBuilder pipeline, MarkdownContext context)
public static MarkdownPipelineBuilder UseQuoteSectionNote(this MarkdownPipelineBuilder pipeline, MarkdownContext context, Dictionary<string, string> notes = null)
{
pipeline.Extensions.AddIfNotAlready(new QuoteSectionNoteExtension(context));
pipeline.Extensions.AddIfNotAlready(new QuoteSectionNoteExtension(context, notes));
return pipeline;
}

Expand All @@ -112,9 +114,9 @@ public static MarkdownPipelineBuilder UseLineNumber(this MarkdownPipelineBuilder
return pipeline;
}

public static MarkdownPipelineBuilder UsePlantUml(this MarkdownPipelineBuilder pipeline, MarkdownContext context)
public static MarkdownPipelineBuilder UsePlantUml(this MarkdownPipelineBuilder pipeline, MarkdownContext context, PlantUmlOptions options = null)
{
pipeline.Extensions.AddIfNotAlready(new PlantUmlExtension(context));
pipeline.Extensions.AddIfNotAlready(new PlantUmlExtension(context, options));
return pipeline;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,31 @@ namespace Docfx.MarkdigEngine.Extensions;
/// An HTML renderer for a <see cref="CodeBlock"/> and <see cref="FencedCodeBlock"/>.
/// </summary>
/// <seealso cref="HtmlObjectRenderer{CodeBlock}" />
public class CustomCodeBlockRenderer : CodeBlockRenderer
class PlantUmlCodeBlockRenderer : CodeBlockRenderer
{
private readonly MarkdownContext _context;
private readonly DocfxPlantUmlSettings _settings;
private readonly PlantUmlSettings _settings;
private readonly OutputFormat _outputFormat;
private readonly RendererFactory rendererFactory;

/// <summary>
/// Initializes a new instance of the <see cref="CodeBlockRenderer"/> class.
/// </summary>
/// <param name="context"></param>
/// <param name="settings"></param>
public CustomCodeBlockRenderer(MarkdownContext context, DocfxPlantUmlSettings settings)
public PlantUmlCodeBlockRenderer(MarkdownContext context, PlantUmlOptions settings)
{
_context = context;
_settings = settings;
_settings = new()
{
Delimitor = settings.Delimitor,
RenderingMode = settings.RenderingMode,
RemoteUrl = settings.RemoteUrl,
JavaPath = settings.JavaPath,
LocalGraphvizDotPath = settings.LocalGraphvizDotPath,
LocalPlantUmlPath = settings.LocalPlantUmlPath,
};
_outputFormat = settings.OutputFormat;

rendererFactory = new RendererFactory();
}
Expand All @@ -43,10 +53,10 @@ protected override void Write(HtmlRenderer renderer, CodeBlock obj)

try
{
byte[] output = plantUmlRenderer.Render(plantUmlCode, _settings.OutputFormat);
byte[] output = plantUmlRenderer.Render(plantUmlCode, _outputFormat);

renderer.EnsureLine();
renderer.Write(FormatOutput(_settings.OutputFormat, output));
renderer.Write(FormatOutput(_outputFormat, output));
renderer.EnsureLine();
}
catch (RenderingException ex)
Expand Down
57 changes: 31 additions & 26 deletions src/Docfx.MarkdigEngine.Extensions/PlantUml/PlantUmlExtension.cs
Original file line number Diff line number Diff line change
@@ -1,47 +1,52 @@
using System.Text.Json.Serialization;
using Markdig;
using Markdig.Renderers;
using Markdig.Renderers.Html;
using Newtonsoft.Json;
using PlantUml.Net;

namespace Docfx.MarkdigEngine.Extensions;

public class DocfxPlantUmlSettings : PlantUmlSettings
public class PlantUmlOptions
{
public DocfxPlantUmlSettings() : base()
{
}
[JsonProperty("javaPath")]
[JsonPropertyName("javaPath")]
public string JavaPath { get; set; }

public DocfxPlantUmlSettings(IReadOnlyDictionary<string, string> config) : this()
{
if (config.TryGetValue("remoteUrl", out var url))
RemoteUrl = url;
if (config.TryGetValue("outputFormat", out var format))
OutputFormat = Enum.Parse<OutputFormat>(format, true);
if (config.TryGetValue("javaPath", out var path))
JavaPath = path;
if (config.TryGetValue("localPlantUmlPath", out path))
LocalPlantUmlPath = path;
if (config.TryGetValue("localGraphvizDotPath", out path))
LocalGraphvizDotPath = path;
if (config.TryGetValue("renderingMode", out var renderMode))
RenderingMode = Enum.Parse<RenderingMode>(renderMode, true);
}
[JsonProperty("remoteUrl")]
[JsonPropertyName("remoteUrl")]
public string RemoteUrl { get; set; }

[JsonProperty("localPlantUmlPath")]
[JsonPropertyName("localPlantUmlPath")]
public string LocalPlantUmlPath { get; set; }

[JsonProperty("localGraphvizDotPath")]
[JsonPropertyName("localGraphvizDotPath")]
public string LocalGraphvizDotPath { get; set; }

[JsonProperty("renderingMode")]
[JsonPropertyName("renderingMode")]
public RenderingMode RenderingMode { get; set; }

[JsonProperty("delimitor")]
[JsonPropertyName("delimitor")]
public string Delimitor { get; set; }

[JsonProperty("outputFormat")]
[JsonPropertyName("outputFormat")]
public OutputFormat OutputFormat { get; set; } = OutputFormat.Svg;
}

internal class PlantUmlExtension : IMarkdownExtension
{
private readonly MarkdownContext _context;
private readonly DocfxPlantUmlSettings _settings;
private readonly PlantUmlOptions _settings;

public PlantUmlExtension(MarkdownContext context)
public PlantUmlExtension(MarkdownContext context, PlantUmlOptions settings)
{
_context = context;
_settings = new();

if (_context.GetExtensionConfiguration("PlantUml") is Dictionary<string, string> config)
_settings = new DocfxPlantUmlSettings(config);
_settings = settings ?? new();
}

public void Setup(MarkdownPipelineBuilder pipeline)
Expand All @@ -52,7 +57,7 @@ public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
if (renderer is HtmlRenderer { ObjectRenderers: not null } htmlRenderer)
{
var customRenderer = new CustomCodeBlockRenderer(_context, _settings);
var customRenderer = new PlantUmlCodeBlockRenderer(_context, _settings);
var renderers = htmlRenderer.ObjectRenderers;

if (renderers.Contains<CodeBlockRenderer>())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ public class QuoteSectionNoteExtension : IMarkdownExtension
["CAUTION"] = "CAUTION",
};

public QuoteSectionNoteExtension(MarkdownContext context)
public QuoteSectionNoteExtension(MarkdownContext context, Dictionary<string, string> notes)
{
_context = context;

if (_context.GetExtensionConfiguration("Alerts") is Dictionary<string, string> config)
if (notes != null)
{
foreach (var (key, value) in config)
foreach (var (key, value) in notes)
_notes[key] = value;
}
}
Expand Down
5 changes: 1 addition & 4 deletions src/Docfx.MarkdigEngine/MarkdigMarkdownService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ public MarkdigMarkdownService(
(code, message, origin, line) => Logger.LogError(message, null, InclusionContext.File.ToString(), line?.ToString(), code),
ReadFile,
GetLink,
GetImageLink,
GetExtensionConfiguration);
GetImageLink);
}

public MarkupResult Markup(string content, string filePath)
Expand Down Expand Up @@ -187,8 +186,6 @@ private static string GetLink(string path, MarkdownObject origin)
return path;
}

private object GetExtensionConfiguration(string extension) => _parameters.GetExtensionConfiguration(extension);

private static string GetImageLink(string href, MarkdownObject origin, string altText) => GetLink(href, origin);

private static void ReportDependency(RelativePath filePathToDocset, string parentFileDirectoryToDocset)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections.Immutable;
using System.Text.Json.Serialization;
using Docfx.MarkdigEngine.Extensions;
using Newtonsoft.Json;

namespace Docfx.Plugins;
Expand Down Expand Up @@ -41,7 +42,7 @@ public class MarkdownServiceProperties
/// </summary>
[JsonProperty("plantUml")]
[JsonPropertyName("plantUml")]
public Dictionary<string, string> PlantUml { get; set; }
public PlantUmlOptions PlantUml { get; set; }
}

public class MarkdownServiceParameters
Expand All @@ -50,16 +51,4 @@ public class MarkdownServiceParameters
public string TemplateDir { get; set; }
public MarkdownServiceProperties Extensions { get; set; } = new();
public ImmutableDictionary<string, string> Tokens { get; set; } = ImmutableDictionary<string, string>.Empty;

public object GetExtensionConfiguration(string extension)
{
if (!string.IsNullOrEmpty(extension) && Extensions != null)
{
var property = typeof(MarkdownServiceProperties).GetProperty(extension);
if (property != null)
return property.GetValue(Extensions);
}

return null;
}
}
11 changes: 5 additions & 6 deletions test/Docfx.MarkdigEngine.Extensions.Tests/PlantUmlTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,10 @@ public void TestRenderSvg_SequenceDiagram()
<div class="lang-plantUml"><?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="120px" preserveAspectRatio="none" style="width:113px;height:120px;background:#FFFFFF;" version="1.1" viewBox="0 0 113 120" width="113px" zoomAndPan="magnify"><defs/><g><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="26" x2="26" y1="36.2969" y2="85.4297"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="82" x2="82" y1="36.2969" y2="85.4297"/><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="43" x="5" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="29" x="12" y="24.9951">Bob</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="43" x="5" y="84.4297"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="29" x="12" y="104.4248">Bob</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="49" x="58" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="35" x="65" y="24.9951">Alice</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="49" x="58" y="84.4297"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="35" x="65" y="104.4248">Alice</text><polygon fill="#181818" points="70.5,63.4297,80.5,67.4297,70.5,71.4297,74.5,67.4297" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="26.5" x2="76.5" y1="67.4297" y2="67.4297"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="30" x="33.5" y="62.3638">hello</text><!--SRC=[SyfFKj2rKt3CoKnELR1Io4ZDoSa70000]--></g></svg></div>
""";

TestUtility.VerifyMarkup(source, expected, extensionConfiguration:
new Dictionary<string, string>
{
{ "outputFormat", "svg"},
{ "remoteUrl", "https://www.plantuml.com/plantuml" }
});
TestUtility.VerifyMarkup(source, expected, plantUml: new()
{
OutputFormat = PlantUml.Net.OutputFormat.Svg,
RemoteUrl = "https://www.plantuml.com/plantuml",
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ public void QuoteSectionNoteTest_ExtensionConfiguration()
<p>This is a custom REVIEW section</p>
</div>
";
TestUtility.VerifyMarkup(source, expected, extensionConfiguration:
TestUtility.VerifyMarkup(source, expected, notes:
new Dictionary<string, string>
{
{ "TODO", "alert alert-secondary" },
Expand Down
10 changes: 4 additions & 6 deletions test/Docfx.MarkdigEngine.Extensions.Tests/TestUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using Docfx.MarkdigEngine.Extensions;
using Markdig;
using Markdig.Syntax;
using Newtonsoft.Json.Linq;
using Xunit;

namespace Docfx.MarkdigEngine.Tests;
Expand All @@ -20,9 +19,9 @@ public static void VerifyMarkup(
string filePath = "test.md",
Dictionary<string, string> tokens = null,
Dictionary<string, string> files = null,
Action<MarkdownObject> verifyAST = null,
IEnumerable<string> optionalExtensions = null,
object extensionConfiguration = null)
Dictionary<string, string> notes = null,
PlantUmlOptions plantUml = null)
{
errors ??= Array.Empty<string>();
tokens ??= new Dictionary<string, string>();
Expand All @@ -38,11 +37,10 @@ public static void VerifyMarkup(
logSuggestion: Log("suggestion"),
logWarning: Log("warning"),
logError: Log("error"),
readFile: ReadFile,
getConfig: _ => extensionConfiguration);
readFile: ReadFile);

var pipelineBuilder = new MarkdownPipelineBuilder()
.UseDocfxExtensions(markdownContext)
.UseDocfxExtensions(markdownContext, notes, plantUml)
.UseYamlFrontMatter()
.UseOptionalExtensions(optionalExtensions);

Expand Down
Loading

0 comments on commit 0d56f79

Please sign in to comment.