示例#1
0
        private EmitResult EmitTemplate(SourceFileGrouping sourceFileGrouping, string filePath, string assemblyFileVersion)
        {
            var compilation = new Compilation(TestTypeHelper.CreateEmptyProvider(), sourceFileGrouping);
            var emitter     = new TemplateEmitter(compilation.GetEntrypointSemanticModel(), assemblyFileVersion);

            using var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            return(emitter.Emit(stream));
        }
示例#2
0
        private EmitResult EmitTemplate(SourceFileGrouping sourceFileGrouping, EmitterSettings emitterSettings, string filePath)
        {
            var compilation = new Compilation(BicepTestConstants.Features, TestTypeHelper.CreateEmptyProvider(), sourceFileGrouping, BicepTestConstants.BuiltInConfiguration, BicepTestConstants.LinterAnalyzer);
            var emitter     = new TemplateEmitter(compilation.GetEntrypointSemanticModel(), emitterSettings);

            using var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            return(emitter.Emit(stream));
        }
示例#3
0
        private EmitResult EmitTemplate(SourceFileGrouping sourceFileGrouping, EmitterSettings emitterSettings, MemoryStream memoryStream)
        {
            var compilation = new Compilation(BicepTestConstants.Features, TestTypeHelper.CreateEmptyProvider(), sourceFileGrouping, BicepTestConstants.BuiltInConfiguration, BicepTestConstants.LinterAnalyzer);
            var emitter     = new TemplateEmitter(compilation.GetEntrypointSemanticModel(), emitterSettings);

            TextWriter tw = new StreamWriter(memoryStream);

            return(emitter.Emit(tw));
        }
示例#4
0
        private EmitResult EmitTemplate(SourceFileGrouping sourceFileGrouping, MemoryStream memoryStream, string assemblyFileVersion)
        {
            var compilation = new Compilation(TestTypeHelper.CreateEmptyProvider(), sourceFileGrouping);
            var emitter     = new TemplateEmitter(compilation.GetEntrypointSemanticModel(), assemblyFileVersion);

            TextWriter tw = new StreamWriter(memoryStream);

            return(emitter.Emit(tw));
        }
示例#5
0
        private string GenerateCompiledParametersFileAndReturnOutputMessage(string bicepFilePath, DocumentUri documentUri)
        {
            string compiledFilePath = PathHelper.ResolveParametersFileOutputPath(bicepFilePath);
            string compiledFile     = Path.GetFileName(compiledFilePath);

            // If the template exists and contains bicep generator metadata, we can go ahead and replace the file.
            // If not, we'll fail the generate params.
            if (File.Exists(compiledFilePath) && !TemplateIsParametersFile(File.ReadAllText(compiledFilePath)))
            {
                return("Generating parameters file failed. The file \"" + compiledFile + "\" already exists but does not contain the schema for a parameters file. If overwriting the file is intended, delete it manually and retry the Generate Parameters command.");
            }

            var fileUri = documentUri.ToUri();
            RootConfiguration?configuration = null;

            try
            {
                configuration = this.configurationManager.GetConfiguration(fileUri);
            }
            catch (ConfigurationException exception)
            {
                // Fail the generate params if there's configuration errors.
                return(exception.Message);
            }

            CompilationContext?context = compilationManager.GetCompilation(fileUri);
            Compilation        compilation;

            if (context is null)
            {
                SourceFileGrouping sourceFileGrouping = SourceFileGroupingBuilder.Build(this.fileResolver, this.moduleDispatcher, new Workspace(), fileUri, configuration);
                compilation = new Compilation(features, namespaceProvider, sourceFileGrouping, configuration, new LinterAnalyzer(configuration));
            }
            else
            {
                compilation = context.Compilation;
            }

            KeyValuePair <BicepFile, IEnumerable <IDiagnostic> > diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile()
                                                                                     .FirstOrDefault(x => x.Key.FileUri == fileUri);

            if (diagnosticsByFile.Value.Any(x => x.Level == DiagnosticLevel.Error))
            {
                return("Generating parameters file failed. Please fix below errors:\n" + DiagnosticsHelper.GetDiagnosticsMessage(diagnosticsByFile));
            }

            var existingContent = File.Exists(compiledFilePath) ? File.ReadAllText(compiledFilePath) : string.Empty;

            var emitter = new TemplateEmitter(compilation.GetEntrypointSemanticModel(), emitterSettings);

            using var fileStream = new FileStream(compiledFilePath, FileMode.Create, FileAccess.Write);
            var result = emitter.EmitParametersFile(fileStream, existingContent);

            return("Generating parameters file succeeded. Processed file " + compiledFile);
        }
