Example #1
0
        public void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Warn about any code generation excluded namespaces
            foreach (var @namespace in script.ExcludedNamespaces)
            {
                _log.Warning("Namespace {0} excluded by code generation, affected methods:\r\n\t{1}",
                             @namespace.Key, string.Join("\r\n\t", @namespace.Value));
            }

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces.Except(script.ExcludedNamespaces.Keys))
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath))
                          .WithEmitDebugInformation(_settings.Debug)
                          .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default);

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());

            _log.Verbose("Compiling build script...");
            var compilation = roslynScript.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            var errors = new List <Diagnostic>();

            foreach (var diagnostic in diagnostics)
            {
                switch (diagnostic.Severity)
                {
                case DiagnosticSeverity.Info:
                    _log.Information(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Warning:
                    _log.Warning(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Error:
                    _log.Error(diagnostic.ToString());
                    errors.Add(diagnostic);
                    break;

                default:
                    break;
                }
            }

            if (errors.Any())
            {
                var errorMessages = string.Join(Environment.NewLine, errors.Select(x => x.ToString()));
                var message       = string.Format(CultureInfo.InvariantCulture, "Error(s) occurred when compiling build script:{0}{1}", Environment.NewLine, errorMessages);
                throw new CakeException(message);
            }

            roslynScript.RunAsync(_host).Wait();
        }
        public override bool ExecuteCore()
        {
            bool result = true;

            try
            {
                result = GenPartialFacadeSourceGenerator.Execute(
                    ReferencePaths?.Select(item => item.ItemSpec).ToArray(),
                    ReferenceAssembly,
                    CompileFiles?.Select(item => item.ItemSpec).ToArray(),
                    DefineConstants,
                    LangVersion,
                    OutputSourcePath,
                    Log,
                    IgnoreMissingTypes,
                    IgnoreMissingTypesList,
                    OmitTypes,
                    SeedTypePreferences);
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e, showStackTrace: false);
            }

            return(result && !Log.HasLoggedErrors);
        }
Example #3
0
        public void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath))
                          .WithEmitDebugInformation(_options.PerformDebug)
                          .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default);

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());

            _log.Verbose("Compiling build script...");
            var compilation = roslynScript.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                var errors  = string.Join(Environment.NewLine, diagnostics.Select(x => x.ToString()));
                var message = string.Format(CultureInfo.InvariantCulture, "Error occurred when compiling build script: {0}", errors);
                throw new CakeException(message);
            }

            roslynScript.RunAsync(_host).Wait();
        }
Example #4
0
 public TemplateGenerator()
 {
     ReferencePaths.Add(Path.GetDirectoryName(typeof(int).Assembly.Location).Replace("Microsoft.NETCore.App", "Microsoft.AspNetCore.App"));
     Refs.Add(typeof(TextTransformation).Assembly.Location);
     Refs.Add(typeof(Uri).Assembly.Location);
     Refs.Add(typeof(File).Assembly.Location);
     Refs.Add(typeof(StringReader).Assembly.Location);
     Imports.Add("System");
 }
Example #5
0
 public static void AddReferences(params Assembly[] assemblies)
 {
     foreach (var assembly in assemblies)
     {
         if (!ReferencePaths.Contains(assembly.Location))
         {
             ReferencePaths.Add(assembly.Location);
         }
     }
 }
Example #6
0
 public static void AddReferences(params Type[] types)
 {
     foreach (var type in types)
     {
         if (!ReferencePaths.Contains(type.Assembly.Location))
         {
             ReferencePaths.Add(type.Assembly.Location);
         }
     }
 }
Example #7
0
 public static void AddReferences(params string[] assemblies)
 {
     foreach (var assembly in assemblies)
     {
         if (!ReferencePaths.Contains(assembly))
         {
             ReferencePaths.Add(assembly);
         }
     }
 }
