Example #1
0
        protected override bool GeneratePackage(string nupkg, List <DiagnosticMessage> packDiagnostics)
        {
            var compilerOptions = Project.GetCompilerOptions(
                Project.GetTargetFramework(targetFramework: null).FrameworkName, Configuration);

            if (compilerOptions.CompileInclude == null)
            {
                foreach (var path in Project.Files.SourceFiles)
                {
                    var srcFile = new PhysicalPackageFile
                    {
                        SourcePath = path,
                        TargetPath = Path.Combine("src", Common.PathUtility.GetRelativePath(Project.ProjectDirectory, path))
                    };

                    PackageBuilder.Files.Add(srcFile);
                }
            }
            else
            {
                var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);
                foreach (var entry in includeFiles)
                {
                    var srcFile = new PhysicalPackageFile
                    {
                        SourcePath = entry.SourcePath,
                        TargetPath = Path.Combine("src", entry.TargetPath)
                    };

                    PackageBuilder.Files.Add(srcFile);
                }
            }

            return(base.GeneratePackage(nupkg, packDiagnostics));
        }
Example #2
0
        private bool HasSourceFiles(ProjectDescription project, CommonCompilerOptions compilerOptions)
        {
            if (compilerOptions.CompileInclude == null)
            {
                return(project.Project.Files.SourceFiles.Any());
            }

            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);

            return(includeFiles.Any());
        }
Example #3
0
        public static IEnumerable <string> GetCompilationSources(ProjectContext project, CommonCompilerOptions compilerOptions)
        {
            if (compilerOptions.CompileInclude == null)
            {
                return(project.ProjectFile.Files.SourceFiles);
            }

            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);

            return(includeFiles.Select(f => f.SourcePath));
        }
Example #4
0
        public static IEnumerable <string> ResolveFiles(this IncludeContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return(IncludeFilesResolver
                   .GetIncludeFiles(context, "/", diagnostics: null)
                   .Select(f => f.SourcePath));
        }
Example #5
0
        private static IEnumerable <string> GetSourceFiles(ProjectContext context, string configuration)
        {
            var compilerOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

            if (compilerOptions.CompileInclude == null)
            {
                return(context.ProjectFile.Files.SourceFiles);
            }

            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);

            return(includeFiles.Select(f => f.SourcePath));
        }
Example #6
0
        private static bool HasSourceFiles(ProjectContext context)
        {
            var compilerOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, null);

            if (compilerOptions.CompileInclude == null)
            {
                return(context.ProjectFile.Files.SourceFiles.Any());
            }

            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);

            return(includeFiles.Any());
        }
        private IEnumerable <string> GetResourceFiles()
        {
            var compilerOptions = Project.GetCompilerOptions(Framework, Configuration);

            if (compilerOptions.EmbedInclude == null)
            {
                return(Project.Files.ResourceFiles.Keys);
            }

            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.EmbedInclude, "/", diagnostics: null);

            return(includeFiles.Select(f => f.SourcePath));
        }
Example #8
0
        private bool HasSourceFiles()
        {
            var compilerOptions = _project.GetCompilerOptions(
                _project.GetTargetFramework(targetFramework: null).FrameworkName, _configuration);

            if (compilerOptions.CompileInclude == null)
            {
                return(_project.Files.SourceFiles.Any());
            }

            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);

            return(includeFiles.Any());
        }
Example #9
0
        public static List <NonCultureResgenIO> GetNonCultureResourcesFromIncludeEntries(Project project, string intermediateOutputPath, CommonCompilerOptions compilationOptions)
        {
            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilationOptions.EmbedInclude, "/", diagnostics: null);

            return
                ((from resourceFile in includeFiles
                  let inputFile = resourceFile.SourcePath
                                  where string.IsNullOrEmpty(ResourceUtility.GetResourceCultureName(inputFile))
                                  let target = resourceFile.IsCustomTarget ? resourceFile.TargetPath : null
                                               let metadataName = GetResourceFileMetadataName(project, resourceFile.SourcePath, target)
                                                                  let outputFile = ResourceUtility.IsResxFile(inputFile) ? Path.Combine(intermediateOutputPath, metadataName) : null
                                                                                   select new NonCultureResgenIO(inputFile, outputFile, metadataName))
                 .ToList());
        }
