Commit 57599ef1 authored by Jon Skeet's avatar Jon Skeet

A few stylistic issues

parent c58ce5dc
...@@ -266,10 +266,10 @@ ...@@ -266,10 +266,10 @@
<property name="Configuration" value="Release" /> <property name="Configuration" value="Release" />
<property name="Platform" value="Any CPU" /> <property name="Platform" value="Any CPU" />
</msbuild> </msbuild>
<!--msbuild project="${src}/ProtocolBuffers.sln"> <msbuild project="${src}/ProtocolBuffers.sln">
<property name="Configuration" value="Silverlight2" /> <property name="Configuration" value="Silverlight2" />
<property name="Platform" value="Any CPU" /> <property name="Platform" value="Any CPU" />
</msbuild--> </msbuild>
<!-- Note the deliberate lack of space in the platform name --> <!-- Note the deliberate lack of space in the platform name -->
<msbuild project="${src}/ProtocolBuffers/ProtocolBuffersCF.csproj"> <msbuild project="${src}/ProtocolBuffers/ProtocolBuffersCF.csproj">
<property name="Configuration" value="Release" /> <property name="Configuration" value="Release" />
...@@ -291,7 +291,7 @@ ...@@ -291,7 +291,7 @@
<mkdir dir="${output-dir}/Protoc" /> <mkdir dir="${output-dir}/Protoc" />
<mkdir dir="${output-dir}/Debug" /> <mkdir dir="${output-dir}/Debug" />
<mkdir dir="${output-dir}/Release" /> <mkdir dir="${output-dir}/Release" />
<!--mkdir dir="${output-dir}/Silverlight2" /--> <mkdir dir="${output-dir}/Silverlight2" />
<mkdir dir="${output-dir}/CompactFramework35" /> <mkdir dir="${output-dir}/CompactFramework35" />
<copy todir="${output-dir}/Protoc"> <copy todir="${output-dir}/Protoc">
<fileset basedir="${project::get-base-directory()}/lib"> <fileset basedir="${project::get-base-directory()}/lib">
...@@ -321,12 +321,12 @@ ...@@ -321,12 +321,12 @@
<exclude name="**/*vshost*" /> <exclude name="**/*vshost*" />
</fileset> </fileset>
</copy> </copy>
<!--copy todir="${output-dir}/Silverlight2" <copy todir="${output-dir}/Silverlight2"
flatten="true"> flatten="true">
<fileset basedir="${src}"> <fileset basedir="${src}">
<include name="ProtocolBuffers/bin/Silverlight2/Google.ProtocolBuffers.dll" /> <include name="ProtocolBuffers/bin/Silverlight2/Google.ProtocolBuffers.dll" />
</fileset> </fileset>
</copy--> </copy>
<copy todir="${output-dir}/CompactFramework35" <copy todir="${output-dir}/CompactFramework35"
flatten="true"> flatten="true">
<fileset basedir="${src}"> <fileset basedir="${src}">
......
...@@ -39,7 +39,6 @@ message CSharpFileOptions { ...@@ -39,7 +39,6 @@ message CSharpFileOptions {
// Generate attributes indicating non-CLS-compliance // Generate attributes indicating non-CLS-compliance
optional bool cls_compliance = 8 [default = true]; optional bool cls_compliance = 8 [default = true];
// ROK - 2010-09-03 additions to csoptions ...
// The extension that should be appended to the umbrella_classname when creating files. // The extension that should be appended to the umbrella_classname when creating files.
optional string file_extension = 221 [default = ".cs"]; optional string file_extension = 221 [default = ".cs"];
......
...@@ -50,7 +50,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -50,7 +50,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
FileDescriptorProto second = new FileDescriptorProto.Builder { Name="Second" }.Build(); FileDescriptorProto second = new FileDescriptorProto.Builder { Name="Second" }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } }; FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
IList<FileDescriptor> converted = Generator.ConvertDescriptors(set); IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count); Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name); Assert.AreEqual("First", converted[0].Name);
Assert.AreEqual(0, converted[0].Dependencies.Count); Assert.AreEqual(0, converted[0].Dependencies.Count);
...@@ -63,7 +63,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -63,7 +63,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = {"Second"} }.Build(); FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = {"Second"} }.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second" }.Build(); FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second" }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } }; FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
IList<FileDescriptor> converted = Generator.ConvertDescriptors(set); IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count); Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name); Assert.AreEqual("First", converted[0].Name);
Assert.AreEqual(1, converted[0].Dependencies.Count); Assert.AreEqual(1, converted[0].Dependencies.Count);
...@@ -77,7 +77,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -77,7 +77,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First" }.Build(); FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First" }.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second", DependencyList = {"First"} }.Build(); FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second", DependencyList = {"First"} }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } }; FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
IList<FileDescriptor> converted = Generator.ConvertDescriptors(set); IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count); Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name); Assert.AreEqual("First", converted[0].Name);
Assert.AreEqual(0, converted[0].Dependencies.Count); Assert.AreEqual(0, converted[0].Dependencies.Count);
...@@ -92,7 +92,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -92,7 +92,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second", DependencyList = { "First" } }.Build(); FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second", DependencyList = { "First" } }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } }; FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
try { try {
Generator.ConvertDescriptors(set); Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception"); Assert.Fail("Expected exception");
} catch (DependencyResolutionException) { } catch (DependencyResolutionException) {
// Expected // Expected
...@@ -104,7 +104,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -104,7 +104,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = { "Second" } }.Build(); FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = { "Second" } }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first } }; FileDescriptorSet set = new FileDescriptorSet { FileList = { first } };
try { try {
Generator.ConvertDescriptors(set); Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception"); Assert.Fail("Expected exception");
} catch (DependencyResolutionException) { } catch (DependencyResolutionException) {
// Expected // Expected
...@@ -116,7 +116,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -116,7 +116,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = { "First" } }.Build(); FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = { "First" } }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first } }; FileDescriptorSet set = new FileDescriptorSet { FileList = { first } };
try { try {
Generator.ConvertDescriptors(set); Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception"); Assert.Fail("Expected exception");
} catch (DependencyResolutionException) { } catch (DependencyResolutionException) {
// Expected // Expected
......
...@@ -5,44 +5,50 @@ using System.Text; ...@@ -5,44 +5,50 @@ using System.Text;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
{ {
class ProtoFile : TempFile class ProtoFile : TempFile
{ {
public ProtoFile (string filename, string contents) public ProtoFile(string filename, string contents)
{ : base(filename, contents)
_tempFile = filename; {
File.WriteAllText(_tempFile, contents); }
} }
} class TempFile : IDisposable
class TempFile : IDisposable {
{ private string tempFile;
protected string _tempFile;
public static TempFile Attach(string path) public static TempFile Attach(string path)
{ {
TempFile f = new TempFile(); return new TempFile(path, null);
f._tempFile = path; }
return f;
}
protected TempFile() { } protected TempFile(string filename, string contents) {
public TempFile(string contents) tempFile = filename;
{ if (contents != null)
File.WriteAllText(_tempFile = Path.GetTempFileName(), contents, Encoding.ASCII); {
} File.WriteAllText(tempFile, contents, new UTF8Encoding(false));
}
}
public string TempPath { get { return _tempFile; } } public TempFile(string contents)
: this(Path.GetTempFileName(), contents)
{
}
public void ChangeExtension(string ext) public string TempPath { get { return tempFile; } }
{
string newFile = Path.ChangeExtension(_tempFile, ext);
File.Move(_tempFile, newFile);
_tempFile = newFile;
}
public void Dispose() public void ChangeExtension(string ext)
{ {
if(File.Exists(_tempFile)) string newFile = Path.ChangeExtension(tempFile, ext);
File.Delete(_tempFile); File.Move(tempFile, newFile);
} tempFile = newFile;
} }
public void Dispose()
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
} }
...@@ -40,381 +40,389 @@ using NUnit.Framework; ...@@ -40,381 +40,389 @@ using NUnit.Framework;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen
{ {
[TestFixture] [TestFixture]
[Category("Preprocessor")] [Category("Preprocessor")]
public partial class TestPreprocessing public partial class TestPreprocessing
{ {
private static readonly string TEMP = Path.Combine(Path.GetTempPath(), "proto-gen-test"); private static readonly string TempPath = Path.Combine(Path.GetTempPath(), "proto-gen-test");
private const string DEFAULT_PROTO = @" private const string DefaultProto = @"
package nunit.simple; package nunit.simple;
// Test a very simple message. // Test a very simple message.
message MyMessage { message MyMessage {
optional string name = 1; optional string name = 1;
}"; }";
#region TestFixture SetUp/TearDown #region TestFixture SetUp/TearDown
private string OriginalWorkingDirectory = Environment.CurrentDirectory; private static readonly string OriginalWorkingDirectory = Environment.CurrentDirectory;
[TestFixtureSetUp] [TestFixtureSetUp]
public virtual void Setup() public virtual void Setup()
{ {
Teardown(); Teardown();
Directory.CreateDirectory(TEMP); Directory.CreateDirectory(TempPath);
Environment.CurrentDirectory = TEMP; Environment.CurrentDirectory = TempPath;
} }
[TestFixtureTearDown] [TestFixtureTearDown]
public virtual void Teardown() public virtual void Teardown()
{ {
Environment.CurrentDirectory = OriginalWorkingDirectory; Environment.CurrentDirectory = OriginalWorkingDirectory;
if (Directory.Exists(TEMP)) if (Directory.Exists(TempPath))
Directory.Delete(TEMP, true); {
} Directory.Delete(TempPath, true);
#endregion }
#region Helper Methods RunProtoGen / RunCsc }
void RunProtoGen(int expect, params string[] args) #endregion
{ #region Helper Methods RunProtoGen / RunCsc
TextWriter tout = Console.Out, terr = Console.Error; void RunProtoGen(int expect, params string[] args)
StringWriter temp = new StringWriter(); {
Console.SetOut(temp); TextWriter tout = Console.Out, terr = Console.Error;
Console.SetError(temp); StringWriter temp = new StringWriter();
try Console.SetOut(temp);
{ Console.SetError(temp);
Assert.AreEqual(expect, ProgramPreprocess.Run(args), "ProtoGen Failed: {0}", temp); try
} {
finally Assert.AreEqual(expect, ProgramPreprocess.Run(args), "ProtoGen Failed: {0}", temp);
{ }
Console.SetOut(tout); finally
Console.SetError(terr); {
} Console.SetOut(tout);
} Console.SetError(terr);
}
}
private Assembly RunCsc(int expect, params string[] sources) private Assembly RunCsc(int expect, params string[] sources)
{ {
using (TempFile tempDll = new TempFile(String.Empty)) using (TempFile tempDll = new TempFile(String.Empty))
{ {
tempDll.ChangeExtension(".dll"); tempDll.ChangeExtension(".dll");
List<string> args = new List<string>(); List<string> args = new List<string>();
args.Add("/nologo"); args.Add("/nologo");
args.Add("/target:library"); args.Add("/target:library");
args.Add("/debug-"); args.Add("/debug-");
args.Add(String.Format(@"""/out:{0}""", tempDll.TempPath)); args.Add(String.Format(@"""/out:{0}""", tempDll.TempPath));
args.Add("/r:System.dll"); args.Add("/r:System.dll");
args.Add(String.Format(@"""/r:{0}""", typeof (Google.ProtocolBuffers.DescriptorProtos.DescriptorProto).Assembly.Location)); args.Add(String.Format(@"""/r:{0}""", typeof (Google.ProtocolBuffers.DescriptorProtos.DescriptorProto).Assembly.Location));
args.AddRange(sources); args.AddRange(sources);
string exe = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "csc.exe"); string exe = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "csc.exe");
ProcessStartInfo psi = new ProcessStartInfo(exe); ProcessStartInfo psi = new ProcessStartInfo(exe);
psi.CreateNoWindow = true; psi.CreateNoWindow = true;
psi.UseShellExecute = false; psi.UseShellExecute = false;
psi.RedirectStandardOutput = true; psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true; psi.RedirectStandardError = true;
psi.Arguments = string.Join(" ", args.ToArray()); psi.Arguments = string.Join(" ", args.ToArray());
Process p = Process.Start(psi); Process p = Process.Start(psi);
p.WaitForExit(); p.WaitForExit();
string errorText = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd(); string errorText = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
Assert.AreEqual(expect, p.ExitCode, "CSC.exe Failed: {0}", errorText); Assert.AreEqual(expect, p.ExitCode, "CSC.exe Failed: {0}", errorText);
Assembly asm = null; Assembly asm = null;
if (p.ExitCode == 0) if (p.ExitCode == 0)
{ {
byte[] allbytes = File.ReadAllBytes(tempDll.TempPath); byte[] allbytes = File.ReadAllBytes(tempDll.TempPath);
asm = Assembly.Load(allbytes); asm = Assembly.Load(allbytes);
foreach (Type t in asm.GetTypes()) foreach (Type t in asm.GetTypes())
Debug.WriteLine(t.FullName, asm.FullName); {
} Debug.WriteLine(t.FullName, asm.FullName);
return asm; }
} }
} return asm;
#endregion }
}
#endregion
// ******************************************************************* // *******************************************************************
// The following tests excercise options for protogen.exe // The following tests excercise options for protogen.exe
// ******************************************************************* // *******************************************************************
[Test] [Test]
public void TestProtoFile() public void TestProtoFile()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath); RunProtoGen(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithConflictingType() public void TestProtoFileWithConflictingType()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
package nunit.simple; package nunit.simple;
// Test a very simple message. // Test a very simple message.
message " + test + @" { message " + test + @" {
optional string name = 1; optional string name = 1;
} ")) } "))
{ {
RunProtoGen(0, proto.TempPath); RunProtoGen(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test, true, true); Type t = a.GetType("nunit.simple." + test, true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto." + test, true, true); a.GetType("nunit.simple.Proto." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithNamespace() public void TestProtoFileWithNamespace()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath, "-namespace:MyNewNamespace"); RunProtoGen(0, proto.TempPath, "-namespace:MyNewNamespace");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true); a.GetType("MyNewNamespace." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithUmbrellaClassName() public void TestProtoFileWithUmbrellaClassName()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach("MyUmbrellaClassname.cs")) using (TempFile source = TempFile.Attach("MyUmbrellaClassname.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath, "/umbrella_classname=MyUmbrellaClassname"); RunProtoGen(0, proto.TempPath, "/umbrella_classname=MyUmbrellaClassname");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrellaClassname", true, true); a.GetType("nunit.simple.MyUmbrellaClassname", true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithNestedClass() public void TestProtoFileWithNestedClass()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath, "-nest_classes:true"); RunProtoGen(0, proto.TempPath, "-nest_classes:true");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true); Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithExpandedNsDirectories() public void TestProtoFileWithExpandedNsDirectories()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(@"nunit\simple\" + test + ".cs")) using (TempFile source = TempFile.Attach(@"nunit\simple\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath, "-expand_namespace_directories:true"); RunProtoGen(0, proto.TempPath, "-expand_namespace_directories:true");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileDisablingClsComplianceFlags() public void TestProtoFileDisablingClsComplianceFlags()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
package nunit.simple; package nunit.simple;
// Test a very simple message. // Test a very simple message.
message MyMessage { message MyMessage {
optional uint32 name = 1; optional uint32 name = 1;
} ")) } "))
{ {
//CS3021: Warning as Error: xx does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute //CS3021: Warning as Error: xx does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute
RunProtoGen(0, proto.TempPath); RunProtoGen(0, proto.TempPath);
RunCsc(1, source.TempPath, "/warnaserror+"); RunCsc(1, source.TempPath, "/warnaserror+");
//Now we know it fails, make it pass by turning off cls_compliance generation //Now we know it fails, make it pass by turning off cls_compliance generation
RunProtoGen(0, proto.TempPath, "-cls_compliance:false"); RunProtoGen(0, proto.TempPath, "-cls_compliance:false");
Assembly a = RunCsc(0, source.TempPath, "/warnaserror+"); Assembly a = RunCsc(0, source.TempPath, "/warnaserror+");
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithNewExtension() public void TestProtoFileWithNewExtension()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".Generated.cs")) using (TempFile source = TempFile.Attach(test + ".Generated.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath, "-file_extension:.Generated.cs"); RunProtoGen(0, proto.TempPath, "-file_extension:.Generated.cs");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithUmbrellaNamespace() public void TestProtoFileWithUmbrellaNamespace()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath, "-umbrella_namespace:MyUmbrella.Namespace"); RunProtoGen(0, proto.TempPath, "-umbrella_namespace:MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrella.Namespace." + test, true, true); a.GetType("nunit.simple.MyUmbrella.Namespace." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithIgnoredUmbrellaNamespaceDueToNesting() public void TestProtoFileWithIgnoredUmbrellaNamespaceDueToNesting()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(0, proto.TempPath, "-nest_classes:true", "-umbrella_namespace:MyUmbrella.Namespace"); RunProtoGen(0, proto.TempPath, "-nest_classes:true", "-umbrella_namespace:MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true); Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithExplicitEmptyUmbrellaNamespace() public void TestProtoFileWithExplicitEmptyUmbrellaNamespace()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
package nunit.simple; package nunit.simple;
// Test a very simple message. // Test a very simple message.
message " + test + @" { message " + test + @" {
optional string name = 1; optional string name = 1;
} ")) } "))
{ {
//Forces the umbrella class to not use a namespace even if a collision with a type is detected. //Forces the umbrella class to not use a namespace even if a collision with a type is detected.
RunProtoGen(0, proto.TempPath, "-umbrella_namespace:"); RunProtoGen(0, proto.TempPath, "-umbrella_namespace:");
//error CS0441: 'nunit.simple.TestProtoFileWithExplicitEmptyUmbrellaNamespace': a class cannot be both static and sealed //error CS0441: 'nunit.simple.TestProtoFileWithExplicitEmptyUmbrellaNamespace': a class cannot be both static and sealed
RunCsc(1, source.TempPath); RunCsc(1, source.TempPath);
} }
} }
[Test] [Test]
public void TestProtoFileWithNewOutputFolder() public void TestProtoFileWithNewOutputFolder()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(@"generated-code\" + test + ".cs")) using (TempFile source = TempFile.Attach(@"generated-code\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
RunProtoGen(1, proto.TempPath, "-output_directory:generated-code"); RunProtoGen(1, proto.TempPath, "-output_directory:generated-code");
Directory.CreateDirectory("generated-code"); Directory.CreateDirectory("generated-code");
RunProtoGen(0, proto.TempPath, "-output_directory:generated-code"); RunProtoGen(0, proto.TempPath, "-output_directory:generated-code");
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileAndIgnoreGoogleProtobuf() public void TestProtoFileAndIgnoreGoogleProtobuf()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
import ""google/protobuf/csharp_options.proto""; import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" + DEFAULT_PROTO)) " + DefaultProto))
{ {
string google = Path.Combine(TEMP, "google\\protobuf"); string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google); Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
File.Copy(file, Path.Combine(google, Path.GetFileName(file))); {
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TEMP, "*.cs").Length); Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true"); RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true");
Assert.AreEqual(1, Directory.GetFiles(TEMP, "*.cs").Length); Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true); a.GetType("MyNewNamespace." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithoutIgnoreGoogleProtobuf() public void TestProtoFileWithoutIgnoreGoogleProtobuf()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
import ""google/protobuf/csharp_options.proto""; import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" + DEFAULT_PROTO)) " + DefaultProto))
{ {
string google = Path.Combine(TEMP, "google\\protobuf"); string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google); Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
File.Copy(file, Path.Combine(google, Path.GetFileName(file))); {
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TEMP, "*.cs").Length); Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//Without the option this fails due to being unable to resolve google/protobuf descriptors //Without the option this fails due to being unable to resolve google/protobuf descriptors
RunProtoGen(1, proto.TempPath, "-ignore_google_protobuf:false"); RunProtoGen(1, proto.TempPath, "-ignore_google_protobuf:false");
} }
} }
// ******************************************************************* // *******************************************************************
// The following tests excercise options for protoc.exe // The following tests excercise options for protoc.exe
// ******************************************************************* // *******************************************************************
[Test] [Test]
public void TestProtoFileWithIncludeImports() public void TestProtoFileWithIncludeImports()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
import ""google/protobuf/csharp_options.proto""; import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
...@@ -423,33 +431,35 @@ package nunit.simple; ...@@ -423,33 +431,35 @@ package nunit.simple;
message MyMessage { message MyMessage {
optional string name = 1; optional string name = 1;
} ")) } "))
{ {
string google = Path.Combine(TEMP, "google\\protobuf"); string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google); Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
File.Copy(file, Path.Combine(google, Path.GetFileName(file))); {
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TEMP, "*.cs").Length); Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//if you specify the protoc option --include_imports this should build three source files //if you specify the protoc option --include_imports this should build three source files
RunProtoGen(0, proto.TempPath, "--include_imports"); RunProtoGen(0, proto.TempPath, "--include_imports");
Assert.AreEqual(3, Directory.GetFiles(TEMP, "*.cs").Length); Assert.AreEqual(3, Directory.GetFiles(TempPath, "*.cs").Length);
//you can (and should) simply omit the inclusion of the extra source files in your project //you can (and should) simply omit the inclusion of the extra source files in your project
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true); a.GetType("MyNewNamespace." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileWithIncludeImportsAndIgnoreGoogleProtobuf() public void TestProtoFileWithIncludeImportsAndIgnoreGoogleProtobuf()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
import ""google/protobuf/csharp_options.proto""; import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
...@@ -458,143 +468,143 @@ package nunit.simple; ...@@ -458,143 +468,143 @@ package nunit.simple;
message MyMessage { message MyMessage {
optional string name = 1; optional string name = 1;
} ")) } "))
{ {
string google = Path.Combine(TEMP, "google\\protobuf"); string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google); Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
File.Copy(file, Path.Combine(google, Path.GetFileName(file))); File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
Assert.AreEqual(0, Directory.GetFiles(TEMP, "*.cs").Length); Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//Even with --include_imports, if you provide -ignore_google_protobuf:true you only get the one source file //Even with --include_imports, if you provide -ignore_google_protobuf:true you only get the one source file
RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "--include_imports"); RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "--include_imports");
Assert.AreEqual(1, Directory.GetFiles(TEMP, "*.cs").Length); Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
//you can (and should) simply omit the inclusion of the extra source files in your project //you can (and should) simply omit the inclusion of the extra source files in your project
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true); a.GetType("MyNewNamespace." + test, true, true);
} }
} }
[Test] [Test]
public void TestProtoFileKeepingTheProtoBuffer() public void TestProtoFileKeepingTheProtoBuffer()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile protobuf = TempFile.Attach(test + ".pb")) using (TempFile protobuf = TempFile.Attach(test + ".pb"))
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", @" using (ProtoFile proto = new ProtoFile(test + ".proto", @"
package nunit.simple; package nunit.simple;
// Test a very simple message. // Test a very simple message.
message MyMessage { message MyMessage {
optional string name = 1; optional string name = 1;
} ")) } "))
{ {
RunProtoGen(0, proto.TempPath, "--descriptor_set_out=" + protobuf.TempPath); RunProtoGen(0, proto.TempPath, "--descriptor_set_out=" + protobuf.TempPath);
Assert.IsTrue(File.Exists(protobuf.TempPath), "Missing: " + protobuf.TempPath); Assert.IsTrue(File.Exists(protobuf.TempPath), "Missing: " + protobuf.TempPath);
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
//Seems the --proto_path or -I option is non-functional for me. Maybe others have luck? //Seems the --proto_path or -I option is non-functional for me. Maybe others have luck?
[Test, Ignore("http://code.google.com/p/protobuf/issues/detail?id=40")] [Test, Ignore("http://code.google.com/p/protobuf/issues/detail?id=40")]
public void TestProtoFileInDifferentDirectory() public void TestProtoFileInDifferentDirectory()
{ {
string test = new StackFrame(false).GetMethod().Name; string test = new StackFrame(false).GetMethod().Name;
Setup(); Setup();
using (TempFile source = TempFile.Attach(test + ".cs")) using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DEFAULT_PROTO)) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{ {
Environment.CurrentDirectory = OriginalWorkingDirectory; Environment.CurrentDirectory = OriginalWorkingDirectory;
RunProtoGen(0, proto.TempPath, "--proto_path=" + TEMP); RunProtoGen(0, proto.TempPath, "--proto_path=" + TempPath);
Assembly a = RunCsc(0, source.TempPath); Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true); Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true); a.GetType("nunit.simple." + test, true, true);
} }
} }
// ******************************************************************* // *******************************************************************
// Handling of mutliple input files // Handling of mutliple input files
// ******************************************************************* // *******************************************************************
[Test] [Test]
public void TestMultipleProtoFiles() public void TestMultipleProtoFiles()
{ {
Setup(); Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs")) using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (ProtoFile proto1 = new ProtoFile("MyMessage.proto", @" using (ProtoFile proto1 = new ProtoFile("MyMessage.proto", @"
package nunit.simple; package nunit.simple;
// Test a very simple message. // Test a very simple message.
message MyMessage { message MyMessage {
optional string name = 1; optional string name = 1;
}")) }"))
using (TempFile source2 = TempFile.Attach("MyMessageList.cs")) using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (ProtoFile proto2 = new ProtoFile("MyMessageList.proto", @" using (ProtoFile proto2 = new ProtoFile("MyMessageList.proto", @"
package nunit.simple; package nunit.simple;
import ""MyMessage.proto""; import ""MyMessage.proto"";
// Test a very simple message. // Test a very simple message.
message MyMessageList { message MyMessageList {
repeated MyMessage messages = 1; repeated MyMessage messages = 1;
}")) }"))
{ {
RunProtoGen(0, proto1.TempPath, proto2.TempPath); RunProtoGen(0, proto1.TempPath, proto2.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath); Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true); Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true); Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true); a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true); a.GetType("nunit.simple.Proto.MyMessageList", true, true);
} }
} }
[Test] [Test]
public void TestOneProtoFileWithBufferFile() public void TestOneProtoFileWithBufferFile()
{ {
Setup(); Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs")) using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (TempFile protobuf = TempFile.Attach("MyMessage.pb")) using (TempFile protobuf = TempFile.Attach("MyMessage.pb"))
using (ProtoFile proto1 = new ProtoFile("MyMessage.proto", @" using (ProtoFile proto1 = new ProtoFile("MyMessage.proto", @"
package nunit.simple; package nunit.simple;
// Test a very simple message. // Test a very simple message.
message MyMessage { message MyMessage {
optional string name = 1; optional string name = 1;
}")) }"))
using (TempFile source2 = TempFile.Attach("MyMessageList.cs")) using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (ProtoFile proto2 = new ProtoFile("MyMessageList.proto", @" using (ProtoFile proto2 = new ProtoFile("MyMessageList.proto", @"
package nunit.simple; package nunit.simple;
import ""MyMessage.proto""; import ""MyMessage.proto"";
// Test a very simple message. // Test a very simple message.
message MyMessageList { message MyMessageList {
repeated MyMessage messages = 1; repeated MyMessage messages = 1;
}")) }"))
{ {
//build the proto buffer for MyMessage //build the proto buffer for MyMessage
RunProtoGen(0, proto1.TempPath, "--descriptor_set_out=" + protobuf.TempPath); RunProtoGen(0, proto1.TempPath, "--descriptor_set_out=" + protobuf.TempPath);
//build the MyMessageList proto-buffer and generate code by including MyMessage.pb //build the MyMessageList proto-buffer and generate code by including MyMessage.pb
RunProtoGen(0, proto2.TempPath, protobuf.TempPath); RunProtoGen(0, proto2.TempPath, protobuf.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath); Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true); Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace //assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true); Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage"); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type //assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true); a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true); a.GetType("nunit.simple.Proto.MyMessageList", true, true);
} }
} }
} }
} }
...@@ -45,24 +45,25 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -45,24 +45,25 @@ namespace Google.ProtocolBuffers.ProtoGen {
internal static string GetFullUmbrellaClassName(IDescriptor descriptor) { internal static string GetFullUmbrellaClassName(IDescriptor descriptor) {
CSharpFileOptions options = descriptor.File.CSharpOptions; CSharpFileOptions options = descriptor.File.CSharpOptions;
string result = options.Namespace; string result = options.Namespace;
if (result != "") result += '.'; if (result != "") {
result += QualifiedUmbrellaClassName(options); result += '.';
}
result += GetQualifiedUmbrellaClassName(options);
return "global::" + result; return "global::" + result;
} }
/// <summary> /// <summary>
/// ROK 2010-09-03
/// Evaluates the options and returns the qualified name of the umbrella class /// Evaluates the options and returns the qualified name of the umbrella class
/// relative to the descriptor type's namespace. Basically contacts the /// relative to the descriptor type's namespace. Basically concatenates the
/// UmbrellaNamespace + UmbrellaClassname fields. /// UmbrellaNamespace + UmbrellaClassname fields.
/// </summary> /// </summary>
internal static string QualifiedUmbrellaClassName(CSharpFileOptions options) internal static string GetQualifiedUmbrellaClassName(CSharpFileOptions options) {
{ string fullName = options.UmbrellaClassname;
string fullName = options.UmbrellaClassname; if (!options.NestClasses && options.UmbrellaNamespace != "") {
if (!options.NestClasses && options.UmbrellaNamespace != "") fullName = String.Format("{0}.{1}", options.UmbrellaNamespace, options.UmbrellaClassname);
fullName = String.Format("{0}.{1}", options.UmbrellaNamespace, options.UmbrellaClassname); }
return fullName; return fullName;
} }
internal static string GetMappedTypeName(MappedType type) { internal static string GetMappedTypeName(MappedType type) {
switch(type) { switch(type) {
......
...@@ -60,30 +60,30 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -60,30 +60,30 @@ namespace Google.ProtocolBuffers.ProtoGen {
} }
public void Generate() { public void Generate() {
List<FileDescriptorSet> descriptorProtos = new List<FileDescriptorSet>(); List<FileDescriptorSet> descriptorProtos = new List<FileDescriptorSet>();
foreach (string inputFile in options.InputFiles) { foreach (string inputFile in options.InputFiles) {
ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance(); ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
extensionRegistry.Add(CSharpOptions.CSharpFileOptions); extensionRegistry.Add(CSharpOptions.CSharpFileOptions);
extensionRegistry.Add(CSharpOptions.CSharpFieldOptions); extensionRegistry.Add(CSharpOptions.CSharpFieldOptions);
using (Stream inputStream = File.OpenRead(inputFile)) { using (Stream inputStream = File.OpenRead(inputFile)) {
descriptorProtos.Add(FileDescriptorSet.ParseFrom(inputStream, extensionRegistry)); descriptorProtos.Add(FileDescriptorSet.ParseFrom(inputStream, extensionRegistry));
} }
} }
IList<FileDescriptor> descriptors = ConvertDescriptors(options.FileOptions, descriptorProtos.ToArray()); IList<FileDescriptor> descriptors = ConvertDescriptors(options.FileOptions, descriptorProtos.ToArray());
//ROK Combine with Options... // Combine with options from command line
foreach (FileDescriptor descriptor in descriptors) foreach (FileDescriptor descriptor in descriptors) {
descriptor.ConfigureWithDefaultOptions(options.FileOptions); descriptor.ConfigureWithDefaultOptions(options.FileOptions);
}
foreach (FileDescriptor descriptor in descriptors) {
//ROK 2010-09-03 Ignore google protobuf package
if(descriptor.CSharpOptions.IgnoreGoogleProtobuf && descriptor.Package == "google.protobuf")
continue;
Generate(descriptor); foreach (FileDescriptor descriptor in descriptors) {
// Optionally exclude descriptors in google.protobuf
if (descriptor.CSharpOptions.IgnoreGoogleProtobuf && descriptor.Package == "google.protobuf") {
continue;
}
Generate(descriptor);
} }
} }
...@@ -102,13 +102,9 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -102,13 +102,9 @@ namespace Google.ProtocolBuffers.ProtoGen {
private string GetOutputFile(FileDescriptor descriptor) { private string GetOutputFile(FileDescriptor descriptor) {
CSharpFileOptions fileOptions = descriptor.CSharpOptions; CSharpFileOptions fileOptions = descriptor.CSharpOptions;
//ROK 2010-09-03 - added the ability to sepcify the extension used within the options string filename = descriptor.CSharpOptions.UmbrellaClassname + descriptor.CSharpOptions.FileExtension;
//string filename = descriptor.CSharpOptions.UmbrellaClassname + ".cs";
string filename = descriptor.CSharpOptions.UmbrellaClassname + descriptor.CSharpOptions.FileExtension;
//ROK 2010-09-03 - output directory can be specific to a descriptor file string outputDirectory = descriptor.CSharpOptions.OutputDirectory;
//string outputDirectory = options.OutputDirectory;
string outputDirectory = descriptor.CSharpOptions.OutputDirectory;
if (fileOptions.ExpandNamespaceDirectories) { if (fileOptions.ExpandNamespaceDirectories) {
string package = fileOptions.Namespace; string package = fileOptions.Namespace;
if (!string.IsNullOrEmpty(package)) { if (!string.IsNullOrEmpty(package)) {
...@@ -117,29 +113,25 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -117,29 +113,25 @@ namespace Google.ProtocolBuffers.ProtoGen {
outputDirectory = Path.Combine(outputDirectory, bit); outputDirectory = Path.Combine(outputDirectory, bit);
} }
} }
} }
//ROK 2010-09-03 - Always force output directory exists since they can specify this in .proto options
Directory.CreateDirectory(outputDirectory); // As the directory can be explicitly specified in options, we need to make sure it exists
Directory.CreateDirectory(outputDirectory);
return Path.Combine(outputDirectory, filename); return Path.Combine(outputDirectory, filename);
} }
// ROK 2010-09-03 - used by unit tests, we will continue to allow them to function as-is.
internal static IList<FileDescriptor> ConvertDescriptors(FileDescriptorSet descriptorProtos) {
return ConvertDescriptors(CSharpFileOptions.DefaultInstance, descriptorProtos);
}
/// <summary> /// <summary>
/// Resolves any dependencies and converts FileDescriptorProtos into FileDescriptors. /// Resolves any dependencies and converts FileDescriptorProtos into FileDescriptors.
/// The list returned is in the same order as the protos are listed in the descriptor set. /// The list returned is in the same order as the protos are listed in the descriptor set.
/// Note: this method is internal rather than private to allow testing. /// Note: this method is internal rather than private to allow testing.
/// </summary> /// </summary>
/// <exception cref="DependencyResolutionException">Not all dependencies could be resolved.</exception> /// <exception cref="DependencyResolutionException">Not all dependencies could be resolved.</exception>
private static IList<FileDescriptor> ConvertDescriptors(CSharpFileOptions options, params FileDescriptorSet[] descriptorProtos) { internal static IList<FileDescriptor> ConvertDescriptors(CSharpFileOptions options, params FileDescriptorSet[] descriptorProtos) {
// Simple strategy: Keep going through the list of protos to convert, only doing ones where // Simple strategy: Keep going through the list of protos to convert, only doing ones where
// we've already converted all the dependencies, until we get to a stalemate // we've already converted all the dependencies, until we get to a stalemate
List<FileDescriptorProto> fileList = new List<FileDescriptorProto>(); List<FileDescriptorProto> fileList = new List<FileDescriptorProto>();
foreach (FileDescriptorSet set in descriptorProtos) foreach (FileDescriptorSet set in descriptorProtos)
fileList.AddRange(set.FileList); fileList.AddRange(set.FileList);
FileDescriptor[] converted = new FileDescriptor[fileList.Count]; FileDescriptor[] converted = new FileDescriptor[fileList.Count];
...@@ -158,31 +150,28 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -158,31 +150,28 @@ namespace Google.ProtocolBuffers.ProtoGen {
FileDescriptorProto candidate = fileList[i]; FileDescriptorProto candidate = fileList[i];
FileDescriptor[] dependencies = new FileDescriptor[candidate.DependencyList.Count]; FileDescriptor[] dependencies = new FileDescriptor[candidate.DependencyList.Count];
CSharpFileOptions.Builder builder = options.ToBuilder(); CSharpFileOptions.Builder builder = options.ToBuilder();
if (candidate.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) { if (candidate.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) {
builder.MergeFrom(candidate.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)); builder.MergeFrom(candidate.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions));
} }
CSharpFileOptions localOptions = builder.Build(); CSharpFileOptions localOptions = builder.Build();
bool foundAllDependencies = true; bool foundAllDependencies = true;
for (int j = 0; j < dependencies.Length; j++) { for (int j = 0; j < dependencies.Length; j++) {
if (!convertedMap.TryGetValue(candidate.DependencyList[j], out dependencies[j])) { if (!convertedMap.TryGetValue(candidate.DependencyList[j], out dependencies[j])) {
// We can auto-magically resolve these since we already have their description
// ROK 2010-09-03 - we can auto-magically resolve these since we already have their description // This way if the file is only referencing options it does not need to be built with the
// This way if the file is only referencing options it does not need to be built with the // --include_imports definition.
// --include_imports definition. if (localOptions.IgnoreGoogleProtobuf && (candidate.DependencyList[j] == "google/protobuf/csharp_options.proto")) {
if (localOptions.IgnoreGoogleProtobuf && (candidate.DependencyList[j] == "google/protobuf/csharp_options.proto")) dependencies[j] = CSharpOptions.Descriptor;
{ continue;
dependencies[j] = CSharpOptions.Descriptor; }
continue; if (localOptions.IgnoreGoogleProtobuf && (candidate.DependencyList[j] == "google/protobuf/descriptor.proto")) {
} dependencies[j] = DescriptorProtoFile.Descriptor;
if (localOptions.IgnoreGoogleProtobuf && (candidate.DependencyList[j] == "google/protobuf/descriptor.proto")) continue;
{ }
dependencies[j] = DescriptorProtoFile.Descriptor; foundAllDependencies = false;
continue;
}
foundAllDependencies = false;
break; break;
} }
} }
......
#region Copyright notice and license #region Copyright notice and license
// Protocol Buffers - Google's data interchange format // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved. // Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/ // http://github.com/jskeet/dotnet-protobufs/
...@@ -30,6 +31,7 @@ ...@@ -30,6 +31,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion #endregion
using System; using System;
...@@ -40,7 +42,6 @@ using Google.ProtocolBuffers.DescriptorProtos; ...@@ -40,7 +42,6 @@ using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen { namespace Google.ProtocolBuffers.ProtoGen {
/// <summary> /// <summary>
/// All the configuration required for the generator - where to generate /// All the configuration required for the generator - where to generate
/// output files, the location of input files etc. While this isn't immutable /// output files, the location of input files etc. While this isn't immutable
...@@ -48,7 +49,6 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -48,7 +49,6 @@ namespace Google.ProtocolBuffers.ProtoGen {
/// the generator. /// the generator.
/// </summary> /// </summary>
public sealed class GeneratorOptions { public sealed class GeneratorOptions {
//ROK, see below - public string OutputDirectory { get; set; }
public IList<string> InputFiles { get; set; } public IList<string> InputFiles { get; set; }
/// <summary> /// <summary>
...@@ -61,13 +61,13 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -61,13 +61,13 @@ namespace Google.ProtocolBuffers.ProtoGen {
public bool TryValidate(out IList<string> reasons) { public bool TryValidate(out IList<string> reasons) {
List<string> tmpReasons = new List<string>(); List<string> tmpReasons = new List<string>();
//ROK 2010-09-03 see population of options below ParseArguments(tmpReasons);
ParseArguments(tmpReasons);
// Output directory validation // Output directory validation
if (string.IsNullOrEmpty(FileOptions.OutputDirectory)) { if (string.IsNullOrEmpty(FileOptions.OutputDirectory)) {
tmpReasons.Add("No output directory specified"); tmpReasons.Add("No output directory specified");
} else { }
else {
if (!Directory.Exists(FileOptions.OutputDirectory)) { if (!Directory.Exists(FileOptions.OutputDirectory)) {
tmpReasons.Add("Specified output directory (" + FileOptions.OutputDirectory + " doesn't exist."); tmpReasons.Add("Specified output directory (" + FileOptions.OutputDirectory + " doesn't exist.");
} }
...@@ -76,7 +76,8 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -76,7 +76,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
// Input file validation (just in terms of presence) // Input file validation (just in terms of presence)
if (InputFiles == null || InputFiles.Count == 0) { if (InputFiles == null || InputFiles.Count == 0) {
tmpReasons.Add("No input files specified"); tmpReasons.Add("No input files specified");
} else { }
else {
foreach (string input in InputFiles) { foreach (string input in InputFiles) {
FileInfo fi = new FileInfo(input); FileInfo fi = new FileInfo(input);
if (!fi.Exists) { if (!fi.Exists) {
...@@ -106,178 +107,160 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -106,178 +107,160 @@ namespace Google.ProtocolBuffers.ProtoGen {
} }
} }
// Raw arguments, used to provide defaults for proto file options
public IList<string> Arguments { get; set; }
[Obsolete("Please use GeneratorOptions.FileOptions.OutputDirectory instead")]
public string OutputDirectory {
get { return FileOptions.OutputDirectory; }
set {
CSharpFileOptions.Builder bld = FileOptions.ToBuilder();
bld.OutputDirectory = value;
FileOptions = bld.Build();
}
}
private static readonly Regex ArgMatch = new Regex(@"^[-/](?<name>[\w_]+?)[:=](?<value>.*)$");
private CSharpFileOptions fileOptions;
public CSharpFileOptions FileOptions {
get { return fileOptions ?? (fileOptions = CSharpFileOptions.DefaultInstance); }
set { fileOptions = value; }
}
private void ParseArguments(IList<string> tmpReasons) {
bool doHelp = Arguments.Count == 0;
// ROK - added to provide defaults for any of the options InputFiles = new List<string>();
//Raw arguments CSharpFileOptions.Builder builder = FileOptions.ToBuilder();
public IList<string> Arguments { get; set; } Dictionary<string, FieldDescriptor> fields =
[Obsolete("Please use GeneratorOptions.FileOptions.OutputDirectory instead")] new Dictionary<string, FieldDescriptor>(StringComparer.OrdinalIgnoreCase);
public string OutputDirectory foreach (FieldDescriptor fld in builder.DescriptorForType.Fields) {
{ fields.Add(fld.Name, fld);
get { }
return FileOptions.OutputDirectory;
} foreach (string argument in Arguments) {
set { if (StringComparer.OrdinalIgnoreCase.Equals("-help", argument) ||
CSharpFileOptions.Builder bld = FileOptions.ToBuilder(); StringComparer.OrdinalIgnoreCase.Equals("/help", argument) ||
bld.OutputDirectory = value; StringComparer.OrdinalIgnoreCase.Equals("-?", argument) ||
FileOptions = bld.Build(); StringComparer.OrdinalIgnoreCase.Equals("/?", argument)) {
} doHelp = true;
} break;
}
private static readonly Regex ArgMatch = new Regex(@"^[-/](?<name>[\w_]+?)[:=](?<value>.*)$");
CSharpFileOptions _fileOptions;
public CSharpFileOptions FileOptions
{
get { return _fileOptions ?? (_fileOptions = CSharpFileOptions.DefaultInstance); }
set { _fileOptions = value; }
}
private void ParseArguments(IList<string> tmpReasons)
{
bool doHelp = Arguments.Count == 0;
//ROK Parse the raw arguments
InputFiles = new List<string>();
CSharpFileOptions.Builder builder = FileOptions.ToBuilder();
Dictionary<string, FieldDescriptor> fields =
new Dictionary<string, FieldDescriptor>(StringComparer.OrdinalIgnoreCase);
foreach (FieldDescriptor fld in builder.DescriptorForType.Fields)
fields.Add(fld.Name, fld);
foreach (string argument in Arguments)
{
if (StringComparer.OrdinalIgnoreCase.Equals("-help", argument) ||
StringComparer.OrdinalIgnoreCase.Equals("/help", argument) ||
StringComparer.OrdinalIgnoreCase.Equals("-?", argument) ||
StringComparer.OrdinalIgnoreCase.Equals("/?", argument))
{
doHelp = true;
break;
}
Match m = ArgMatch.Match(argument);
if (m.Success)
{
FieldDescriptor fld;
string name = m.Groups["name"].Value;
string value = m.Groups["value"].Value;
if (fields.TryGetValue(name, out fld))
{
object obj;
if (TryCoerceType(value, fld, out obj, tmpReasons))
builder[fld] = obj;
}
else if (!File.Exists(argument))
{
doHelp = true;
tmpReasons.Add("Unknown argument '" + name + "'.");
}
else
InputFiles.Add(argument);
}
else
InputFiles.Add(argument);
}
if (doHelp || InputFiles.Count == 0)
{
tmpReasons.Add("Arguments:");
foreach (KeyValuePair<string, FieldDescriptor> field in fields)
{
tmpReasons.Add(String.Format("-{0}=[{1}]", field.Key, field.Value.FieldType));
}
tmpReasons.Add("followed by one or more file paths.");
}
else
FileOptions = builder.Build();
}
private static bool TryCoerceType(string text, FieldDescriptor field, out object value, IList<string> tmpReasons)
{
value = null;
switch (field.FieldType)
{
case FieldType.Int32:
case FieldType.SInt32:
case FieldType.SFixed32:
value = Int32.Parse(text);
break;
case FieldType.Int64:
case FieldType.SInt64:
case FieldType.SFixed64:
value = Int64.Parse(text);
break;
case FieldType.UInt32:
case FieldType.Fixed32:
value = UInt32.Parse(text);
break;
case FieldType.UInt64:
case FieldType.Fixed64:
value = UInt64.Parse(text);
break;
case FieldType.Float:
value = float.Parse(text);
break;
case FieldType.Double:
value = Double.Parse(text);
break;
case FieldType.Bool:
value = Boolean.Parse(text);
break;
case FieldType.String:
value = text;
break;
case FieldType.Enum:
{
EnumDescriptor enumType = field.EnumType;
int number;
if (int.TryParse(text, out number))
{
value = enumType.FindValueByNumber(number);
if (value == null)
{
tmpReasons.Add(
"Enum type \"" + enumType.FullName +
"\" has no value with number " + number + ".");
return false;
}
}
else
{
value = enumType.FindValueByName(text);
if (value == null)
{
tmpReasons.Add(
"Enum type \"" + enumType.FullName +
"\" has no value named \"" + text + "\".");
return false;
}
}
break;
}
case FieldType.Bytes:
case FieldType.Message:
case FieldType.Group:
tmpReasons.Add("Unhandled field type " + field.FieldType.ToString() + ".");
return false;
}
return true;
}
Match m = ArgMatch.Match(argument);
if (m.Success) {
FieldDescriptor fld;
string name = m.Groups["name"].Value;
string value = m.Groups["value"].Value;
if (fields.TryGetValue(name, out fld)) {
object obj;
if (TryCoerceType(value, fld, out obj, tmpReasons)) {
builder[fld] = obj;
}
}
else if (!File.Exists(argument)) {
doHelp = true;
tmpReasons.Add("Unknown argument '" + name + "'.");
}
else {
InputFiles.Add(argument);
}
}
else {
InputFiles.Add(argument);
}
}
if (doHelp || InputFiles.Count == 0) {
tmpReasons.Add("Arguments:");
foreach (KeyValuePair<string, FieldDescriptor> field in fields) {
tmpReasons.Add(String.Format("-{0}=[{1}]", field.Key, field.Value.FieldType));
}
tmpReasons.Add("followed by one or more file paths.");
}
else {
FileOptions = builder.Build();
}
}
private static bool TryCoerceType(string text, FieldDescriptor field, out object value, IList<string> tmpReasons) {
value = null;
switch (field.FieldType) {
case FieldType.Int32:
case FieldType.SInt32:
case FieldType.SFixed32:
value = Int32.Parse(text);
break;
case FieldType.Int64:
case FieldType.SInt64:
case FieldType.SFixed64:
value = Int64.Parse(text);
break;
case FieldType.UInt32:
case FieldType.Fixed32:
value = UInt32.Parse(text);
break;
case FieldType.UInt64:
case FieldType.Fixed64:
value = UInt64.Parse(text);
break;
case FieldType.Float:
value = float.Parse(text);
break;
case FieldType.Double:
value = Double.Parse(text);
break;
case FieldType.Bool:
value = Boolean.Parse(text);
break;
case FieldType.String:
value = text;
break;
case FieldType.Enum: {
EnumDescriptor enumType = field.EnumType;
int number;
if (int.TryParse(text, out number)) {
value = enumType.FindValueByNumber(number);
if (value == null) {
tmpReasons.Add(
"Enum type \"" + enumType.FullName +
"\" has no value with number " + number + ".");
return false;
}
}
else {
value = enumType.FindValueByName(text);
if (value == null) {
tmpReasons.Add(
"Enum type \"" + enumType.FullName +
"\" has no value named \"" + text + "\".");
return false;
}
}
break;
}
case FieldType.Bytes:
case FieldType.Message:
case FieldType.Group:
tmpReasons.Add("Unhandled field type " + field.FieldType.ToString() + ".");
return false;
}
return true;
}
} }
} }
\ No newline at end of file
#region Copyright notice and license #region Copyright notice and license
// Protocol Buffers - Google's data interchange format // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved. // Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/ // http://github.com/jskeet/dotnet-protobufs/
...@@ -30,6 +31,7 @@ ...@@ -30,6 +31,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion #endregion
using System; using System;
...@@ -40,12 +42,12 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -40,12 +42,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
/// <summary> /// <summary>
/// Entry point for the Protocol Buffers generator. /// Entry point for the Protocol Buffers generator.
/// </summary> /// </summary>
class Program { internal class Program {
internal static int Main(string[] args) { internal static int Main(string[] args) {
try { try {
// Hack to make sure everything's initialized // Hack to make sure everything's initialized
DescriptorProtoFile.Descriptor.ToString(); DescriptorProtoFile.Descriptor.ToString();
GeneratorOptions options = ParseCommandLineArguments(args); GeneratorOptions options = new GeneratorOptions {Arguments = args};
IList<string> validationFailures; IList<string> validationFailures;
if (!options.TryValidate(out validationFailures)) { if (!options.TryValidate(out validationFailures)) {
...@@ -58,25 +60,13 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -58,25 +60,13 @@ namespace Google.ProtocolBuffers.ProtoGen {
Generator generator = Generator.CreateGenerator(options); Generator generator = Generator.CreateGenerator(options);
generator.Generate(); generator.Generate();
return 0; return 0;
} catch (Exception e) { }
catch (Exception e) {
Console.Error.WriteLine("Error: {0}", e.Message); Console.Error.WriteLine("Error: {0}", e.Message);
Console.Error.WriteLine(); Console.Error.WriteLine();
Console.Error.WriteLine("Detailed exception information: {0}", e); Console.Error.WriteLine("Detailed exception information: {0}", e);
return 1; return 1;
} }
} }
private static GeneratorOptions ParseCommandLineArguments(string[] args) {
GeneratorOptions options = new GeneratorOptions();
//string baseDir = "c:\\Users\\Jon\\Documents\\Visual Studio 2008\\Projects\\ProtocolBuffers";
//options.OutputDirectory = baseDir + "\\tmp";
//options.InputFiles = new[] { baseDir + "\\protos\\nwind-solo.protobin" };
//ROK 2010-09-03 - fixes to allow parsing these options...
//options.OutputDirectory = ".";
//options.InputFiles = args;
options.Arguments = args;
return options;
}
} }
} }
\ No newline at end of file
...@@ -3,148 +3,151 @@ using System.Collections.Generic; ...@@ -3,148 +3,151 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers.ProtoGen namespace Google.ProtocolBuffers.ProtoGen {
{ /// <summary>
/// <summary> /// Preprocesses any input files with an extension of '.proto' by running protoc.exe. If arguments
/// Preprocesses any input files with an extension of '.proto' by running protoc.exe. If arguments /// are supplied with '--' prefix they are provided to protoc.exe, otherwise they are assumed to
/// are supplied with '--' prefix they are provided to protoc.exe, otherwise they are assumed to /// be used for ProtoGen.exe which is run on the resulting output proto buffer. If the option
/// be used for ProtoGen.exe which is run on the resulting output proto buffer. If the option /// --descriptor_set_out= is specified the proto buffer file is kept, otherwise it will be removed
/// --descriptor_set_out= is specified the proto buffer file is kept, otherwise it will be removed /// after code generation.
/// after code generation. /// </summary>
/// </summary> internal class ProgramPreprocess {
internal class ProgramPreprocess private static int Main(string[] args) {
{ try {
static int Main(string[] args) return Environment.ExitCode = Run(args);
{ }
try catch (Exception ex) {
{ Console.Error.WriteLine(ex);
return Environment.ExitCode = Run(args); return Environment.ExitCode = 2;
} }
catch (Exception ex) }
{
Console.Error.WriteLine(ex); internal static int Run(params string[] args) {
return Environment.ExitCode = 2; bool deleteFile = false;
} string tempFile = null;
int result;
bool doHelp = args.Length == 0;
try {
List<string> protocArgs = new List<string>();
List<string> protoGenArgs = new List<string>();
foreach (string arg in args) {
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "/?");
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "/help");
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "-?");
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "-help");
if (arg.StartsWith("--descriptor_set_out=")) {
tempFile = arg.Substring("--descriptor_set_out=".Length);
protoGenArgs.Add(tempFile);
}
} }
internal static int Run(params string[] args) if (doHelp) {
{ Console.WriteLine();
bool deleteFile = false; Console.WriteLine("PROTOC.exe: Use any of the following options that begin with '--':");
string tempFile = null; Console.WriteLine();
int result = 1; try {
bool doHelp = args.Length == 0; RunProtoc("--help");
try }
{ catch (Exception ex) {
List<string> protocArgs = new List<string>(); Console.Error.WriteLine(ex.Message);
List<string> protoGenArgs = new List<string>(); }
Console.WriteLine();
foreach (string arg in args) Console.WriteLine();
{ Console.WriteLine("PRTOGEN.exe: The following options are used to specify defaults for code generation.");
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "/?"); Console.WriteLine();
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "/help"); Program.Main(new string[0]);
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "-?"); return 0;
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "-help"); }
if(arg.StartsWith("--descriptor_set_out=")) foreach (string arg in args) {
{ if (arg.StartsWith("--")) {
tempFile = arg.Substring("--descriptor_set_out=".Length); protocArgs.Add(arg);
protoGenArgs.Add(tempFile); }
} else if (File.Exists(arg) && StringComparer.OrdinalIgnoreCase.Equals(".proto", Path.GetExtension(arg))) {
} if (tempFile == null) {
deleteFile = true;
if (doHelp) tempFile = Path.GetTempFileName();
{ protocArgs.Add(String.Format("--descriptor_set_out={0}", tempFile));
Console.WriteLine(); protoGenArgs.Add(tempFile);
Console.WriteLine("PROTOC.exe: Use any of the following options that begin with '--':");
Console.WriteLine();
try { RunProtoc("--help"); }
catch (Exception ex) { Console.Error.WriteLine(ex.Message); }
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("PRTOGEN.exe: The following options are used to specify defaults for code generation.");
Console.WriteLine();
Program.Main(new string[0]);
return 0;
}
foreach (string arg in args)
{
if (arg.StartsWith("--"))
protocArgs.Add(arg);
else if (File.Exists(arg) && StringComparer.OrdinalIgnoreCase.Equals(".proto", Path.GetExtension(arg)))
{
if (tempFile == null)
{
deleteFile = true;
tempFile = Path.GetTempFileName();
protocArgs.Add(String.Format("--descriptor_set_out={0}", tempFile));
protoGenArgs.Add(tempFile);
}
protocArgs.Add(arg);
}
else
protoGenArgs.Add(arg);
}
if (tempFile != null)
{
result = RunProtoc(protocArgs.ToArray());
if (result != 0)
return result;
}
result = Program.Main(protoGenArgs.ToArray());
}
finally
{
if (deleteFile && tempFile != null && File.Exists(tempFile))
File.Delete(tempFile);
} }
protocArgs.Add(arg);
}
else {
protoGenArgs.Add(arg);
}
}
if (tempFile != null) {
result = RunProtoc(protocArgs.ToArray());
if (result != 0) {
return result; return result;
}
} }
private static int RunProtoc(params string[] args) result = Program.Main(protoGenArgs.ToArray());
{ }
const string protoc = "protoc.exe"; finally {
string exePath = protoc; if (deleteFile && tempFile != null && File.Exists(tempFile)) {
File.Delete(tempFile);
//why oh why is this not in System.IO.Path or Environment... }
List<string> searchPath = new List<string>(); }
searchPath.Add(Environment.CurrentDirectory); return result;
searchPath.Add(AppDomain.CurrentDomain.BaseDirectory); }
searchPath.AddRange((Environment.GetEnvironmentVariable("PATH") ?? String.Empty).Split(Path.PathSeparator));
private static int RunProtoc(params string[] args) {
foreach (string path in searchPath) const string protoc = "protoc.exe";
if (File.Exists(exePath = Path.Combine(path, protoc))) string exePath = protoc;
break;
// Why oh why is this not in System.IO.Path or Environment...?
if (!File.Exists(exePath)) List<string> searchPath = new List<string>();
throw new FileNotFoundException("Unable to locate " + protoc + " make sure it is in the PATH, cwd, or exe dir."); searchPath.Add(Environment.CurrentDirectory);
searchPath.Add(AppDomain.CurrentDomain.BaseDirectory);
for (int i = 0; i < args.Length; i++) searchPath.AddRange((Environment.GetEnvironmentVariable("PATH") ?? String.Empty).Split(Path.PathSeparator));
if (args[i].IndexOf(' ') > 0 && args[i][0] != '"')
args[i] = '"' + args[i] + '"'; foreach (string path in searchPath) {
if (File.Exists(exePath = Path.Combine(path, protoc))) {
ProcessStartInfo psi = new ProcessStartInfo(exePath); break;
psi.Arguments = String.Join(" ", args); }
psi.RedirectStandardError = true; }
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true; if (!File.Exists(exePath)) {
psi.ErrorDialog = false; throw new FileNotFoundException("Unable to locate " + protoc + " make sure it is in the PATH, cwd, or exe dir.");
psi.CreateNoWindow = true; }
psi.UseShellExecute = false;
psi.WorkingDirectory = Environment.CurrentDirectory; for (int i = 0; i < args.Length; i++) {
if (args[i].IndexOf(' ') > 0 && args[i][0] != '"') {
Process process = Process.Start(psi); args[i] = '"' + args[i] + '"';
if (process == null) return 1;
process.WaitForExit();
string tmp = process.StandardOutput.ReadToEnd();
if(tmp.Trim().Length > 0) Console.Out.WriteLine(tmp);
tmp = process.StandardError.ReadToEnd();
if (tmp.Trim().Length > 0) Console.Error.WriteLine(tmp);
return process.ExitCode;
} }
}
ProcessStartInfo psi = new ProcessStartInfo(exePath);
psi.Arguments = String.Join(" ", args);
psi.RedirectStandardError = true;
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.ErrorDialog = false;
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = Environment.CurrentDirectory;
Process process = Process.Start(psi);
if (process == null) {
return 1;
}
process.WaitForExit();
string tmp = process.StandardOutput.ReadToEnd();
if (tmp.Trim().Length > 0) {
Console.Out.WriteLine(tmp);
}
tmp = process.StandardError.ReadToEnd();
if (tmp.Trim().Length > 0) {
Console.Error.WriteLine(tmp);
}
return process.ExitCode;
} }
}
} }
...@@ -61,7 +61,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -61,7 +61,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(); writer.WriteLine();
writer.WriteLine("{0} static pbd::ServiceDescriptor Descriptor {{", ClassAccessLevel); writer.WriteLine("{0} static pbd::ServiceDescriptor Descriptor {{", ClassAccessLevel);
writer.WriteLine(" get {{ return {0}.Descriptor.Services[{1}]; }}", writer.WriteLine(" get {{ return {0}.Descriptor.Services[{1}]; }}",
DescriptorUtil.QualifiedUmbrellaClassName(Descriptor.File.CSharpOptions), Descriptor.Index); DescriptorUtil.GetQualifiedUmbrellaClassName(Descriptor.File.CSharpOptions), Descriptor.Index);
writer.WriteLine("}"); writer.WriteLine("}");
writer.WriteLine("{0} pbd::ServiceDescriptor DescriptorForType {{", ClassAccessLevel); writer.WriteLine("{0} pbd::ServiceDescriptor DescriptorForType {{", ClassAccessLevel);
writer.WriteLine(" get { return Descriptor; }"); writer.WriteLine(" get { return Descriptor; }");
......
...@@ -93,12 +93,12 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -93,12 +93,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
//ROK 2010-09-03 - close the namespace around the umbrella class if defined // Close the namespace around the umbrella class if defined
if (!Descriptor.CSharpOptions.NestClasses && Descriptor.CSharpOptions.UmbrellaNamespace != "") { if (!Descriptor.CSharpOptions.NestClasses && Descriptor.CSharpOptions.UmbrellaNamespace != "") {
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); writer.WriteLine("}");
} }
} }
WriteChildren(writer, "Enums", Descriptor.EnumTypes); WriteChildren(writer, "Enums", Descriptor.EnumTypes);
WriteChildren(writer, "Messages", Descriptor.MessageTypes); WriteChildren(writer, "Messages", Descriptor.MessageTypes);
WriteChildren(writer, "Services", Descriptor.Services); WriteChildren(writer, "Services", Descriptor.Services);
...@@ -122,12 +122,12 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -122,12 +122,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.Indent(); writer.Indent();
writer.WriteLine(); writer.WriteLine();
} }
//ROK 2010-09-03 - add the namespace around the umbrella class if defined // Add the namespace around the umbrella class if defined
if(!Descriptor.CSharpOptions.NestClasses && Descriptor.CSharpOptions.UmbrellaNamespace != "") { if(!Descriptor.CSharpOptions.NestClasses && Descriptor.CSharpOptions.UmbrellaNamespace != "") {
writer.WriteLine("namespace {0} {{", Descriptor.CSharpOptions.UmbrellaNamespace); writer.WriteLine("namespace {0} {{", Descriptor.CSharpOptions.UmbrellaNamespace);
writer.Indent(); writer.Indent();
writer.WriteLine(); writer.WriteLine();
} }
if (Descriptor.CSharpOptions.CodeContracts) { if (Descriptor.CSharpOptions.CodeContracts) {
writer.WriteLine("[global::System.Diagnostics.Contracts.ContractVerificationAttribute(false)]"); writer.WriteLine("[global::System.Diagnostics.Contracts.ContractVerificationAttribute(false)]");
......
...@@ -76,7 +76,7 @@ namespace Google.ProtocolBuffers { ...@@ -76,7 +76,7 @@ namespace Google.ProtocolBuffers {
public void DynamicMessageSettersRejectNull() { public void DynamicMessageSettersRejectNull() {
IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.AssertReflectionSettersRejectNull(builder); reflectionTester.AssertReflectionSettersRejectNull(builder);
} }
[Test] [Test]
public void DynamicMessageExtensionAccessors() { public void DynamicMessageExtensionAccessors() {
...@@ -93,7 +93,7 @@ namespace Google.ProtocolBuffers { ...@@ -93,7 +93,7 @@ namespace Google.ProtocolBuffers {
public void DynamicMessageExtensionSettersRejectNull() { public void DynamicMessageExtensionSettersRejectNull() {
IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor); IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor);
extensionsReflectionTester.AssertReflectionSettersRejectNull(builder); extensionsReflectionTester.AssertReflectionSettersRejectNull(builder);
} }
[Test] [Test]
public void DynamicMessageRepeatedSetters() { public void DynamicMessageRepeatedSetters() {
......
...@@ -32,17 +32,17 @@ ...@@ -32,17 +32,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.IO;
using Google.ProtocolBuffers.DescriptorProtos; using Google.ProtocolBuffers.DescriptorProtos;
using FileOptions = Google.ProtocolBuffers.DescriptorProtos.FileOptions;
namespace Google.ProtocolBuffers.Descriptors { namespace Google.ProtocolBuffers.Descriptors {
/// <summary> /// <summary>
/// Describes a .proto file, including everything defined within. /// Describes a .proto file, including everything defined within.
/// IDescriptor is implemented such that the File property returns this descriptor, /// IDescriptor is implemented such that the File property returns this descriptor,
/// and the FullName is the same as the Name. /// and the FullName is the same as the Name.
/// </summary> /// </summary>
public sealed class FileDescriptor : IDescriptor<FileDescriptorProto> { public sealed class FileDescriptor : IDescriptor<FileDescriptorProto> {
private FileDescriptorProto proto; private FileDescriptorProto proto;
private readonly IList<MessageDescriptor> messageTypes; private readonly IList<MessageDescriptor> messageTypes;
private readonly IList<EnumDescriptor> enumTypes; private readonly IList<EnumDescriptor> enumTypes;
...@@ -52,7 +52,7 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -52,7 +52,7 @@ namespace Google.ProtocolBuffers.Descriptors {
private readonly DescriptorPool pool; private readonly DescriptorPool pool;
private CSharpFileOptions csharpFileOptions; private CSharpFileOptions csharpFileOptions;
private readonly object optionsLock = new object(); private readonly object optionsLock = new object();
private FileDescriptor(FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool) { private FileDescriptor(FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool) {
this.pool = pool; this.pool = pool;
this.proto = proto; this.proto = proto;
...@@ -60,49 +60,60 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -60,49 +60,60 @@ namespace Google.ProtocolBuffers.Descriptors {
pool.AddPackage(Package, this); pool.AddPackage(Package, this);
messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageTypeList, messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageTypeList,
(message, index) => new MessageDescriptor(message, this, null, index)); (message, index) =>
new MessageDescriptor(message, this, null, index));
enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumTypeList, enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumTypeList,
(enumType, index) => new EnumDescriptor(enumType, this, null, index)); (enumType, index) =>
new EnumDescriptor(enumType, this, null, index));
services = DescriptorUtil.ConvertAndMakeReadOnly(proto.ServiceList, services = DescriptorUtil.ConvertAndMakeReadOnly(proto.ServiceList,
(service, index) => new ServiceDescriptor(service, this, index)); (service, index) => new ServiceDescriptor(service, this, index));
extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.ExtensionList, extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.ExtensionList,
(field, index) => new FieldDescriptor(field, this, null, index, true)); (field, index) =>
new FieldDescriptor(field, this, null, index, true));
} }
/// <summary> /// <summary>
/// ROK - Added to allow the GeneratorOptions to sepcify the default for any or all of these values /// Allows a file descriptor to be configured with a set of external options, e.g. from the
/// </summary> /// command-line arguments to protogen.
internal void ConfigureWithDefaultOptions(CSharpFileOptions options) /// </summary>
{ internal void ConfigureWithDefaultOptions(CSharpFileOptions options) {
csharpFileOptions = BuildOrFakeWithDefaultOptions(options); csharpFileOptions = BuildOrFakeWithDefaultOptions(options);
} }
private CSharpFileOptions BuildOrFakeWithDefaultOptions(CSharpFileOptions defaultOptions)
{ private CSharpFileOptions BuildOrFakeWithDefaultOptions(CSharpFileOptions defaultOptions) {
// ROK 2010-09-03 - fix for being able to relocate these files to any directory structure // Fix for being able to relocate these files to any directory structure
if(proto.Package == "google.protobuf") { if (proto.Package == "google.protobuf") {
string filename = System.IO.Path.GetFileName(proto.Name); string filename = Path.GetFileName(proto.Name);
// TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues) // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues)
if (filename == "descriptor.proto") { if (filename == "descriptor.proto") {
return new CSharpFileOptions.Builder { return new CSharpFileOptions.Builder {
Namespace = "Google.ProtocolBuffers.DescriptorProtos", Namespace = "Google.ProtocolBuffers.DescriptorProtos",
UmbrellaClassname = "DescriptorProtoFile", NestClasses = false, MultipleFiles = false, PublicClasses = true, UmbrellaClassname = "DescriptorProtoFile",
OutputDirectory = defaultOptions.OutputDirectory, IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf NestClasses = false,
}.Build(); MultipleFiles = false,
} PublicClasses = true,
if (filename == "csharp_options.proto") { OutputDirectory = defaultOptions.OutputDirectory,
return new CSharpFileOptions.Builder { IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf
Namespace = "Google.ProtocolBuffers.DescriptorProtos", }.Build();
UmbrellaClassname = "CSharpOptions", NestClasses = false, MultipleFiles = false, PublicClasses = true, }
OutputDirectory = defaultOptions.OutputDirectory, IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf if (filename == "csharp_options.proto") {
}.Build(); return new CSharpFileOptions.Builder {
} Namespace = "Google.ProtocolBuffers.DescriptorProtos",
} UmbrellaClassname = "CSharpOptions",
CSharpFileOptions.Builder builder = defaultOptions.ToBuilder(); NestClasses = false,
MultipleFiles = false,
PublicClasses = true,
OutputDirectory = defaultOptions.OutputDirectory,
IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf
}.Build();
}
}
CSharpFileOptions.Builder builder = defaultOptions.ToBuilder();
if (proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) { if (proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) {
builder.MergeFrom(proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)); builder.MergeFrom(proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions));
} }
...@@ -112,22 +123,26 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -112,22 +123,26 @@ namespace Google.ProtocolBuffers.Descriptors {
if (!builder.HasUmbrellaClassname) { if (!builder.HasUmbrellaClassname) {
int lastSlash = Name.LastIndexOf('/'); int lastSlash = Name.LastIndexOf('/');
string baseName = Name.Substring(lastSlash + 1); string baseName = Name.Substring(lastSlash + 1);
builder.UmbrellaClassname = NameHelpers.UnderscoresToPascalCase(NameHelpers.StripProto(baseName)); builder.UmbrellaClassname = NameHelpers.UnderscoresToPascalCase(NameHelpers.StripProto(baseName));
} }
// ROK 2010-09-03 - auto fix for name collision by placing umbrella class into a new namespace. This // Auto-fix for name collision by placing umbrella class into a new namespace. This
// still won't fix the collisions with nesting enabled; however, you have to turn that on so whatever. // still won't fix the collisions with nesting enabled; however, you have to turn that on explicitly anyway.
if(!builder.NestClasses && !builder.HasUmbrellaNamespace) { if (!builder.NestClasses && !builder.HasUmbrellaNamespace) {
bool collision = false; bool collision = false;
foreach (IDescriptor d in MessageTypes) foreach (IDescriptor d in MessageTypes) {
collision |= d.Name == builder.UmbrellaClassname; collision |= d.Name == builder.UmbrellaClassname;
foreach (IDescriptor d in Services) }
collision |= d.Name == builder.UmbrellaClassname; foreach (IDescriptor d in Services) {
foreach (IDescriptor d in EnumTypes) collision |= d.Name == builder.UmbrellaClassname;
collision |= d.Name == builder.UmbrellaClassname; }
if (collision) foreach (IDescriptor d in EnumTypes) {
builder.UmbrellaNamespace = "Proto"; collision |= d.Name == builder.UmbrellaClassname;
} }
if (collision) {
builder.UmbrellaNamespace = "Proto";
}
}
return builder.Build(); return builder.Build();
} }
...@@ -140,7 +155,7 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -140,7 +155,7 @@ namespace Google.ProtocolBuffers.Descriptors {
} }
/// <value> /// <value>
/// The <see cref="FileOptions" /> defined in <c>descriptor.proto</c>. /// The <see cref="DescriptorProtos.FileOptions" /> defined in <c>descriptor.proto</c>.
/// </value> /// </value>
public FileOptions Options { public FileOptions Options {
get { return proto.Options; } get { return proto.Options; }
...@@ -238,15 +253,15 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -238,15 +253,15 @@ namespace Google.ProtocolBuffers.Descriptors {
internal DescriptorPool DescriptorPool { internal DescriptorPool DescriptorPool {
get { return pool; } get { return pool; }
} }
/// <summary> /// <summary>
/// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types. /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
/// </summary> /// </summary>
/// <param name="name">The unqualified type name to look for.</param> /// <param name="name">The unqualified type name to look for.</param>
/// <typeparam name="T">The type of descriptor to look for (or ITypeDescriptor for any)</typeparam> /// <typeparam name="T">The type of descriptor to look for (or ITypeDescriptor for any)</typeparam>
/// <returns>The type's descriptor, or null if not found.</returns> /// <returns>The type's descriptor, or null if not found.</returns>
public T FindTypeByName<T>(String name) public T FindTypeByName<T>(String name)
where T : class, IDescriptor { where T : class, IDescriptor {
// Don't allow looking up nested types. This will make optimization // Don't allow looking up nested types. This will make optimization
// easier later. // easier later.
if (name.IndexOf('.') != -1) { if (name.IndexOf('.') != -1) {
...@@ -291,20 +306,20 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -291,20 +306,20 @@ namespace Google.ProtocolBuffers.Descriptors {
if (dependencies.Length != proto.DependencyCount) { if (dependencies.Length != proto.DependencyCount) {
throw new DescriptorValidationException(result, throw new DescriptorValidationException(result,
"Dependencies passed to FileDescriptor.BuildFrom() don't match " + "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
"those listed in the FileDescriptorProto."); "those listed in the FileDescriptorProto.");
} }
for (int i = 0; i < proto.DependencyCount; i++) { for (int i = 0; i < proto.DependencyCount; i++) {
if (dependencies[i].Name != proto.DependencyList[i]) { if (dependencies[i].Name != proto.DependencyList[i]) {
throw new DescriptorValidationException(result, throw new DescriptorValidationException(result,
"Dependencies passed to FileDescriptor.BuildFrom() don't match " + "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
"those listed in the FileDescriptorProto."); "those listed in the FileDescriptorProto.");
} }
} }
result.CrossLink(); result.CrossLink();
return result; return result;
} }
private void CrossLink() { private void CrossLink() {
foreach (MessageDescriptor message in messageTypes) { foreach (MessageDescriptor message in messageTypes) {
...@@ -323,7 +338,7 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -323,7 +338,7 @@ namespace Google.ProtocolBuffers.Descriptors {
message.CheckRequiredFields(); message.CheckRequiredFields();
} }
} }
/// <summary> /// <summary>
/// This method is to be called by generated code only. It is equivalent /// This method is to be called by generated code only. It is equivalent
/// to BuildFrom except that the FileDescriptorProto is encoded in /// to BuildFrom except that the FileDescriptorProto is encoded in
...@@ -350,19 +365,21 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -350,19 +365,21 @@ namespace Google.ProtocolBuffers.Descriptors {
public delegate ExtensionRegistry InternalDescriptorAssigner(FileDescriptor descriptor); public delegate ExtensionRegistry InternalDescriptorAssigner(FileDescriptor descriptor);
public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData, public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData,
FileDescriptor[] dependencies,InternalDescriptorAssigner descriptorAssigner) { FileDescriptor[] dependencies,
InternalDescriptorAssigner descriptorAssigner) {
FileDescriptorProto proto; FileDescriptorProto proto;
try { try {
proto = FileDescriptorProto.ParseFrom(descriptorData); proto = FileDescriptorProto.ParseFrom(descriptorData);
} catch (InvalidProtocolBufferException e) { }
catch (InvalidProtocolBufferException e) {
throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e); throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
} }
FileDescriptor result; FileDescriptor result;
try { try {
result = BuildFrom(proto, dependencies); result = BuildFrom(proto, dependencies);
} catch (DescriptorValidationException e) { }
catch (DescriptorValidationException e) {
throw new ArgumentException("Invalid embedded descriptor for \"" + proto.Name + "\".", e); throw new ArgumentException("Invalid embedded descriptor for \"" + proto.Name + "\".", e);
} }
...@@ -372,7 +389,8 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -372,7 +389,8 @@ namespace Google.ProtocolBuffers.Descriptors {
// We must re-parse the proto using the registry. // We must re-parse the proto using the registry.
try { try {
proto = FileDescriptorProto.ParseFrom(descriptorData, registry); proto = FileDescriptorProto.ParseFrom(descriptorData, registry);
} catch (InvalidProtocolBufferException e) { }
catch (InvalidProtocolBufferException e) {
throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e); throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
} }
...@@ -381,7 +399,6 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -381,7 +399,6 @@ namespace Google.ProtocolBuffers.Descriptors {
return result; return result;
} }
/// <summary> /// <summary>
/// Replace our FileDescriptorProto with the given one, which is /// Replace our FileDescriptorProto with the given one, which is
/// identical except that it might contain extensions that weren't present /// identical except that it might contain extensions that weren't present
...@@ -412,4 +429,4 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -412,4 +429,4 @@ namespace Google.ProtocolBuffers.Descriptors {
} }
} }
} }
} }
\ No newline at end of file
...@@ -335,7 +335,7 @@ namespace Google.ProtocolBuffers { ...@@ -335,7 +335,7 @@ namespace Google.ProtocolBuffers {
} }
public override bool IsInitialized { public override bool IsInitialized {
get { return fields.IsInitializedWithRespectTo(type); } get { return fields.IsInitializedWithRespectTo(type); }
} }
public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) { public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) {
......
...@@ -273,7 +273,7 @@ namespace Google.ProtocolBuffers { ...@@ -273,7 +273,7 @@ namespace Google.ProtocolBuffers {
if (extras.Count == 0) { if (extras.Count == 0) {
return current; return current;
} }
if (current == null) { if (current == null) {
current = new List<T>(extras); current = new List<T>(extras);
} else { } else {
current.AddRange(extras); current.AddRange(extras);
...@@ -359,7 +359,7 @@ namespace Google.ProtocolBuffers { ...@@ -359,7 +359,7 @@ namespace Google.ProtocolBuffers {
/// <returns></returns> /// <returns></returns>
private static ReadOnlyCollection<T> MakeReadOnly<T>(ref List<T> list) { private static ReadOnlyCollection<T> MakeReadOnly<T>(ref List<T> list) {
ReadOnlyCollection<T> ret = list == null ? Lists<T>.Empty : new ReadOnlyCollection<T>(list); ReadOnlyCollection<T> ret = list == null ? Lists<T>.Empty : new ReadOnlyCollection<T>(list);
list = null; list = null;
return ret; return ret;
} }
} }
......
Work complete on csharptest/branch
New Options (in csharp_options.proto):
1 - Add a way to specify the output directory
Added an option to csharp_options.proto called "output_directory", defaults to "."
2 - Added an option "file_extension" to control the suffix for cs files generated, defaults to ".cs"
This enables using ".Generated.cs" to provide easy filtering and cleanup of generated code.
3 - Added the option for "umbrella_namespace" used when nest_classes=false and having name conflicts
4 - Optionally remove dependencies to csharp options
provided option "ignore_google_protobuf" to prevent generation of code for csharp_options.proto and descriptor.proto
option also relaxes the contraint of having either of these compiled into the proto buffer input
5 - Investigate command line parsing library
All proto options for csharp_options.proto can now be provided via the command-line by using the following format:
/option=value or -option:value
i.e. use /namespace=My.Name.Space
6 - Investigate calling protoc directly
ProgramPreprocess.cs - input files with an extension of '.proto' by running protoc.exe. If arguments
are supplied with '--' prefix they are provided to protoc.exe, otherwise they are assumed to
be used for ProtoGen.exe which is run on the resulting output proto buffer. If the option
--descriptor_set_out= is specified the proto buffer file is kept, otherwise it will be removed
after code generation.
7 - Unable to resolve dependencies correctly
Fixed an issue where two or more proto-buffers are provided to protogen.exe that depend on types
defined in one-another. The dependency walker of the generator was not taking into account all
inputs when evaluating the descriptor's existence.
8 - Added several (20) nunits to automate the command-line invocation of each option and ensured the
generated code compiles into a working assembly and contains some of the expected types. Not sure
how to disable this test for mono, I'm certain it will not work; however, I still believe it's worth
having. As a side-benefit from testing the command-line options, it verifies behavior of each
setting in csharp_options (save for multi-file).
Current task list (not in order) Current task list (not in order)
? Optionally remove dependencies to csharp options
- Remove multifile support - Remove multifile support
- Docs - Docs
- Clean up protogen code - Clean up protogen code
X Add flags to protogen
- Avoid using reflection for messages which don't need it (is this - Avoid using reflection for messages which don't need it (is this
possible?) possible?)
- Bring service generation into line with Java - Bring service generation into line with Java
...@@ -53,7 +12,5 @@ X Add flags to protogen ...@@ -53,7 +12,5 @@ X Add flags to protogen
- Reformat code - Reformat code
- Change generated format - Change generated format
- Add regions to copyright - Add regions to copyright
X Investigate command line parsing library
X Investigate calling protoc directly
- Build and publish binaries - Build and publish binaries
- Work out why the Compact Framework 3.5 build fails under VS2010 - Work out why the Compact Framework 3.5 build fails under VS2010
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment