Beispiel #1
0
        public static IEnumerable<IDocumentStorage> Build(IDocumentSchema schema, DocumentMapping[] mappings)
        {
            // Generate the actual source code
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();

            // Tell the generator which other assemblies that it should be referencing 
            // for the compilation
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType<NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType<QueryModel>();
            generator.ReferenceAssemblyContainingType<DbCommand>();
            generator.ReferenceAssemblyContainingType<Component>();
            generator.ReferenceAssemblyContainingType<DbDataReader>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            // build the new assembly -- this will blow up if there are any
            // compilation errors with the list of errors and the actual code

            var assembly = generator.Generate(code);

            return assembly
                .GetExportedTypes()
                .Where(x => x.IsConcreteTypeOf<IDocumentStorage>())
                .Select(x => BuildStorageObject(schema, mappings, x));
        }
Beispiel #2
0
        public static IEnumerable <IDocumentStorage> Build(IDocumentSchema schema, DocumentMapping[] mappings)
        {
            // Generate the actual source code
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();

            // Tell the generator which other assemblies that it should be referencing
            // for the compilation
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType <NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType <QueryModel>();
            generator.ReferenceAssemblyContainingType <DbCommand>();
            generator.ReferenceAssemblyContainingType <Component>();
            generator.ReferenceAssemblyContainingType <DbDataReader>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            // build the new assembly -- this will blow up if there are any
            // compilation errors with the list of errors and the actual code

            var assembly = generator.Generate(code);

            return(assembly
                   .GetExportedTypes()
                   .Where(x => x.IsConcreteTypeOf <IDocumentStorage>())
                   .Select(x => BuildStorageObject(schema, mappings, x)));
        }
Beispiel #3
0
        public void generate_code_on_the_fly_using_source_writer()
        {
            #region sample_using-AssemblyGenerator-with-source-writer
            var generator = new AssemblyGenerator();

            // This is necessary for the compilation to succeed
            // It's exactly the equivalent of adding references
            // to your project
            generator.ReferenceAssembly(typeof(Console).Assembly);
            generator.ReferenceAssembly(typeof(IOperation).Assembly);


            var assembly = generator.Generate(x =>
            {
                x.Namespace("Generated");
                x.StartClass("AddOperator", typeof(IOperation));

                x.Write("BLOCK:public int Calculate(int one, int two)");
                x.Write("return one + two;");
                x.FinishBlock();  // Finish the method

                x.FinishBlock();  // Finish the class
                x.FinishBlock();  // Finish the namespace
            });



            var type      = assembly.GetExportedTypes().Single();
            var operation = (IOperation)Activator.CreateInstance(type);

            var result = operation.Calculate(1, 2);

            #endregion
            result.ShouldBe(3);
        }
        public static IEnumerable<IDocumentStorage> Build(IDocumentSchema schema, DocumentMapping[] mappings)
        {
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType<NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType<QueryModel>();
            generator.ReferenceAssemblyContainingType<DbCommand>();
            generator.ReferenceAssemblyContainingType<Component>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            var assembly = generator.Generate(code);

            return assembly
                .GetExportedTypes()
                .Where(x => x.IsConcreteTypeOf<IDocumentStorage>())
                .Select(x =>
                {
                    var docType =
                        x.FindInterfaceThatCloses(typeof (IdAssignment<>)).GetGenericArguments().Single();

                    var mapping = mappings.Single(m => m.DocumentType == docType);

                    var arguments = mapping.IdStrategy.ToArguments().Select(arg => arg.GetValue(schema)).ToArray();

                    var ctor = x.GetConstructors().Single();

                    return ctor.Invoke(arguments).As<IDocumentStorage>();
                });
        }
