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

Use raw string literals if supported by the target language #244

Merged
merged 1 commit into from
Jul 3, 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
1 change: 1 addition & 0 deletions src/Directory.props
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<PackageScribanIncludeSource>true</PackageScribanIncludeSource>

<SuppressNETCoreSdkPreviewMessage>true</SuppressNETCoreSdkPreviewMessage>
<NoWarn>MSB3277;$(NoWarn)</NoWarn>
</PropertyGroup>

<PropertyGroup Label="Build">
Expand Down
11 changes: 7 additions & 4 deletions src/ThisAssembly.AssemblyInfo/AssemblyInfoGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
.Collect();

context.RegisterSourceOutput(
metadata.Combine(context.CompilationProvider.Select((s, _) => s.Language)),
metadata.Combine(context.ParseOptionsProvider),
GenerateSource);
}

Expand All @@ -66,12 +66,15 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
return new KeyValuePair<string, string>(key, value);
}

static void GenerateSource(SourceProductionContext spc, (ImmutableArray<KeyValuePair<string, string>> attributes, string language) arg2)
static void GenerateSource(SourceProductionContext spc, (ImmutableArray<KeyValuePair<string, string>> attributes, ParseOptions parse) arg)
{
var (attributes, language) = arg2;
var (attributes, parse) = arg;

var model = new Model(attributes.ToList());
var file = language.Replace("#", "Sharp") + ".sbntxt";
if (parse is CSharpParseOptions cs && (int)cs.LanguageVersion >= 11)
model.RawStrings = true;

var file = parse.Language.Replace("#", "Sharp") + ".sbntxt";
var template = Template.Parse(EmbeddedResource.GetContent(file), file);
var output = template.Render(model, member => member.Name);

Expand Down
8 changes: 7 additions & 1 deletion src/ThisAssembly.AssemblyInfo/CSharp.sbntxt
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@ partial class ThisAssembly
public static partial class Info
{
{{~ for prop in Properties ~}}
{{~ if RawStrings ~}}
public const string {{ prop.Key }} =
"""
{{ prop.Value }}
""";
{{~ else ~}}
public const string {{ prop.Key }} = @"{{ prop.Value }}";

{{~ end ~}}
{{~ end ~}}
}
}
1 change: 1 addition & 0 deletions src/ThisAssembly.AssemblyInfo/Model.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public class Model
{
public Model(IEnumerable<KeyValuePair<string, string>> properties) => Properties = properties.ToList();

public bool RawStrings { get; set; } = false;
public string Version => Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

public List<KeyValuePair<string, string>> Properties { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,8 @@ on the `ThisAssembly.Info` class.
<PackageReference Include="PolySharp" Version="1.13.2" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="ThisAssembly.Tests"/>
</ItemGroup>

</Project>
9 changes: 8 additions & 1 deletion src/ThisAssembly.Constants/CSharp.sbntxt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,14 @@
{
{{~ for value in $0.Values ~}}
{{- summary value ~}}
public const string {{ value.Name | string.replace "-" "_" | string.replace " " "_" }} = @"{{ value.Value }}";
{{~ if RawStrings ~}}
public const string {{ value.Name | string.replace "-" "_" | string.replace " " "_" }} =
"""
{{ value.Value }}
""";
{{~ else ~}}
public const string {{ value.Name | string.replace "-" "_" | string.replace " " "_" }} = @"{{ value.Value }}";
{{~ end ~}}
{{~ end ~}}

{{ for area in $0.NestedAreas
Expand Down
19 changes: 12 additions & 7 deletions src/ThisAssembly.Constants/ConstantsGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Scriban;

Expand Down Expand Up @@ -30,28 +31,32 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
comment: string.IsNullOrWhiteSpace(comment) ? null : comment,
root: string.IsNullOrWhiteSpace(root) ? "Constants" : root!);
})
.Combine(context.CompilationProvider.Select((p, _) => p.Language));
.Combine(context.ParseOptionsProvider);

context.RegisterSourceOutput(
files,
GenerateConstant);

}

void GenerateConstant(SourceProductionContext spc, ((string name, string value, string? comment, string root), string language) args)
void GenerateConstant(SourceProductionContext spc, ((string name, string value, string? comment, string root), ParseOptions parse) args)
{
var ((name, value, comment, root), language) = args;
var ((name, value, comment, root), parse) = args;

var rootArea = Area.Load(new List<Constant> { new Constant(name, value, comment), }, root);
var file = language.Replace("#", "Sharp") + ".sbntxt";
var file = parse.Language.Replace("#", "Sharp") + ".sbntxt";
var template = Template.Parse(EmbeddedResource.GetContent(file), file);
var output = template.Render(new Model(rootArea), member => member.Name);
var model = new Model(rootArea);
if (parse is CSharpParseOptions cs && (int)cs.LanguageVersion >= 11)
model.RawStrings = true;

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

// Apply formatting since indenting isn't that nice in Scriban when rendering nested
// structures via functions.
if (language == LanguageNames.CSharp)
if (parse.Language == LanguageNames.CSharp)
{
output = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseCompilationUnit(output)
output = SyntaxFactory.ParseCompilationUnit(output)
.NormalizeWhitespace()
.GetText()
.ToString();
Expand Down
1 change: 1 addition & 0 deletions src/ThisAssembly.Constants/Model.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
[DebuggerDisplay("Values = {RootArea.Values.Count}")]
record Model(Area RootArea)
{
public bool RawStrings { get; set; } = false;
public string Version => Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
}

Expand Down
10 changes: 9 additions & 1 deletion src/ThisAssembly.Metadata/CSharp.sbntxt
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,16 @@ partial class ThisAssembly
public static partial class Metadata
{
{{~ for md in Metadata ~}}
/// <summary>{{ md.Key }} = {{ md.Value }}</summary>
/// <summary>{{ md.Key }} = {{ md.Value | string.split "\n" | array.first | string.replace "\r" "" | string.lstrip | string.rstrip }}</summary>
{{~ if RawStrings ~}}
public const string {{ md.Key }} =
"""
{{ md.Value }}
""";
{{~ else ~}}
/// <summary>{{ prop.Key }} = {{ prop.Value }}</summary>
public const string {{ md.Key }} = @"{{ md.Value }}";
{{~ end ~}}

{{~ end ~}}
}
Expand Down
13 changes: 9 additions & 4 deletions src/ThisAssembly.Metadata/MetadataGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Scriban;
using Scriban.Parsing;

namespace ThisAssembly
{
Expand All @@ -26,7 +28,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
.Collect();

context.RegisterSourceOutput(
metadata.Combine(context.CompilationProvider.Select((s, _) => s.Language)),
metadata.Combine(context.ParseOptionsProvider),
GenerateSource);
}

Expand Down Expand Up @@ -54,12 +56,15 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
return new KeyValuePair<string, string>(key, value);
}

void GenerateSource(SourceProductionContext spc, (ImmutableArray<KeyValuePair<string, string>> attributes, string language) arg2)
void GenerateSource(SourceProductionContext spc, (ImmutableArray<KeyValuePair<string, string>> attributes, ParseOptions parse) arg)
{
var (attributes, language) = arg2;
var (attributes, parse) = arg;

var model = new Model(attributes.ToList());
var file = language.Replace("#", "Sharp") + ".sbntxt";
if (parse is CSharpParseOptions cs && (int)cs.LanguageVersion >= 11)
model.RawStrings = true;

var file = parse.Language.Replace("#", "Sharp") + ".sbntxt";
var template = Template.Parse(EmbeddedResource.GetContent(file), file);
var output = template.Render(model, member => member.Name);

Expand Down
1 change: 1 addition & 0 deletions src/ThisAssembly.Metadata/Model.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public class Model
{
public Model(IEnumerable<KeyValuePair<string, string>> metadata) => Metadata = metadata.ToList();

public bool RawStrings { get; set; } = false;
public string Version => Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

public List<KeyValuePair<string, string>> Metadata { get; }
Expand Down
8 changes: 7 additions & 1 deletion src/ThisAssembly.Project/CSharp.sbntxt
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,15 @@ partial class ThisAssembly
public static partial class Project
{
{{~ for prop in Properties ~}}
{{~ if RawStrings ~}}
public const string {{ prop.Key }} =
"""
{{ prop.Value }}
""";
{{~ else ~}}
/// <summary>{{ prop.Key }} = {{ prop.Value }}</summary>
public const string {{ prop.Key }} = @"{{ prop.Value }}";

{{~ end ~}}
{{~ end ~}}
}
}
1 change: 1 addition & 0 deletions src/ThisAssembly.Project/Model.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public class Model
{
public Model(IEnumerable<KeyValuePair<string, string>> properties) => Properties = properties.ToList();

public bool RawStrings { get; set; } = false;
public string Version => Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

public List<KeyValuePair<string, string>> Properties { get; }
Expand Down
12 changes: 8 additions & 4 deletions src/ThisAssembly.Project/ProjectPropertyGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Scriban;

Expand All @@ -30,16 +31,19 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
.Collect();

context.RegisterSourceOutput(
properties.Combine(context.CompilationProvider.Select((s, _) => s.Language)),
properties.Combine(context.ParseOptionsProvider),
GenerateSource);
}

void GenerateSource(SourceProductionContext spc, (ImmutableArray<KeyValuePair<string, string?>> properties, string language) arg2)
void GenerateSource(SourceProductionContext spc, (ImmutableArray<KeyValuePair<string, string?>> properties, ParseOptions parse) arg)
{
var (properties, language) = arg2;
var (properties, parse) = arg;

var model = new Model(properties);
var file = language.Replace("#", "Sharp") + ".sbntxt";
if (parse is CSharpParseOptions cs && (int)cs.LanguageVersion >= 11)
model.RawStrings = true;

var file = parse.Language.Replace("#", "Sharp") + ".sbntxt";
var template = Template.Parse(EmbeddedResource.GetContent(file), file);
var output = template.Render(model, member => member.Name);

Expand Down
9 changes: 7 additions & 2 deletions src/ThisAssembly.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,13 @@ public void CanUseInfo()

[Fact]
public void CanUseInfoDescription()
=> Assert.Equal(@"A Description
with a newline".ReplaceLineEndings(), ThisAssembly.Info.Description.ReplaceLineEndings());
=> Assert.Equal(
"""
A Description
with a newline and
* Some "things" with quotes
// Some comments too.
""".ReplaceLineEndings(), ThisAssembly.Info.Description.ReplaceLineEndings());

[Fact]
public void CanUseConstants()
Expand Down
17 changes: 15 additions & 2 deletions src/ThisAssembly.Tests/ThisAssembly.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@
<PropertyGroup>
<IsPackable>false</IsPackable>
<TargetFramework>net7.0</TargetFramework>
<Multiline>
A Description
with a newline and
* Some "things" with quotes
// Some comments too.
</Multiline>
<Description>A Description
with a newline</Description>
with a newline and
* Some "things" with quotes
// Some comments too.</Description>
<TargetFramework Condition="'$(BuildingInsideVisualStudio)' == 'true'">net472</TargetFramework>
<RootNamespace>ThisAssemblyTests</RootNamespace>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
Expand Down Expand Up @@ -54,20 +62,25 @@ with a newline</Description>
<ItemGroup>
<ProjectProperty Include="Foo" />
<ProjectProperty Include="Foo" />
<ProjectProperty Include="Description" />
<!-- Multiline values that go through .editorconfig will get truncated, unfortunately -->
<ProjectProperty Include="Multiline" />
<Constant Include="Foo.Raw" Value="$(Multiline)" Comment="$(Multiline)" />
<Constant Include="Foo.Bar" Value="Baz" Comment="Yay!" />
<Constant Include="Foo.Hello" Value="World" Comment="Comments make everything better 😍" />
<FileConstant Include="@(None)" />
<FileConstant Update="@(FileConstant -&gt; WithMetadataValue('Filename', 'Readme'))">
<Link>Included/%(Filename)%(Extension)</Link>
</FileConstant>
<AssemblyMetadata Include="Foo" Value="Bar" />
<AssemblyMetadata Include="Raw" Value="$(Multiline)" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\ThisAssembly.Strings\Model.cs" Link="Model.cs" />
</ItemGroup>

<Import Project="..\ThisAssembly.Prerequisites.targets"/>
<Import Project="..\ThisAssembly.Prerequisites.targets" />
<Import Project="..\*\*.targets" />

</Project>