Example #10
0
        protected virtual bool GeneratePackage(string nupkg, List <DiagnosticMessage> packDiagnostics)
        {
            foreach (var sharedFile in Project.Files.SharedFiles)
            {
                var file = new PhysicalPackageFile();
                file.SourcePath = sharedFile;
                file.TargetPath = Path.Combine("shared", Path.GetFileName(sharedFile));
                PackageBuilder.Files.Add(file);
            }

            if (Project.PackOptions.PackInclude != null)
            {
                var files = IncludeFilesResolver.GetIncludeFiles(
                    Project.PackOptions.PackInclude,
                    "/",
                    diagnostics: packDiagnostics);
                PackageBuilder.Files.AddRange(GetPackageFiles(files, packDiagnostics));
            }
            else if (Project.Files.PackInclude != null && Project.Files.PackInclude.Any())
            {
                AddPackageFiles(Project.Files.PackInclude, packDiagnostics);
            }

            // Write the packages as long as we're still in a success state.
            if (!packDiagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error))
            {
                Reporter.Verbose.WriteLine($"Adding package files");
                foreach (var file in PackageBuilder.Files.OfType <PhysicalPackageFile>())
                {
                    if (file.SourcePath != null && File.Exists(file.SourcePath))
                    {
                        Reporter.Verbose.WriteLine($"Adding {file.Path.Yellow()}");
                    }
                }

                Directory.CreateDirectory(Path.GetDirectoryName(nupkg));

                using (var fs = File.Create(nupkg))
                {
                    PackageBuilder.Save(fs);
                    Reporter.Output.WriteLine($"{Project.Name} -> {Path.GetFullPath(nupkg)}");
                }

                return(true);
            }

            return(false);
        }
Example #11
0
        public static List <CultureResgenIO> GetCultureResourcesFromIncludeEntries(Project project, string outputPath, CommonCompilerOptions compilationOptions)
        {
            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilationOptions.EmbedInclude, "/", diagnostics: null);

            return
                ((from resourceFileGroup in includeFiles
                  .GroupBy(resourceFile => ResourceUtility.GetResourceCultureName(resourceFile.SourcePath))
                  let culture = resourceFileGroup.Key
                                where !string.IsNullOrEmpty(culture)
                                let inputFileToMetadata = resourceFileGroup.ToDictionary(
                      r => r.SourcePath, r => GetResourceFileMetadataName(project, r.SourcePath, r.IsCustomTarget ? r.TargetPath : null))
                                                          let resourceOutputPath = Path.Combine(outputPath, culture)
                                                                                   let outputFile = Path.Combine(resourceOutputPath, project.Name + ".resources.dll")
                                                                                                    select new CultureResgenIO(culture, inputFileToMetadata, outputFile))
                 .ToList());
        }
Example #12
0
        private void CopyContentFiles()
        {
            var contentFiles = new ContentFiles(_context);

            if (_compilerOptions.CopyToOutputInclude != null)
            {
                var includeEntries = IncludeFilesResolver.GetIncludeFiles(
                    _compilerOptions.CopyToOutputInclude,
                    PathUtility.EnsureTrailingSlash(_runtimeOutputPath),
                    diagnostics: null);

                contentFiles.StructuredCopyTo(_runtimeOutputPath, includeEntries);
            }
            else
            {
                contentFiles.StructuredCopyTo(_runtimeOutputPath);
            }
        }
Example #13
0
        protected virtual void ProcessContext(ProjectContext context)
        {
            PopulateDependencies(context);

            var inputFolder = ArtifactPathsCalculator.InputPathForContext(context);

            var compilerOptions = Project.GetCompilerOptions(context.TargetFramework, Configuration);
            var outputName      = compilerOptions.OutputName;
            var outputExtension =
                context.TargetFramework.IsDesktop() && compilerOptions.EmitEntryPoint.GetValueOrDefault()
                    ? ".exe" : ".dll";

            IEnumerable <string> resourceCultures = null;

            if (compilerOptions.EmbedInclude == null)
            {
                resourceCultures = context.ProjectFile.Files.ResourceFiles
                                   .Select(resourceFile => ResourceUtility.GetResourceCultureName(resourceFile.Key))
                                   .Distinct();
            }
            else
            {
                var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.EmbedInclude, "/", diagnostics: null);
                resourceCultures = includeFiles
                                   .Select(file => ResourceUtility.GetResourceCultureName(file.SourcePath))
                                   .Distinct();
            }

            foreach (var culture in resourceCultures)
            {
                if (string.IsNullOrEmpty(culture))
                {
                    continue;
                }

                var resourceFilePath = Path.Combine(culture, $"{outputName}.resources.dll");
                TryAddOutputFile(context, inputFolder, resourceFilePath);
            }

            TryAddOutputFile(context, inputFolder, outputName + outputExtension);
            TryAddOutputFile(context, inputFolder, $"{outputName}.xml");
            TryAddOutputFile(context, inputFolder, $"{outputName}.runtimeconfig.json");
        }