Example #8
0
        /// <summary>
        /// add a reference path for a particular runtime
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="directoryPath"></param>
        public void AddReferencePath(RuntimeKind runtime, string directoryPath)
        {
            if (!ReferencePaths.ContainsKey(runtime))
            {
                ReferencePaths[runtime] = new List <string>();
            }

            if (!ReferencePaths[runtime].Any(x => x.Equals(directoryPath, StringComparison.OrdinalIgnoreCase)))
            {
                ReferencePaths[runtime].Add(directoryPath);
            }
        }
Example #9
0
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddNamespaces(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            _log.Verbose("Compiling build script for debugging...");

            var roslynScript = Microsoft.CodeAnalysis.Scripting.CSharp.CSharpScript.Create(code, options)
                               .WithGlobalsType(_host.GetType());

            var compilation = roslynScript.GetCompilation();

            compilation = compilation.WithOptions(compilation.Options
                                                  .WithOptimizationLevel(Microsoft.CodeAnalysis.OptimizationLevel.Debug)
                                                  .WithOutputKind(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary));

            using (var exeStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(exeStream, pdbStream: pdbStream);

                    if (result.Success)
                    {
                        _log.Verbose("Compilation successful");

                        var assembly = AppDomain.CurrentDomain.Load(exeStream.ToArray(), pdbStream.ToArray());

                        var type   = assembly.GetType(CompiledType);
                        var method = type.GetMethod(CompiledMethod, BindingFlags.Static | BindingFlags.Public);

                        var submissionStates = new object[2];
                        submissionStates[0] = _host;

                        method.Invoke(null, new[] { submissionStates });
                    }
                    else
                    {
                        _log.Verbose("Compilation failed");

                        var errors  = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                        var message = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Error occurred when compiling: {0}", errors);

                        throw new CakeException(message);
                    }
                }
        }
Example #10
0
        public void AddReference(FilePath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            _log.Debug("Adding reference to {0}...", path.GetFilename().FullPath);
#if NETCORE
            References.Add(_loader.Load(path, true));
#else
            ReferencePaths.Add(path);
#endif
        }
Example #11
0
        public static void AddReferences(params Type[] types)
        {
            if (_initialized)
            {
                throw new InvalidOperationException("Compilador só pode ser executado no Pre-Start!");
            }

            foreach (var type in types)
            {
                if (!ReferencePaths.Contains(type.Assembly.Location))
                {
                    ReferencePaths.Add(type.Assembly.Location);
                }
            }
        }
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddNamespaces(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            _log.Verbose("Compiling build script...");
            Microsoft.CodeAnalysis.Scripting.CSharp.CSharpScript.Eval(code, options, _host);
        }
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());
            var compilation  = roslynScript.GetCompilation();

            compilation = compilation.WithOptions(compilation.Options
                                                  .WithOptimizationLevel(OptimizationLevel.Debug)
                                                  .WithOutputKind(OutputKind.DynamicallyLinkedLibrary));

            using (var assemblyStream = new MemoryStream())
                using (var symbolStream = new MemoryStream())
                {
                    _log.Verbose("Compiling build script for debugging...");
                    var emitOptions = new EmitOptions(false, DebugInformationFormat.PortablePdb);
                    var result      = compilation.Emit(assemblyStream, symbolStream, options: emitOptions);
                    if (result.Success)
                    {
                        // Rewind the streams.
                        assemblyStream.Seek(0, SeekOrigin.Begin);
                        symbolStream.Seek(0, SeekOrigin.Begin);

                        var assembly = AssemblyLoadContext.Default.LoadFromStream(assemblyStream, symbolStream);
                        var type     = assembly.GetType(CompiledType);
                        var method   = type.GetMethod(CompiledMethod, BindingFlags.Static | BindingFlags.Public);

                        var submissionStates = new object[2];
                        submissionStates[0] = _host;

                        method.Invoke(null, new object[] { submissionStates });
                    }
                    else
                    {
                        var errors  = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                        var message = string.Format(CultureInfo.InvariantCulture, "Error occurred when compiling: {0}", errors);
                        throw new CakeException(message);
                    }
                }
        }