示例#6
0
        private string GenerateCompiledFileAndReturnBuildOutputMessage(string bicepFilePath, DocumentUri documentUri)
        {
            string compiledFilePath = PathHelper.GetDefaultBuildOutputPath(bicepFilePath);
            string compiledFile     = Path.GetFileName(compiledFilePath);

            // If the template exists and contains bicep generator metadata, we can go ahead and replace the file.
            // If not, we'll fail the build.
            if (File.Exists(compiledFilePath) && !TemplateContainsBicepGeneratorMetadata(File.ReadAllText(compiledFilePath)))
            {
                return("Build failed. The file \"" + compiledFile + "\" already exists and was not generated by Bicep. If overwriting the file is intended, delete it manually and retry the Build command.");
            }

            var fileUri = documentUri.ToUri();
            RootConfiguration?configuration = null;

            try
            {
                configuration = this.configurationManager.GetConfiguration(fileUri);
            }
            catch (ConfigurationException exception)
            {
                // Fail the build if there's configuration errors.
                return(exception.Message);
            }

            CompilationContext?context = compilationManager.GetCompilation(fileUri);
            Compilation        compilation;

            if (context is null)
            {
                SourceFileGrouping sourceFileGrouping = SourceFileGroupingBuilder.Build(this.fileResolver, this.moduleDispatcher, new Workspace(), fileUri, configuration);
                compilation = new Compilation(namespaceProvider, sourceFileGrouping, configuration);
            }
            else
            {
                compilation = context.Compilation;
            }

            KeyValuePair <BicepFile, IEnumerable <IDiagnostic> > diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile()
                                                                                     .FirstOrDefault(x => x.Key.FileUri == fileUri);

            if (diagnosticsByFile.Value.Any(x => x.Level == DiagnosticLevel.Error))
            {
                return(GetDiagnosticsMessage(diagnosticsByFile));
            }

            using var fileStream = new FileStream(compiledFilePath, FileMode.Create, FileAccess.ReadWrite);
            var        emitter = new TemplateEmitter(compilation.GetEntrypointSemanticModel(), emitterSettings);
            EmitResult result  = emitter.Emit(fileStream);

            return("Build succeeded. Created file " + compiledFile);
        }