Example #14
0
        public bool Compile(ProjectContext context, string config, string buildBasePath)
        {
            // Set up Output Paths
            var outputPaths            = context.GetOutputPaths(config, buildBasePath);
            var outputPath             = outputPaths.CompilationOutputPath;
            var intermediateOutputPath = outputPaths.IntermediateOutputDirectoryPath;

            Directory.CreateDirectory(outputPath);
            Directory.CreateDirectory(intermediateOutputPath);

            // Create the library exporter
            var exporter = context.CreateExporter(config, buildBasePath);

            // Gather exports for the project
            var dependencies = exporter.GetDependencies().ToList();

            var diagnostics = new List <DiagnosticMessage>();
            var missingFrameworkDiagnostics = new List <DiagnosticMessage>();

            // Collect dependency diagnostics
            foreach (var diag in context.LibraryManager.GetAllDiagnostics())
            {
                if (diag.ErrorCode == ErrorCodes.DOTNET1011 ||
                    diag.ErrorCode == ErrorCodes.DOTNET1012)
                {
                    missingFrameworkDiagnostics.Add(diag);
                }

                diagnostics.Add(diag);
            }

            if (diagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error))
            {
                // We got an unresolved dependency or missing framework. Don't continue the compilation.
                return(false);
            }

            // Get compilation options
            var outputName         = outputPaths.CompilationFiles.Assembly;
            var compilationOptions = context.ResolveCompilationOptions(config);

            // Set default platform if it isn't already set and we're on desktop
            if (compilationOptions.EmitEntryPoint == true && string.IsNullOrEmpty(compilationOptions.Platform) && context.TargetFramework.IsDesktop())
            {
                // See https://github.com/dotnet/cli/issues/2428 for more details.
                compilationOptions.Platform = RuntimeInformation.ProcessArchitecture == Architecture.X64 ?
                                              "x64" : "anycpu32bitpreferred";
            }

            var references  = new List <string>();
            var sourceFiles = new List <string>();

            // Add metadata options
            var assemblyInfoOptions = AssemblyInfoOptions.CreateForProject(context);

            foreach (var dependency in dependencies)
            {
                references.AddRange(dependency.CompilationAssemblies.Select(r => r.ResolvedPath));
                sourceFiles.AddRange(dependency.SourceReferences.Select(s => s.GetTransformedFile(intermediateOutputPath)));
            }

            var resources = new List <string>();

            if (compilationOptions.PreserveCompilationContext == true)
            {
                var allExports        = exporter.GetAllExports().ToList();
                var dependencyContext = new DependencyContextBuilder().Build(compilationOptions,
                                                                             allExports,
                                                                             allExports,
                                                                             false, // For now, just assume non-portable mode in the legacy deps file (this is going away soon anyway)
                                                                             context.TargetFramework,
                                                                             context.RuntimeIdentifier ?? string.Empty);

                var writer       = new DependencyContextWriter();
                var depsJsonFile = Path.Combine(intermediateOutputPath, compilationOptions.OutputName + "dotnet-compile.deps.json");
                using (var fileStream = File.Create(depsJsonFile))
                {
                    writer.Write(dependencyContext, fileStream);
                }

                resources.Add($"\"{depsJsonFile}\",{compilationOptions.OutputName}.deps.json");
            }

            // Add project source files
            if (compilationOptions.CompileInclude == null)
            {
                sourceFiles.AddRange(context.ProjectFile.Files.SourceFiles);
            }
            else
            {
                var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilationOptions.CompileInclude, "/", diagnostics: null);
                sourceFiles.AddRange(includeFiles.Select(f => f.SourcePath));
            }

            if (String.IsNullOrEmpty(intermediateOutputPath))
            {
                return(false);
            }

            var translated = TranslateCommonOptions(compilationOptions, outputName);

            var allArgs = new List <string>(translated);

            allArgs.AddRange(GetDefaultOptions());

            // Generate assembly info
            var assemblyInfo = Path.Combine(intermediateOutputPath, $"dotnet-compile.assemblyinfo.cs");

            File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateCSharp(assemblyInfoOptions, sourceFiles));

            allArgs.Add($"\"{assemblyInfo}\"");

            if (!String.IsNullOrEmpty(outputName))
            {
                allArgs.Add($"-out:\"{outputName}\"");
            }

            allArgs.AddRange(references.Select(r => $"-r:\"{r}\""));
            allArgs.AddRange(resources.Select(resource => $"-resource:{resource}"));
            allArgs.AddRange(sourceFiles.Select(s => $"\"{s}\""));
            allArgs.Prepend($"-noconfig");

            // Execute CSC!
            var result = RunCsc(allArgs.ToArray())
                         .WorkingDirectory(Directory.GetCurrentDirectory())
                         .ForwardStdErr()
                         .ForwardStdOut()
                         .Execute();

            return(result.ExitCode == 0);
        }