Example #14
0
        protected async Task <TResult> RunIsolatedAsync(string configurationFile)
        {
            var assemblyDirectory = AssemblyPaths.Any() ? Path.GetDirectoryName(Path.GetFullPath(PathUtilities.ExpandFileWildcards(AssemblyPaths).First())) : configurationFile;
            var bindingRedirects  = GetBindingRedirects();
            var assemblies        = GetAssemblies(assemblyDirectory);

            if (UseNuGetCache)
            {
                var defaultNugetPackages = LoadDefaultNugetCache();
                ReferencePaths = ReferencePaths.Concat(defaultNugetPackages).ToArray();
            }

            using (var isolated = new AppDomainIsolation <IsolatedCommandAssemblyLoader>(assemblyDirectory, AssemblyConfig, bindingRedirects, assemblies))
            {
                return(await Task.Run(() => isolated.Object.Run(GetType().FullName, JsonConvert.SerializeObject(this), AssemblyPaths, ReferencePaths)).ConfigureAwait(false));
            }
        }
 /// <summary>
 /// Add a new entity path reference to this existing entity.
 /// </summary>
 /// <param name="path">The path that can be used to reach this entity.</param>
 public void AddReferencePath(EntityPath path)
 {
     ReferencePaths.Add(path);
 }
Example #16
0
        public void Execute(Script script)
        {
            var    scriptName        = _settings.Script.GetFilename();
            var    cacheDLLFileName  = $"{scriptName}.dll";
            var    cacheHashFileName = $"{scriptName}.hash";
            var    cachedAssembly    = _scriptCachePath.CombineWithFilePath(cacheDLLFileName);
            var    hashFile          = _scriptCachePath.CombineWithFilePath(cacheHashFileName);
            string scriptHash        = default;

            if (_scriptCacheEnabled && _fileSystem.Exist(cachedAssembly) && !_regenerateCache)
            {
                _log.Verbose($"Cache enabled: Checking cache build script ({cacheDLLFileName})");
                scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines)));
                var cachedHash = _fileSystem.Exist(hashFile)
                               ? _fileSystem.GetFile(hashFile).ReadLines(Encoding.UTF8).FirstOrDefault()
                               : string.Empty;
                if (scriptHash.Equals(cachedHash, StringComparison.Ordinal))
                {
                    _log.Verbose("Running cached build script...");
                    RunScriptAssembly(cachedAssembly.FullPath);
                    return;
                }
                else
                {
                    _log.Verbose("Cache check failed.");
                }
            }
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Warn about any code generation excluded namespaces
            foreach (var @namespace in script.ExcludedNamespaces)
            {
                _log.Warning("Namespace {0} excluded by code generation, affected methods:\r\n\t{1}",
                             @namespace.Key, string.Join("\r\n\t", @namespace.Value));
            }

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces.Except(script.ExcludedNamespaces.Keys))
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath))
                          .WithEmitDebugInformation(_settings.Debug)
                          .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default);

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());

            _log.Verbose("Compiling build script...");
            var compilation = roslynScript.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            var errors = new List <Diagnostic>();

            foreach (var diagnostic in diagnostics)
            {
                // Suppress some diagnostic information. See https://github.com/cake-build/cake/issues/3337
                switch (diagnostic.Id)
                {
                // CS1701 Compiler Warning (level 2)
                // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy
                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1701
                case "CS1701":
                    continue;

                // CS1702 Compiler Warning (level 3)
                // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy
                // https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs1702
                case "CS1702":
                    continue;

                // CS1705 Compiler Error
                // Assembly 'AssemblyName1' uses 'TypeName' which has a higher version than referenced assembly 'AssemblyName2'
                case "CS1705":
                    continue;

                default:
                    break;
                }

                switch (diagnostic.Severity)
                {
                case DiagnosticSeverity.Info:
                    _log.Information(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Warning:
                    _log.Warning(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Error:
                    _log.Error(diagnostic.ToString());
                    errors.Add(diagnostic);
                    break;

                default:
                    break;
                }
            }

            if (errors.Any())
            {
                var errorMessages = string.Join(Environment.NewLine, errors.Select(x => x.ToString()));
                var message       = string.Format(CultureInfo.InvariantCulture, "Error(s) occurred when compiling build script:{0}{1}", Environment.NewLine, errorMessages);
                throw new CakeException(message);
            }

            if (_scriptCacheEnabled)
            {
                // Verify cache directory exists
                if (!_fileSystem.GetDirectory(_scriptCachePath).Exists)
                {
                    _fileSystem.GetDirectory(_scriptCachePath).Create();
                }
                if (string.IsNullOrWhiteSpace(scriptHash))
                {
                    scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines)));
                }
                var emitResult = compilation.Emit(cachedAssembly.FullPath);

                if (emitResult.Success)
                {
                    using (var stream = _fileSystem.GetFile(hashFile).OpenWrite())
                        using (var writer = new StreamWriter(stream, Encoding.UTF8))
                        {
                            writer.Write(scriptHash);
                        }
                    RunScriptAssembly(cachedAssembly.FullPath);
                }
            }
            else
            {
                roslynScript.RunAsync(_host).GetAwaiter().GetResult();
            }
        }
        public override bool Execute()
        {
            try
            {
                var functionGenerator = new FunctionMetadataGenerator(MSBuildLogger);

                var functions = functionGenerator.GenerateFunctionMetadata(AssemblyPath !, ReferencePaths.Select(p => p.ItemSpec));

                var extensions = functionGenerator.Extensions;
                var extensionsCsProjGenerator = new ExtensionsCsprojGenerator(extensions, ExtensionsCsProjFilePath !, AzureFunctionsVersion !);

                extensionsCsProjGenerator.Generate();

                FunctionMetadataJsonWriter.WriteMetadata(functions, OutputPath !);
            }
            catch (FunctionsMetadataGenerationException)
            {
                Log.LogError($"Unable to build Azure Functions metadata for {AssemblyPath}");
                return(false);
            }

            return(true);
        }