Beispiel #5
0
        public void say_hello()
        {
            var generator = new AssemblyGenerator();

            generator.ReferenceAssembly(typeof(IGreeter).Assembly);

            var assembly = generator.Generate(w =>
            {
                w.Write(@"


public class HelloWorld : LamarCompiler.Testing.Samples.IGreeter
{
    public string Greetings()
    {
        return ""Hello NDC London!"";
    }
}
");
            });

            var greeter = (IGreeter)Activator.CreateInstance(assembly.GetExportedTypes().Single());


            _output.WriteLine(greeter.Greetings());
        }
Beispiel #6
0
        // Public methods
        ///////////////////////////

        public static Action Create(Ecs.Internals ecs, MethodInfo systemInfo)
        {
            var systemName = $"{systemInfo.DeclaringType}.{systemInfo.Name}";
            var arguments  = systemInfo.GetParameters()
                             .Select(p => GetArgumentData(ecs, p))
                             .ToArray();

            if (arguments.Length == 0)
            {
                return(() => systemInfo.Invoke(null, null));
            }
            var resources = arguments
                            .Where(a => a.isResource)
                            .ToArray();
            var components = arguments
                             .Where(a => !a.isResource)
                             .ToArray();
            var src = default(string);

            if (components.Length > 0)
            {
                src = ForEachSource(ecs, arguments, resources, components);
            }
            else
            {
                src = ResourceOnlySource(ecs, resources);
            }
            var asmGen = new AssemblyGenerator();

            asmGen.ReferenceAssemblyByName("System");
            asmGen.ReferenceAssemblyByName("System.Collections");
            asmGen.ReferenceAssemblyByName("System.Reflection");
            asmGen.ReferenceAssemblyContainingType(typeof(Ecs));
            src = asmGen.Format(src);
            var startTime = TimeNow();

            var(assembly, errors) = asmGen.Generate(src);
            if (errors != null)
            {
                var sb = new System.Text.StringBuilder();
                sb.Append($"encountered error(s) compiling system runner for {systemName}");
                foreach (var error in errors)
                {
                    sb.Append($"\n  {error.Replace("\n", "\n  ")}");
                }
                var srcLines = src.Split("\n");
                for (var i = 0; i < srcLines.Length; i++)
                {
                    sb.Append($"\n{i+1}\t{srcLines[i]}");
                }
                throw new Exception(sb.ToString());
            }
            var runner   = assembly.GetType("Runner");
            var duration = TimeNow() - startTime;

            Console.WriteLine($"generated system runner for {systemName} in {duration}ms:\n  {src.Replace("\n", "\n  ")}");
            runner.GetMethod("Initialize").Invoke(null, new object[] { ecs, systemInfo });
            return((Action)runner.GetMethod("Run").CreateDelegate(typeof(Action)));
        }
Beispiel #7
0
        public void generate_assembly_with_random_name_by_default()
        {
            var generator = new AssemblyGenerator();

            var assembly = generator.Generate("public class Given{}");

            assembly.GetName().Name.ShouldNotBeNullOrWhiteSpace();
        }
        public void CopiesJsiiToOutput()
        {
            const string json =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""version"": """",
    ""types"": {}
}";

            string jsonPath        = GetJsonPath("aws-cdk-cx-api");
            string projectFilePath = GetProjectFilePath("Aws.Cdk.CxApi", "Aws.Cdk.CxApi");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(Substitute.For <IDirectory>());
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApiPackageId");

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk-cx-api", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk-cx-api", "aws-cdk-cx-api-1.2.3.5.tgz"),
                Symbols
            );

            file.Received().Copy(jsonPath, Path.Combine(OutputRoot, "Aws.Cdk.CxApiPackageId", ".jsii"));
        }
Beispiel #9
0
        public void CreatesAssemblyInfo()
        {
            const string json =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApi""
        }
    },
    ""version"": """",
    ""types"": {}
}";

            string jsonPath        = GetJsonPath("aws-cdk-cx-api");
            string projectFilePath = GetProjectFilePath("Aws.Cdk.CxApi", "Aws.Cdk.CxApi");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(Substitute.For <IDirectory>());
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApi");

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                "myAuthors",
                "myCompany",
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk-cx-api", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk-cx-api", "aws-cdk-cx-api-1.2.3.5.tgz"),
                Symbols
            );

            file.Received().WriteAllText(Path.Combine(OutputRoot, "Aws.Cdk.CxApi", "AssemblyInfo.cs"),
                                         Arg.Do <string>(
                                             code => Assert.Equal(
                                                 @"using Amazon.JSII.Runtime.Deputy;

[assembly: JsiiAssembly(""jsii$aws_cdk_cx_api$"", """", ""aws-cdk-cx-api-1.2.3.5.tgz"")]",
                                                 code,
                                                 ignoreLineEndingDifferences: true
                                                 )
                                             )
                                         );
        }
Beispiel #10
0
        public void generate_assembly_with_given_name()
        {
            var generator = new AssemblyGenerator
            {
                AssemblyName = "given",
            };

            var assembly = generator.Generate("public class Given{}");

            assembly.GetName().Name.ShouldBe("given");
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            var config = @"{
                ModelConfig: {},
                ViewModelConfig: {},
                ControllerConfig: {}
            }";

            var generator = new AssemblyGenerator(config);

            generator.Generate();
        }
Beispiel #12
0
        private static void GenerateAssembly(bool debug, StreamReader inputFile)
        {
            AssemblyGenerator assemblyGenerator = new AssemblyGenerator();
            assemblyGenerator.Debug = debug;
            assemblyGenerator.Name = _output;

            AssemblyBuilder assemblyBuilder = assemblyGenerator.Generate(inputFile);

            assemblyBuilder.Save(assemblyBuilder.GetName().Name);

            if (assemblyGenerator.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(assemblyGenerator.Errors.Count);
                sb.Append(" Errors:");
                sb.Append(Environment.NewLine);

                foreach (CompilerError error in assemblyGenerator.Errors)
                {
                    sb.Append(error.ErrorText);
                }

                Console.WriteLine(sb.ToString());
            }

            if (debug)
            {
                Assembly assembly = Assembly.LoadFrom("test.debug.exe");

                Type t = assembly.GetType("test.Program");

                object o = Activator.CreateInstance(t);

                MemberInfo[] memberInfos =
                    t.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
                                 BindingFlags.Static);

                EventInfo eventInfo = t.GetEvent("BreakEvent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
                                 BindingFlags.Static);

                //eventInfo.AddEventHandler(o, new EventHandler<EventArgs>(Test));

                //MethodInfo m = t.GetMethod("Break");

                //m.Invoke(o, new object[0]);
            }

            //Console.ReadLine();
        }
Beispiel #13
0
    public void generate_a_small_class()
    {
        var code = @"
using System;
using Marten.Testing;


namespace RoslynGenerationSpike
{
    public class Writer : IMessageWriter
    {
        public void WriteMessages()
        {
            Console.WriteLine('What is this?');
            Console.WriteLine('Dynamic Code?');
            Console.WriteLine('Really?');
        }
    }
}
".Replace("'", "\"");


        // New helper for this mess called AssemblyGenerator
        var builder = new AssemblyGenerator();


        // you might need to help it out w/ references
        builder.ReferenceAssembly(Assembly.GetExecutingAssembly());

        // Make the new Assembly
        var assembly = builder.Generate(code);

        // Do stuff with it
        var writerType = assembly.GetExportedTypes().Single();
        var writer     = Activator.CreateInstance(writerType).As <IMessageWriter>();

        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
    }
Beispiel #14
0
    public void generate_a_small_class()
    {
        var code = @"
using System;
using Marten.Testing;


namespace RoslynGenerationSpike
{
    public class Writer : IMessageWriter
    {
        public void WriteMessages()
        {
            Console.WriteLine('What is this?');
            Console.WriteLine('Dynamic Code?');
            Console.WriteLine('Really?');
        }
    }
}
".Replace("'", "\"");


        // New helper for this mess called AssemblyGenerator
        var builder = new AssemblyGenerator();


        // you might need to help it out w/ references
        builder.ReferenceAssembly(Assembly.GetExecutingAssembly());

        // Make the new Assembly
        var assembly = builder.Generate(code);

        // Do stuff with it
        var writerType = assembly.GetExportedTypes().Single();
        var writer = Activator.CreateInstance(writerType).As<IMessageWriter>();

        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
        writer.WriteMessages();
    }
Beispiel #15
0
        public void generate_code_on_the_fly()
        {
            #region sample_using-AssemblyGenerator
            var generator = new AssemblyGenerator();

            // This is necessary for the compilation to succeed
            // It's exactly the equivalent of adding references
            // to your project
            generator.ReferenceAssembly(typeof(Console).Assembly);
            generator.ReferenceAssembly(typeof(IOperation).Assembly);

            // Compile and generate a new .Net Assembly object
            // in memory
            var assembly = generator.Generate(@"
using LamarCompiler.Testing.Samples;

namespace Generated
{
    public class AddOperator : IOperation
    {
        public int Calculate(int one, int two)
        {
            return one + two;
        }
    }
}
");

            // Find the new type we generated up above
            var type = assembly.GetExportedTypes().Single();

            // Use Activator.CreateInstance() to build an object
            // instance of our new class, and cast it to the
            // IOperation interface
            var operation = (IOperation)Activator.CreateInstance(type);

            // Use our new type
            var result = operation.Calculate(1, 2);

            #endregion
            result.ShouldBe(3);
        }
Beispiel #16
0
        public static IEnumerable<IDocumentStorage> Build(DocumentMapping[] mappings)
        {
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType<NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType<QueryModel>();
            generator.ReferenceAssemblyContainingType<DbCommand>();
            generator.ReferenceAssemblyContainingType<Component>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            var assembly = generator.Generate(code);

            return assembly
                .GetExportedTypes()
                .Where(x => x.IsConcreteTypeOf<IDocumentStorage>())
                .Select(x => Activator.CreateInstance(x).As<IDocumentStorage>());
        }
Beispiel #17
0
        public static IEnumerable <IDocumentStorage> Build(IDocumentSchema schema, IDocumentMapping[] mappings)
        {
            // Generate the actual source code
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();

            // Tell the generator which other assemblies that it should be referencing
            // for the compilation
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType <NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType <QueryModel>();
            generator.ReferenceAssemblyContainingType <DbCommand>();
            generator.ReferenceAssemblyContainingType <Component>();
            generator.ReferenceAssemblyContainingType <DbDataReader>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            // build the new assembly -- this will blow up if there are any
            // compilation errors with the list of errors and the actual code

            var assembly = generator.Generate(code);

            return(assembly
                   .GetExportedTypes()
                   .Where(x => x.IsConcreteTypeOf <IDocumentStorage>())
                   .Select(x =>
            {
                var docType =
                    x.FindInterfaceThatCloses(typeof(IdAssignment <>)).GetGenericArguments().Single();

                var mapping = mappings.Single(m => m.DocumentType == docType);

                var arguments = mapping.ToArguments().Select(arg => arg.GetValue(schema)).ToArray();

                var ctor = x.GetConstructors().Single();

                return ctor.Invoke(arguments).As <IDocumentStorage>();
            }));
        }
        public static IEnumerable<IDocumentStorage> Build(IDocumentSchema schema, IDocumentMapping[] mappings)
        {
            // Generate the actual source code
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();

            // Tell the generator which other assemblies that it should be referencing 
            // for the compilation
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType<NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType<QueryModel>();
            generator.ReferenceAssemblyContainingType<DbCommand>();
            generator.ReferenceAssemblyContainingType<Component>();
            generator.ReferenceAssemblyContainingType<DbDataReader>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            // build the new assembly -- this will blow up if there are any
            // compilation errors with the list of errors and the actual code

            var assembly = generator.Generate(code);

            return assembly
                .GetExportedTypes()
                .Where(x => x.IsConcreteTypeOf<IDocumentStorage>())
                .Select(x =>
                {
                    var docType =
                        x.FindInterfaceThatCloses(typeof (IdAssignment<>)).GetGenericArguments().Single();

                    var mapping = mappings.Single(m => m.DocumentType == docType);

                    var arguments = mapping.ToArguments().Select(arg => arg.GetValue(schema)).ToArray();

                    var ctor = x.GetConstructors().Single();

                    return ctor.Invoke(arguments).As<IDocumentStorage>();
                });
        }
        public static IEnumerable <IDocumentStorage> Build(DocumentMapping[] mappings)
        {
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();

            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType <NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType <QueryModel>();
            generator.ReferenceAssemblyContainingType <DbCommand>();
            generator.ReferenceAssemblyContainingType <Component>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));


            var assembly = generator.Generate(code);

            return(assembly
                   .GetExportedTypes()
                   .Where(x => x.IsConcreteTypeOf <IDocumentStorage>())
                   .Select(x => Activator.CreateInstance(x).As <IDocumentStorage>()));
        }
Beispiel #20
0
        static (Action, bool) Compile(string fileName)
        {
            var startTime = Time.Now();
            var source    = File.ReadAllText(fileName);
            var asmGen    = new AssemblyGenerator();

            asmGen.ReferenceAssemblyByName("System.Collections");
            asmGen.ReferenceAssemblyByName("System.Linq");
            asmGen.ReferenceAssemblyContainingType(typeof(Program));
            source = asmGen.Format(source);
            var(assembly, errors) = asmGen.Generate(source);
            if (errors != null)
            {
                Log.Error($"compilation error:\n{String.Join("\n", errors)}");
                return(null, false);
            }
            var scriptType = assembly.GetType("Script");
            var mainMethod = scriptType.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static);
            var run        = (Action)mainMethod.CreateDelegate(typeof(Action));
            var duration   = Time.Now() - startTime;

            Log.Info($"compiled script {fileName} in {duration:F2}s");
            return(run, true);
        }
        public void CreatesBasicTypeFile()
        {
            const string json =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""version"": """",
    ""types"": {
        ""jsii$aws_cdk_cx_api$.MissingContext"": {
            ""kind"": ""class"",
            ""fqn"": ""jsii$aws_cdk_cx_api$.MissingContext"",
            ""assembly"": ""jsii$aws_cdk_cx_api$"",
            ""name"": ""MissingContext"",
            ""initializer"": {
                ""initializer"": true
            }
        }
    }
}";

            string jsonPath     = GetJsonPath("aws-cdk-cx-api");
            string typeFilePath = GetTypeFilePath("Aws.Cdk.CxApiPackageId", "Aws.Cdk.CxApiNamespace", "MissingContext");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(Substitute.For <IDirectory>());
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApiPackageId");
            Symbols.MapNamespace("jsii$aws_cdk_cx_api$", "Aws.Cdk.CxApiNamespace");
            Symbols.MapTypeName("jsii$aws_cdk_cx_api$.MissingContext", "MissingContext", TypeKind.Class);

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk-cx-api", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk-cx-api", "aws-cdk-cx-api-1.1.1.tgz"),
                Symbols
            );


            string expected =
                @"using Amazon.JSII.Runtime.Deputy;

namespace Aws.Cdk.CxApiNamespace
{
    [JsiiClass(typeof(MissingContext), ""jsii$aws_cdk_cx_api$.MissingContext"", ""[]"")]
    public class MissingContext : DeputyBase
    {
        public MissingContext(): base(new DeputyProps(new object[]{}))
        {
        }

        protected MissingContext(ByRefValue reference): base(reference)
        {
        }

        protected MissingContext(DeputyProps props): base(props)
        {
        }
    }
}";

            file.Received().WriteAllText(typeFilePath,
                                         Arg.Is <string>(actual => PlatformIndependentEqual(expected, actual))
                                         );
        }
Beispiel #22
0
        public void CreatesBasicProjectFile()
        {
            const string json =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""package"": ""aws-cdk-cx-api"",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApi""
        }
    },
    ""version"": ""1.2.3"",
    ""types"": {}
}";

            string jsonPath        = GetJsonPath("aws-cdk-cx-api");
            string projectFilePath = GetProjectFilePath("Aws.Cdk.CxApi", "Aws.Cdk.CxApi");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(Substitute.For <IDirectory>());
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApi");

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                "myAuthors",
                "myCompany",
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk-cx-api", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk-cx-api", "aws-cdk-cx-api-1.2.3.5.tgz"),
                Symbols
            );

            string expected =
                @"<Project Sdk=""Microsoft.NET.Sdk"">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <Authors>myAuthors</Authors>
    <Company>myCompany</Company>
    <PackageVersion>1.2.3</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <EmbeddedResource Include=""aws-cdk-cx-api-1.2.3.5.tgz"" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include=""Amazon.JSII.Runtime"" Version=""" + JsiiVersion.Version + @""" />
  </ItemGroup>
