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

BuildTools OneOf + Optional #1132

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
133 changes: 133 additions & 0 deletions src/protobuf-net.MSBuild.Test/BuildTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
#if DEBUG
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using Microsoft.Build.Locator;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;

namespace ProtoBuf.Build
{
internal class MSBuildFixture : IDisposable
{
public MSBuildFixture()
{
MSBuildLocator.RegisterDefaults();
}

void IDisposable.Dispose()
{
}
}

public class BuildTests : IClassFixture<MSBuildFixture>
{
private readonly ILogger logger;
private readonly ITestOutputHelper o;

private static readonly Dictionary<string, string> gp =
new Dictionary<string, string>
{
["Configuration"] = "Debug",
["Platform"] = "AnyCPU",
};

public BuildTests(ITestOutputHelper o)
{
this.o = o;
this.logger = new XUnitTestLogger(o);
}

//private string GetOutput(string exePath, string args)
//{
// var psi = new ProcessStartInfo(exePath, args)
// {
// UseShellExecute = false,
// RedirectStandardOutput = true,
// CreateNoWindow = true,
// };
// var proc = Process.Start(psi);
// var text = proc.StandardOutput.ReadToEnd();
// proc.WaitForExit();
// return text;
//}

private void LogProps(Project proj)
{
foreach (var kvp in Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().OrderBy(e => e.Key))
{
o.WriteLine(kvp.Key + ": " + kvp.Value);
}

foreach (var prop in proj.AllEvaluatedProperties.OrderBy(p => p.Name))
{
o.WriteLine(prop.Name + ": " + prop.EvaluatedValue + " (" + prop.UnevaluatedValue + ")");
}
}

private string BuildProject(string projFile)
{
#pragma warning disable IDE0067 // Dispose objects before losing scope
var pc = new ProjectCollection(gp);
#pragma warning restore IDE0067 // Dispose objects before losing scope
var proj = pc.LoadProject(projFile);
var restored = proj.Build("Restore", new[] { logger });
if (!restored)
{
LogProps(proj);
}
Assert.True(restored, "Failed to restore packages");
var result = proj.Build(logger);
var outputPath = proj.GetPropertyValue("TargetPath");
Assert.True(result, "Build failed");
return outputPath;
}

[Fact]
public void CSharpCodeGenTest()
{
BuildProject("Data/Proj1/Proj.csproj");
}

[Fact]
public void VBCodeGenTest()
{
BuildProject("Data/Proj2/Proj.vbproj");
}

[Fact]
public void CodeGenErrors()
{
var testLogger = new TestLogger();
const string projFile = "Data/Proj3/Proj.csproj";

#pragma warning disable IDE0067 // Dispose objects before losing scope
var pc = new ProjectCollection(gp);
#pragma warning restore IDE0067 // Dispose objects before losing scope
var proj = pc.LoadProject(projFile);
var restored = proj.Build("Restore", new[] { logger });
if (!restored) LogProps(proj);
Assert.True(restored, "Failed to restore packages");
var result = proj.Build(new ILogger[] { logger, testLogger });
Assert.False(result);
Assert.Single(testLogger.Errors);
Assert.Single(testLogger.Warnings);
}

[Fact]
public void ServicesGenTest()
{
BuildProject("Data/Proj4/Proj.csproj");
}

[Fact]
public void BuildOneOfEnumAndOptional()
{
BuildProject("Data/Proj5/Proj.csproj");
}
}
}
#endif
14 changes: 14 additions & 0 deletions src/protobuf-net.MSBuild.Test/Data/Proj5/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestNS;

class Program
{
static void Main()
{
ExampleMessage message = new ExampleMessage();
}
}
9 changes: 9 additions & 0 deletions src/protobuf-net.MSBuild.Test/Data/Proj5/Proj.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<RootNamespace>TestNS</RootNamespace>
<TargetFramework>net461</TargetFramework>
</PropertyGroup>

<Import Project="$(MSBuildThisFileDirectory)/../Common.props"/>
</Project>
24 changes: 24 additions & 0 deletions src/protobuf-net.MSBuild.Test/Data/Proj5/Test.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
syntax = "proto3";

import "protobuf-net/protogen.proto";
option (.protobuf_net.fileopt).oneofEnum = true;

message ExampleMessage
{
oneof ExampleMessageOneOf
{
TypeOne TypeOne = 1;
TypeTwo TypeTwo = 2;
}
}

message TypeOne
{
double numericValue = 1;
}

message TypeTwo
{
string stringValue = 1;
optional int32 integerValue = 2;
}
41 changes: 41 additions & 0 deletions src/protobuf-net.MSBuild.Test/protobuf-net.MSBuild.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net472</TargetFramework>
<RootNamespace>ProtoBuf.Build</RootNamespace>
<GenerateProgramFile>false</GenerateProgramFile>
<NoWarn>$(NOWARN);CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
<None Remove="Data\**\*" />
<Compile Remove="Data\**\*" />
<Content Include="Data\**\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Build" Version="16.8.0">
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Build.Framework" Version="16.8.0">
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Build.Locator" Version="1.2.6" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="16.8.0">
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
<PackageReference Include="System.Collections.Immutable" Version="5.0.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\protobuf-net.MSBuild\protobuf-net.MSBuild.csproj" />
</ItemGroup>
</Project>
12 changes: 10 additions & 2 deletions src/protobuf-net.Reflection/CodeGenerator.OneOfStub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,13 @@ internal OneOfStub(OneofDescriptorProto decl, int index)
internal int CountRef { get; private set; }
internal int CountTotal => CountRef + Count32 + Count64;

private void AccountFor(FieldDescriptorProto.Type type, string typeName)
private bool _anyProto3Optional;

private void AccountFor(FieldDescriptorProto.Type type, string typeName, bool isProto3Optional)
{
if (isProto3Optional)
_anyProto3Optional = true;

switch (type)
{
case FieldDescriptorProto.Type.TypeBool:
Expand Down Expand Up @@ -130,7 +135,7 @@ internal static OneOfStub[] Build(DescriptorProto message)
{
if (field.ShouldSerializeOneofIndex())
{
stubs[field.OneofIndex].AccountFor(field.type, field.TypeName);
stubs[field.OneofIndex].AccountFor(field.type, field.TypeName, field.Proto3Optional);
}
}
return stubs;
Expand Down Expand Up @@ -162,6 +167,9 @@ internal string GetUnionType()
}
return "DiscriminatedUnionObject";
}

internal bool IsProto3OptionalSyntheticOneOf()
=> CountTotal == 1 && _anyProto3Optional;
}
}
}
2 changes: 1 addition & 1 deletion src/protobuf-net.Reflection/CodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ protected virtual void WriteEnum(GeneratorContext ctx, EnumDescriptorProto obj)
/// </summary>
protected virtual void WriteOneOf(GeneratorContext ctx, OneOfStub stub)
{
if (ctx.OneOfEnums)
if (ctx.OneOfEnums && !stub.IsProto3OptionalSyntheticOneOf())
{
int index = stub.Index;
var obj = stub.OneOf;
Expand Down