示例#7
0
 public Compilation(IResourceTypeProvider resourceTypeProvider, SourceFileGrouping sourceFileGrouping, ImmutableDictionary <ISourceFile, ISemanticModel>?modelLookup = null)
 {
     this.SourceFileGrouping      = sourceFileGrouping;
     this.ResourceTypeProvider    = resourceTypeProvider;
     this.lazySemanticModelLookup = sourceFileGrouping.SourceFiles.ToImmutableDictionary(
         sourceFile => sourceFile,
         sourceFile => (modelLookup is not null && modelLookup.TryGetValue(sourceFile, out var existingModel)) ?
         new(existingModel) :
         new Lazy <ISemanticModel>(() => sourceFile switch
     {
         BicepFile bicepFile => new SemanticModel(this, bicepFile, SourceFileGrouping.FileResolver),
         ArmTemplateFile armTemplateFile => new ArmTemplateSemanticModel(armTemplateFile),
         _ => throw new ArgumentOutOfRangeException(nameof(sourceFile)),
     }));
示例#8
0
            static IEnumerable <IDiagnostic> GetModuleDiagnosticsPerFile(SourceFileGrouping grouping, BicepFile bicepFile, ImmutableHashSet <ModuleDeclarationSyntax> originalModulesToRestore)
            {
                foreach (var module in bicepFile.ProgramSyntax.Declarations.OfType <ModuleDeclarationSyntax>())
                {
                    if (!originalModulesToRestore.Contains(module))
                    {
                        continue;
                    }

                    if (grouping.TryLookUpModuleErrorDiagnostic(module, out var error))
                    {
                        yield return(error);
                    }
                }
            }
        private async Task <string> GenerateForceModulesRestoreOutputMessage(string bicepFilePath, DocumentUri documentUri)
        {
            var fileUri = documentUri.ToUri();
            RootConfiguration?configuration = null;

            try
            {
                configuration = this.configurationManager.GetConfiguration(fileUri);
            }
            catch (ConfigurationException exception)
            {
                // Fail the restore if there's configuration errors.
                return(exception.Message);
            }
            Workspace          workspace          = new Workspace();
            SourceFileGrouping sourceFileGrouping = SourceFileGroupingBuilder.Build(this.fileResolver, this.moduleDispatcher, workspace, fileUri, configuration);

            // Ignore modules to restore logic, include all modules to be restored
            var modulesToRestore = sourceFileGrouping.SourceFilesByModuleDeclaration
                                   .Select(kvp => kvp.Key)
                                   .Union(sourceFileGrouping.ModulesToRestore)
                                   .ToImmutableHashSet();

            // RestoreModules() does a distinct but we'll do it also to prevent deuplicates in outputs and logging
            var modulesToRestoreReferences = this.moduleDispatcher.GetValidModuleReferences(modulesToRestore, configuration)
                                             .Distinct()
                                             .OrderBy(key => key.FullyQualifiedReference);

            if (!modulesToRestoreReferences.Any())
            {
                return($"Restore (force) skipped. No modules references in input file.");
            }

            // restore is supposed to only restore the module references that are syntactically valid
            await this.moduleDispatcher.RestoreModules(configuration, modulesToRestoreReferences, forceModulesRestore : true);

            // if all are marked as success
            var sbRestoreSummary = new StringBuilder();

            foreach (var module in modulesToRestoreReferences)
            {
                var restoreStatus = this.moduleDispatcher.GetModuleRestoreStatus(module, configuration, out _);
                sbRestoreSummary.Append($"{Environment.NewLine}  * {module.FullyQualifiedReference}: {restoreStatus}");
            }

            return($"Restore (force) summary: {sbRestoreSummary}");
        }
示例#10
0
        public Compilation(INamespaceProvider namespaceProvider, SourceFileGrouping sourceFileGrouping, RootConfiguration configuration, ImmutableDictionary <ISourceFile, ISemanticModel>?modelLookup = null)
        {
            this.SourceFileGrouping = sourceFileGrouping;
            this.NamespaceProvider  = namespaceProvider;
            this.Configuration      = configuration;

            var fileResolver = SourceFileGrouping.FileResolver;

            this.lazySemanticModelLookup = sourceFileGrouping.SourceFiles.ToImmutableDictionary(
                sourceFile => sourceFile,
                sourceFile => (modelLookup is not null && modelLookup.TryGetValue(sourceFile, out var existingModel)) ?
                new(existingModel) :
                new Lazy <ISemanticModel>(() => sourceFile switch
            {
                BicepFile bicepFile => new SemanticModel(this, bicepFile, fileResolver, configuration),
                ArmTemplateFile armTemplateFile => new ArmTemplateSemanticModel(armTemplateFile),
                TemplateSpecFile templateSpecFile => new TemplateSpecSemanticModel(templateSpecFile),
                _ => throw new ArgumentOutOfRangeException(nameof(sourceFile)),
            }));
示例#11
0
        private CompilationContext CreateContext(SourceFileGrouping syntaxTreeGrouping, ImmutableDictionary <ISourceFile, ISemanticModel> modelLookup)
        {
            var compilation = new Compilation(resourceTypeProvider, syntaxTreeGrouping, modelLookup);

            return(new CompilationContext(compilation));
        }
示例#12
0
 private static IReadOnlyDictionary <BicepFile, IEnumerable <IDiagnostic> > GetModuleRestoreDiagnosticsByBicepFile(SourceFileGrouping sourceFileGrouping, ImmutableHashSet <ModuleDeclarationSyntax> originalModulesToRestore)
 {
示例#13
0
        private CompilationContext CreateContext(SourceFileGrouping syntaxTreeGrouping, ImmutableDictionary <ISourceFile, ISemanticModel> modelLookup, RootConfiguration configuration, LinterAnalyzer linterAnalyzer)
        {
            var compilation = new Compilation(this.features, namespaceProvider, syntaxTreeGrouping, configuration, linterAnalyzer, modelLookup);

            return(new CompilationContext(compilation));
        }