Example #18
0
        public void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Warn about any code generation excluded namespaces
            foreach (var @namespace in script.ExcludedNamespaces)
            {
                _log.Warning("Namespace {0} excluded by code generation, affected methods:\r\n\t{1}",
                             @namespace.Key, string.Join("\r\n\t", @namespace.Value));
            }

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces.Except(script.ExcludedNamespaces.Keys))
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath))
                          .WithEmitDebugInformation(_settings.Debug)
                          .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default);

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());

            _log.Verbose("Compiling build script...");
            var compilation = roslynScript.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            var errors = new List <Diagnostic>();

            foreach (var diagnostic in diagnostics)
            {
                // Suppress some diagnostic information. See https://github.com/cake-build/cake/issues/3337
                switch (diagnostic.Id)
                {
                // CS1701 Compiler Warning (level 2)
                // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy
                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1701
                case "CS1701":
                    continue;

                // CS1702 Compiler Warning (level 3)
                // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy
                // https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs1702
                case "CS1702":
                    continue;

                // CS1705 Compiler Error
                // Assembly 'AssemblyName1' uses 'TypeName' which has a higher version than referenced assembly 'AssemblyName2'
                case "CS1705":
                    continue;

                default:
                    break;
                }

                switch (diagnostic.Severity)
                {
                case DiagnosticSeverity.Info:
                    _log.Information(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Warning:
                    _log.Warning(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Error:
                    _log.Error(diagnostic.ToString());
                    errors.Add(diagnostic);
                    break;

                default:
                    break;
                }
            }

            if (errors.Any())
            {
                var errorMessages = string.Join(Environment.NewLine, errors.Select(x => x.ToString()));
                var message       = string.Format(CultureInfo.InvariantCulture, "Error(s) occurred when compiling build script:{0}{1}", Environment.NewLine, errorMessages);
                throw new CakeException(message);
            }

            roslynScript.RunAsync(_host).Wait();
        }