Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ThisAssembly.Resources Improvements #157

Merged
merged 6 commits into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/ThisAssembly.Resources/CSharp.sbntxt
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@
{{ func render }}
public static partial class {{ $0.Name }}
{
{{~ if $0.Resource ~}}
{{- resource $0.Resource ~}}
{{~ if $0.Resources ~}}
{{~ for $r in $0.Resources ~}}
{{- resource $r ~}}
{{~ end ~}}
{{~ else ~}}
{{ render $0.NestedArea }}
{{~ end ~}}
Expand Down
25 changes: 19 additions & 6 deletions src/ThisAssembly.Resources/Model.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

[DebuggerDisplay("Values = {RootArea.Values.Count}")]
record Model(Area RootArea)
Expand All @@ -15,24 +16,36 @@ record Model(Area RootArea)
record Area(string Name)
{
public Area? NestedArea { get; private set; }
public Resource? Resource { get; private set; }
public IEnumerable<Resource>? Resources { get; private set; }

public static Area Load(Resource resource, string rootArea = "Resources")
public static Area Load(string basePath, List<Resource> resources, string rootArea = "Resources")
{
var root = new Area(rootArea);

// Splits: ([area].)*[name]
var area = root;
var parts = resource.Name.Split(new[] { "\\", "/" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts.AsSpan()[..^1])
var parts = basePath.Split(new[] { "\\", "/" }, StringSplitOptions.RemoveEmptyEntries);
var end = resources.Count == 1 ? ^1 : ^0;

foreach (var part in parts.AsSpan()[..end])
{
area.NestedArea = new Area(part);
var partStr = SanitizePart(part);
area.NestedArea = new Area(partStr);
area = area.NestedArea;
}

area.Resource = resource with { Name = Path.GetFileNameWithoutExtension(parts[^1]), Path = resource.Name, };
area.Resources = resources;
return root;
}

static readonly Regex invalidCharsRegex = new(@"\W");
static string SanitizePart(string? part)
{
var partStr = invalidCharsRegex.Replace(part, "_");
if (char.IsDigit(partStr[0]))
partStr = "_" + partStr;
return partStr;
}
}

[DebuggerDisplay("{Name}")]
Expand Down
72 changes: 50 additions & 22 deletions src/ThisAssembly.Resources/ResourcesGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -30,47 +30,75 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
x.Right.GetOptions(x.Left).TryGetValue("build_metadata.EmbeddedResource.Value", out var resourceName);
x.Right.GetOptions(x.Left).TryGetValue("build_metadata.EmbeddedResource.Kind", out var kind);
x.Right.GetOptions(x.Left).TryGetValue("build_metadata.EmbeddedResource.Comment", out var comment);
return (resourceName!, kind, comment: string.IsNullOrWhiteSpace(comment) ? null : comment);
return (resourceName: resourceName!, kind, comment: string.IsNullOrWhiteSpace(comment) ? null : comment);
})
.Collect()
.Combine(context.AnalyzerConfigOptionsProvider
.Select((p, _) =>
.SelectMany((p, _) =>
{
if (!p.GlobalOptions.TryGetValue("build_property.EmbeddedResourceStringExtensions", out var extensions) ||
extensions == null)
return new HashSet<string>();
return Array.Empty<string>();

return new HashSet<string>(extensions.Split('|'), StringComparer.OrdinalIgnoreCase);
}));
return extensions.Split('|');
})
.WithComparer(StringComparer.OrdinalIgnoreCase)
.Collect());

context.RegisterSourceOutput(
files,
GenerateSource);
}

static void GenerateSource(SourceProductionContext spc, ((string resourceName, string? kind, string? comment), HashSet<string> extensions) arg2)
static void GenerateSource(
SourceProductionContext spc,
(
ImmutableArray<(string resourceName, string? kind, string? comment)> files,
ImmutableArray<string> extensions) arg2)
{
var ((resourceName, kind, comment), extensions) = arg2;
var (files, extensions) = arg2;

var file = "CSharp.sbntxt";
var template = Template.Parse(EmbeddedResource.GetContent(file), file);

var isText = kind?.Equals("text", StringComparison.OrdinalIgnoreCase) == true ||
extensions.Contains(Path.GetExtension(resourceName));
var root = Area.Load(new Resource(resourceName, comment, isText));
var model = new Model(root);
var groupsWithoutExtensions = files
.GroupBy(f => Path.Combine(
Path.GetDirectoryName(f.resourceName),
Path.GetFileNameWithoutExtension(f.resourceName)));
foreach (var group in groupsWithoutExtensions)
{
var basePath = group.Key;
var resources = group
.Select(f =>
{
var isText = f.kind?.Equals("text", StringComparison.OrdinalIgnoreCase) == true ||
extensions.Contains(Path.GetExtension(f.resourceName));
var name = group.Count() == 1
? Path.GetFileNameWithoutExtension(f.resourceName)
: Path.GetExtension(f.resourceName)[1..];
return new Resource(name, f.comment, isText)
{
Path = f.resourceName,
};
})
.ToList();

var root = Area.Load(basePath, resources);
var model = new Model(root);

var output = template.Render(model, member => member.Name);
var output = template.Render(model, member => member.Name);

// Apply formatting since indenting isn't that nice in Scriban when rendering nested
// structures via functions.
output = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseCompilationUnit(output)
.NormalizeWhitespace()
.GetText()
.ToString();
// Apply formatting since indenting isn't that nice in Scriban when rendering nested
// structures via functions.
output = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseCompilationUnit(output)
.NormalizeWhitespace()
.GetText()
.ToString();

spc.AddSource(
$"{resourceName.Replace('\\', '.').Replace('/', '.')}.g.cs",
SourceText.From(output, Encoding.UTF8));
spc.AddSource(
$"{basePath.Replace('\\', '.').Replace('/', '.')}.g.cs",
SourceText.From(output, Encoding.UTF8));
}
}
}
}
2 changes: 2 additions & 0 deletions src/ThisAssembly.Tests/Content/Swagger/swagger-ui.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
body {
}
1 change: 1 addition & 0 deletions src/ThisAssembly.Tests/Content/Swagger/swagger-ui.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
(function () { })();
3 changes: 3 additions & 0 deletions src/ThisAssembly.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,8 @@ public void CanUseTextResource()
public void CanUseByteResource()
=> Assert.NotNull(ThisAssembly.Resources.Content.Styles.Main.GetBytes());

[Fact]
public void CanUseSameNameDifferentExtensions()
=> Assert.NotNull(ThisAssembly.Resources.Content.Swagger.swagger_ui.css.GetBytes());
}
}
2 changes: 2 additions & 0 deletions src/ThisAssembly.Tests/ThisAssembly.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
<EmbeddedResource Include="Content/Styles/Custom.css" Kind="Text" Comment="Secondary CSS" />
<EmbeddedResource Include="Content/Styles/Main.css" Comment="Primary CSS" />
<EmbeddedResource Include="Content/Docs/*" />
<EmbeddedResource Include="Content/Swagger/*" />
<None Remove="Content/Swagger/*" />
</ItemGroup>

<PropertyGroup>
Expand Down