Example #15
0
        /// <summary>
        /// Publish the project for given 'framework (ex - netcoreapp1.0)' and 'runtimeID (ex - win7-x64)'
        /// </summary>
        /// <param name="context">project that is to be published</param>
        /// <param name="baseOutputPath">Location of published files</param>
        /// <param name="configuration">Debug or Release</param>
        /// <param name="nativeSubdirectories"></param>
        /// <returns>Return 0 if successful else return non-zero</returns>
        private bool PublishProjectContext(ProjectContext context, string buildBasePath, string outputPath, string configuration, bool nativeSubdirectories)
        {
            var target = context.TargetFramework.DotNetFrameworkName;

            if (!string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                target = $"{target}/{context.RuntimeIdentifier}";
            }
            Reporter.Output.WriteLine($"Publishing {context.RootProject.Identity.Name.Yellow()} for {target.Yellow()}");

            var options     = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            var outputPaths = context.GetOutputPaths(configuration, buildBasePath, outputPath);

            if (string.IsNullOrEmpty(outputPath))
            {
                outputPath = Path.Combine(outputPaths.RuntimeOutputPath, PublishSubfolderName);
            }

            var contextVariables = new Dictionary <string, string>
            {
                { "publish:ProjectPath", context.ProjectDirectory },
                { "publish:Configuration", configuration },
                { "publish:OutputPath", outputPath },
                { "publish:TargetFramework", context.TargetFramework.GetShortFolderName() },
                { "publish:FullTargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "publish:Runtime", context.RuntimeIdentifier },
            };

            RunScripts(context, ScriptNames.PrePublish, contextVariables);

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            // Compile the project (and transitively, all it's dependencies)
            if (ShouldBuild && !InvokeBuildOnProject(context, buildBasePath, configuration))
            {
                return(false);
            }

            // Use a library exporter to collect publish assets
            var exporter = context.CreateExporter(configuration, buildBasePath);

            // Get the output paths used by the call to `dotnet build` above (since we didn't pass `--output`, they will be different from
            // our current output paths)
            var buildOutputPaths = context.GetOutputPaths(configuration, buildBasePath);

            var exports = exporter.GetAllExports();

            var exportsLookup         = exports.ToDictionary(e => e.Library.Identity.Name, StringComparer.OrdinalIgnoreCase);
            var platformExclusionList = context.GetPlatformExclusionList(exportsLookup);
            var buildExclusionList    = context.GetTypeBuildExclusionList(exportsLookup);
            var allExclusionList      = new HashSet <string>(platformExclusionList);

            allExclusionList.UnionWith(buildExclusionList);
            var filteredExports = exports.FilterExports(allExclusionList);

            foreach (var export in filteredExports)
            {
                Reporter.Verbose.WriteLine($"publish: Publishing {export.Library.Identity.ToString().Green().Bold()} ...");

                PublishAssetGroups(export.RuntimeAssemblyGroups, outputPath, nativeSubdirectories: false, includeRuntimeGroups: context.IsPortable);
                PublishAssetGroups(export.NativeLibraryGroups, outputPath, nativeSubdirectories, includeRuntimeGroups: context.IsPortable);

                var runtimeAssetsToCopy = export.RuntimeAssets.Where(a => ShouldCopyExportRuntimeAsset(context, buildOutputPaths, export, a));
                runtimeAssetsToCopy.StructuredCopyTo(outputPath, outputPaths.IntermediateOutputDirectoryPath);

                foreach (var resourceAsset in export.ResourceAssemblies)
                {
                    var dir = Path.Combine(outputPath, resourceAsset.Locale);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.Copy(resourceAsset.Asset.ResolvedPath, Path.Combine(dir, resourceAsset.Asset.FileName), overwrite: true);
                }
            }
            foreach (var export in exports)
            {
                if (options.PreserveCompilationContext.GetValueOrDefault())
                {
                    PublishRefs(export, outputPath);
                }
            }

            if (context.ProjectFile.HasRuntimeOutput(configuration) && !context.TargetFramework.IsDesktop())
            {
                // Make executable in the new location
                var executable         = new Executable(context, buildOutputPaths, outputPath, buildOutputPaths.IntermediateOutputDirectoryPath, exporter, configuration);
                var runtimeExports     = filteredExports;
                var compilationExports = exports.FilterExports(buildExclusionList);

                executable.WriteConfigurationFiles(exports, runtimeExports, compilationExports, includeDevConfig: false);
            }

            var contentFiles = new ContentFiles(context);

            if (context.ProjectFile.PublishOptions != null)
            {
                var includeEntries = IncludeFilesResolver.GetIncludeFiles(
                    context.ProjectFile.PublishOptions,
                    PathUtility.EnsureTrailingSlash(outputPath),
                    diagnostics: null);

                contentFiles.StructuredCopyTo(outputPath, includeEntries);
            }
            else
            {
                contentFiles.StructuredCopyTo(outputPath);
            }

            // Publish a host if this is an application
            if (options.EmitEntryPoint.GetValueOrDefault() && !string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                Reporter.Verbose.WriteLine($"publish: Renaming native host in output to create fully standalone output.");
                RenamePublishedHost(context, outputPath, options);
            }

            RunScripts(context, ScriptNames.PostPublish, contextVariables);

            Reporter.Output.WriteLine($"publish: Published to {outputPath}".Green().Bold());

            return(true);
        }
Example #16
0
 private IEnumerable <IncludeEntry> GetIncludeFiles(IncludeContext context, string targetBasePath)
 {
     return(IncludeFilesResolver.GetIncludeFiles(context, targetBasePath, null));
 }
Example #17
0
        private ProjectId AddProject(ProjectContext project)
        {
            // Create the framework specific project and add it to the workspace
            var projectInfo = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Create(),
                project.ProjectFile.Name + "+" + project.TargetFramework,
                project.ProjectFile.Name,
                LanguageNames.CSharp,
                project.ProjectFile.ProjectFilePath);

            OnProjectAdded(projectInfo);

            // TODO: ctor argument?
            var configuration = "Debug";

            var compilerOptions = project.GetLanguageSpecificCompilerOptions(project.TargetFramework, configuration);

            var compilationSettings = ToCompilationSettings(compilerOptions, project.TargetFramework, project.ProjectFile.ProjectDirectory);

            OnParseOptionsChanged(projectInfo.Id, new CSharpParseOptions(compilationSettings.LanguageVersion, preprocessorSymbols: compilationSettings.Defines));

            OnCompilationOptionsChanged(projectInfo.Id, compilationSettings.CompilationOptions);

            IEnumerable <string> sourceFiles = null;

            if (compilerOptions.CompileInclude == null)
            {
                sourceFiles = project.ProjectFile.Files.SourceFiles;
            }
            else
            {
                var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);
                sourceFiles = includeFiles.Select(f => f.SourcePath);
            }

            foreach (var file in sourceFiles)
            {
                using (var stream = File.OpenRead(file))
                {
                    AddSourceFile(projectInfo, file, stream);
                }
            }

            var exporter = project.CreateExporter(configuration);

            foreach (var dependency in exporter.GetDependencies())
            {
                var projectDependency = dependency.Library as ProjectDescription;
                if (projectDependency != null)
                {
                    var projectDependencyContext = ProjectContext.Create(projectDependency.Project.ProjectFilePath, projectDependency.Framework);

                    var id = AddProject(projectDependencyContext);

                    OnProjectReferenceAdded(projectInfo.Id, new ProjectReference(id));
                }
                else
                {
                    foreach (var asset in dependency.CompilationAssemblies)
                    {
                        OnMetadataReferenceAdded(projectInfo.Id, GetMetadataReference(asset.ResolvedPath));
                    }
                }

                foreach (var file in dependency.SourceReferences)
                {
                    using (var stream = file.GetTransformedStream())
                    {
                        AddSourceFile(projectInfo, file.ResolvedPath, stream);
                    }
                }
            }

            return(projectInfo.Id);
        }