</Project>";

            file.Received().WriteAllText(projectFilePath, Arg.Do <string>(actual => PlatformIndependentEqual(expected, actual)));
        }
Beispiel #23
0
        static void Generate(Options options)
        {
            AssemblyGenerator generator = new AssemblyGenerator(options.OutputDirectory, "", "");

            generator.Generate(options.JsiiFile, options.Tarball);
        }
        public void CreatesProjectFileWithDependencies()
        {
            string json =
                @"{
    ""name"": ""jsii$aws_cdk$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.CdkNamespace"",
            ""packageId"": ""Aws.CdkPackageId""
        }
    },
    ""version"": ""1.2.3"",
    ""types"": {},
    ""dependencies"": {
        ""jsii$aws_cdk_cx_api$"": {
            ""package"": ""aws-cdk-cx-api"",
            ""version"": """",
            ""targets"": {
                ""dotnet"": {
                    ""namespace"": ""Aws.Cdk.CxApi"",
                    ""packageId"": ""Aws.Cdk.CxApi""
                }
            }
        }
    }
}";
            string cxJson =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""version"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""types"": {}
}";

            string jsonPath        = GetJsonPath("aws-cdk");
            string cxJsonPath      = Path.Combine(Path.GetDirectoryName(jsonPath), "node_modules", "jsii$aws_cdk_cx_api$");
            string projectFilePath = GetProjectFilePath("Aws.CdkPackageId", "Aws.CdkPackageId");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);
            file.ReadAllText(Path.Combine(cxJsonPath, ".jsii")).Returns(cxJson);

            IDirectory directory = Substitute.For <IDirectory>();

            directory.Exists(cxJsonPath).Returns(true);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(directory);
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk", "Aws.CdkPackageId");
            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApiNamespace");
            Symbols.MapAssemblyName("jsii$aws_cdk_cx_api$", "Aws.Cdk.CxApiPackageId");

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk", "aws-cdk-1.2.3.4.tgz"),
                Symbols
            );

            string expected =
                @"<Project Sdk=""Microsoft.NET.Sdk"">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <Authors>myAuthors</Authors>
    <Company>myCompany</Company>
    <PackageVersion>1.2.3</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <EmbeddedResource Include=""aws-cdk-1.2.3.4.tgz"" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include=""Amazon.JSII.Runtime"" Version=""" + JsiiVersion.Version + @""" />
    <ProjectReference Include=""..\Aws.Cdk.CxApi\Aws.Cdk.CxApi.csproj"" Version=""" + JsiiVersion.Version + @""" />
  </ItemGroup>
</Project>";

            file.Received().WriteAllText(projectFilePath, Arg.Do <string>(actual => PlatformIndependentEqual(expected, actual)));
        }
        public void CreatesAnchorFile()
        {
            string json =
                @"{
    ""name"": ""jsii$aws_cdk$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.CdkNamespace"",
            ""packageId"": ""Aws.CdkPackageId""
        }
    },
    ""version"": ""1.2.3"",
    ""types"": {},
    ""dependencies"": {
        ""jsii$aws_cdk_cx_api$"": {
            ""package"": ""aws-cdk-cx-api"",
            ""version"": """",
            ""targets"": {
                ""dotnet"": {
                    ""namespace"": ""Aws.Cdk.CxApi"",
                    ""packageId"": ""Aws.Cdk.CxApi""
                }
            }
        }
    }
}";
            string cxJson =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""version"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""types"": {}
}";

            string jsonPath       = GetJsonPath("aws-cdk");
            string cxJsonPath     = Path.Combine(Path.GetDirectoryName(jsonPath), "node_modules", "jsii$aws_cdk_cx_api$");
            string anchorFilePath = GetAnchorFilePath("Aws.CdkPackageId", "Aws.CdkNamespace");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);
            file.ReadAllText(Path.Combine(cxJsonPath, ".jsii")).Returns(cxJson);

            IDirectory directory = Substitute.For <IDirectory>();

            directory.Exists(cxJsonPath).Returns(true);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(directory);
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk", "Aws.CdkPackageId");
            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApiNamespace");
            Symbols.MapAssemblyName("jsii$aws_cdk_cx_api$", "Aws.Cdk.CxApiPackageId");

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk", "aws-cdk-1.2.3.4.tgz"),
                Symbols
            );

            string expected =
                @"namespace Aws.CdkNamespace.Internal.DependencyResolution
{
    public class Anchor
    {
        public Anchor()
        {
            new Aws.Cdk.CxApiNamespace.Internal.DependencyResolution.Anchor();
        }
    }
}";

            file.Received().WriteAllText(anchorFilePath, Arg.Do <string>(actual => PlatformIndependentEqual(expected, actual)));
        }
        public void AccessesFileSystemThroughShim()
        {
            const string json =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""version"": """",
    ""types"": {
        ""jsii$aws_cdk_cx_api$.MissingContext"": {
            ""kind"": ""class"",
            ""fqn"": ""jsii$aws_cdk_cx_api$.MissingContext"",
            ""assembly"": ""jsii$aws_cdk_cx_api$"",
            ""name"": ""MissingContext"",
            ""initializer"": {
                ""initializer"": true
            }
        }
    }
}";

            string jsonPath          = GetJsonPath("aws-cdk-cx-api");
            string packageOutputRoot = GetPackageOutputRoot("Aws.Cdk.CxApiPackageId");
            string projectFilePath   = GetProjectFilePath("Aws.Cdk.CxApiPackageId", "Aws.Cdk.CxApiPackageId");
            string typeFilePath      = GetTypeFilePath("Aws.Cdk.CxApiPackageId", "Aws.Cdk.CxApiNamespace", "MissingContext");

            IDirectory directory = Substitute.For <IDirectory>();

            directory.Exists(packageOutputRoot).Returns(true, false);

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(directory);
            fileSystem.File.Returns(file);

            //Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApi");
            Symbols.MapNamespace("jsii$aws_cdk_cx_api$", "Aws.Cdk.CxApiNamespace");
            Symbols.MapTypeName("jsii$aws_cdk_cx_api$.MissingContext", "MissingContext", TypeKind.Class);

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk-cx-api", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk-cx-api", "aws-cdk-cx-api-1.2.3.5.tgz"),
                Symbols
            );

            directory.Received().Delete(packageOutputRoot, true);
            directory.Received().CreateDirectory(packageOutputRoot);
            file.Received().ReadAllText(jsonPath);
            file.Received().WriteAllText(projectFilePath, Arg.Any <string>());
            file.Received().WriteAllText(typeFilePath, Arg.Any <string>());
        }