Example #1
0
        private void CalculateDefaultsForNonAssigned()
        {
            if (string.IsNullOrWhiteSpace(Project))
            {
                Project = Directory.GetCurrentDirectory();
            }

            if (string.IsNullOrWhiteSpace(Configuration))
            {
                Configuration = Constants.DefaultConfiguration;
            }

            var contexts = ProjectContext.CreateContextForEachFramework(Project);
            if (Framework == null)
            {
                _context = contexts.First();
            }
            else
            {
                var fx = NuGetFramework.Parse(Framework);
                _context = contexts.FirstOrDefault(c => c.TargetFramework.Equals(fx));
            }

            if (Args == null)
            {
                _args = new List<string>();
            }
            else
            {
                _args = new List<string>(Args);
            }
        }
Example #2
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 compilationOptions = project.ProjectFile.GetCompilerOptions(project.TargetFramework, configuration);

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

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

            OnCompilationOptionsChanged(projectInfo.Id, compilationSettings.CompilationOptions);

            foreach (var file in project.ProjectFile.Files.SourceFiles)
            {
                AddSourceFile(projectInfo, file);
            }

            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)
                {
                    AddSourceFile(projectInfo, file);
                }
            }

            return projectInfo.Id;
        }
Example #3
0
        public static void PopulateDependencies(ProjectContext context, PackageBuilder packageBuilder)
        {
            var dependencies = new List<PackageDependency>();
            var project = context.RootProject;

            foreach (var dependency in project.Dependencies)
            {
                if (!dependency.HasFlag(LibraryDependencyTypeFlag.BecomesNupkgDependency))
                {
                    continue;
                }

                // TODO: Efficiency
                var dependencyDescription = context.LibraryManager.GetLibraries().First(l => l.RequestedRanges.Contains(dependency));

                // REVIEW: Can we get this far with unresolved dependencies
                if (dependencyDescription == null || !dependencyDescription.Resolved)
                {
                    continue;
                }

                if (dependencyDescription.Identity.Type == LibraryType.Project &&
                    ((ProjectDescription)dependencyDescription).Project.EmbedInteropTypes)
                {
                    continue;
                }

                if (dependency.Target == LibraryType.ReferenceAssembly)
                {
                    packageBuilder.FrameworkAssemblies.Add(new FrameworkAssemblyReference(dependency.Name, new[] { context.TargetFramework }));

                    Reporter.Verbose.WriteLine($"Adding framework assembly {dependency.Name.Yellow()}");
                }
                else
                {
                    VersionRange dependencyVersion = null;

                    if (dependency.VersionRange == null ||
                        dependency.VersionRange.IsFloating)
                    {
                        dependencyVersion = new VersionRange(dependencyDescription.Identity.Version);
                    }
                    else
                    {
                        dependencyVersion = dependency.VersionRange;
                    }

                    Reporter.Verbose.WriteLine($"Adding dependency {dependency.Name.Yellow()} {VersionUtility.RenderVersion(dependencyVersion).Yellow()}");

                    dependencies.Add(new PackageDependency(dependency.Name, dependencyVersion));
                }
            }

            packageBuilder.DependencySets.Add(new PackageDependencySet(context.TargetFramework, dependencies));
        }
Example #4
0
        private static int Run(ProjectContext context, string configuration, List<string> remainingArguments, bool preserveTemporaryOutput)
        {
            // Create a temporary directory
            var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));

            // Compile to that directory
            var result = Command.Create($"dotnet-compile", $"--output \"{tempDir}\" --framework \"{context.TargetFramework}\" --configuration \"{configuration}\" {context.ProjectFile.ProjectDirectory}")
                .ForwardStdOut(onlyIfVerbose: true)
                .ForwardStdErr()
                .Execute();

            if (result.ExitCode != 0)
            {
                return result.ExitCode;
            }

            // Now launch the output and give it the results
            var outputName = Path.Combine(tempDir, context.ProjectFile.Name + Constants.ExeSuffix);
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (context.TargetFramework.IsDesktop())
                {
                    // Run mono if we're running a desktop target on non windows
                    remainingArguments.Insert(0, outputName + ".exe");

                    if (string.Equals(configuration, "Debug", StringComparison.OrdinalIgnoreCase))
                    {
                        // If we're compiling for the debug configuration then add the --debug flag
                        // other options may be passed using the MONO_OPTIONS env var
                        remainingArguments.Insert(0, "--debug");
                    }

                    outputName = "mono";
                }
            }

            result = Command.Create(outputName, string.Join(" ", remainingArguments))
                .ForwardStdOut()
                .ForwardStdErr()
                .EnvironmentVariable("CLRHOST_CLR_PATH", AppContext.BaseDirectory)
                .Execute();

            // Clean up
            if (!preserveTemporaryOutput)
            {
                Directory.Delete(tempDir, recursive: true);
            }

            return result.ExitCode;
        }
Example #5
0
        private static void MakeRunnable(ProjectContext runtimeContext, string outputPath, LibraryExporter exporter)
        {
            CopyContents(runtimeContext, outputPath);

            if (runtimeContext.TargetFramework.IsDesktop())
            {
                // On desktop we need to copy dependencies since we don't own the host
                foreach (var export in exporter.GetDependencies())
                {
                    CopyExport(outputPath, export);
                }
            }
            else
            {
                EmitHost(runtimeContext, outputPath, exporter);
            }
        }
Example #6
0
        private static string GetIntermediateOutputPath(ProjectContext context, string configuration, string intermediateOutputValue, string outputOptionValue)
        {
            var intermediateOutputPath = string.Empty;

            if (string.IsNullOrEmpty(intermediateOutputValue))
            {
                intermediateOutputPath = Path.Combine(
                    GetDefaultRootOutputPath(context, outputOptionValue),
                    Constants.ObjDirectoryName,
                    configuration,
                    context.TargetFramework.GetTwoDigitShortFolderName());
            }
            else
            {
                intermediateOutputPath = intermediateOutputValue;
            }

            return intermediateOutputPath;
        }
Example #7
0
        private static string GetDefaultRootOutputPath(ProjectContext context, string outputOptionValue)
        {
            string rootOutputPath = string.Empty;

            if (string.IsNullOrEmpty(outputOptionValue))
            {
                rootOutputPath = context.ProjectFile.ProjectDirectory;
            }

            return rootOutputPath;
        }
Example #8
0
        private static void EmitHost(ProjectContext runtimeContext, string outputPath, LibraryExporter exporter)
        {
            // Write the Host information file (basically a simplified form of the lock file)
            var lines = new List<string>();
            foreach (var export in exporter.GetAllExports())
            {
                if (export.Library == runtimeContext.RootProject)
                {
                    continue;
                }

                if (export.Library is ProjectDescription)
                {
                    // Copy project dependencies to the output folder
                    CopyFiles(export.RuntimeAssemblies, outputPath);
                    CopyFiles(export.NativeLibraries, outputPath);
                }
                else
                {
                    lines.AddRange(GenerateLines(export, export.RuntimeAssemblies, "runtime"));
                    lines.AddRange(GenerateLines(export, export.NativeLibraries, "native"));
                }
            }

            File.WriteAllLines(Path.Combine(outputPath, runtimeContext.ProjectFile.Name + ".deps"), lines);

            // Copy the host in
            CopyHost(Path.Combine(outputPath, runtimeContext.ProjectFile.Name + Constants.ExeSuffix));
        }
Example #9
0
        private static bool Compile(ProjectContext context, string configuration, string outputOptionValue, string intermediateOutputValue, bool buildProjectReferences)
        {
            // Set up Output Paths
            string outputPath = GetOutputPath(context, configuration, outputOptionValue);
            string intermediateOutputPath = GetIntermediateOutputPath(context, configuration, intermediateOutputValue, outputOptionValue);

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

            // Create the library exporter
            var exporter = context.CreateExporter(configuration);

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

            if (buildProjectReferences)
            {
                var projects = new Dictionary<string, ProjectDescription>();

                // Build project references
                foreach (var dependency in dependencies)
                {
                    var projectDependency = dependency.Library as ProjectDescription;

                    if (projectDependency != null && projectDependency.Project.Files.SourceFiles.Any())
                    {
                        projects[projectDependency.Identity.Name] = projectDependency;
                    }
                }

                foreach (var projectDependency in Sort(projects))
                {
                    // Skip compiling project dependencies since we've already figured out the build order
                    var compileResult = Command.Create("dotnet-compile", $"--framework {projectDependency.Framework} --configuration {configuration} --output \"{outputPath}\" --temp-output \"{intermediateOutputPath}\" --no-project-dependencies \"{projectDependency.Project.ProjectDirectory}\"")
                            .ForwardStdOut()
                            .ForwardStdErr()
                            .Execute();

                    if (compileResult.ExitCode != 0)
                    {
                        return false;
                    }
                }

                projects.Clear();
            }

            Reporter.Output.WriteLine($"Compiling {context.RootProject.Identity.Name.Yellow()} for {context.TargetFramework.DotNetFrameworkName.Yellow()}");
            var sw = Stopwatch.StartNew();

            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 (missingFrameworkDiagnostics.Count > 0)
            {
                // The framework isn't installed so we should short circuit the rest of the compilation
                // so we don't get flooded with errors
                PrintSummary(missingFrameworkDiagnostics, sw);
                return false;
            }

            // Dump dependency data
            // TODO: Turn on only if verbose, we can look at the response
            // file anyways
            // ShowDependencyInfo(dependencies);

            // Get compilation options
            var outputName = GetProjectOutput(context.ProjectFile, context.TargetFramework, configuration, outputPath);

            // Assemble args
            var compilerArgs = new List<string>()
            {
                $"--temp-output:{intermediateOutputPath}",
                $"--out:{outputName}"
            };

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

            if (!string.IsNullOrEmpty(compilationOptions.KeyFile))
            {
                // Resolve full path to key file
                compilationOptions.KeyFile = Path.GetFullPath(Path.Combine(context.ProjectFile.ProjectDirectory, compilationOptions.KeyFile));
            }

            // Add compilation options to the args
            compilerArgs.AddRange(compilationOptions.SerializeToArgs());

            foreach (var dependency in dependencies)
            {
                var projectDependency = dependency.Library as ProjectDescription;

                if (projectDependency != null)
                {
                    if (projectDependency.Project.Files.SourceFiles.Any())
                    {
                        var projectOutputPath = GetProjectOutput(projectDependency.Project, projectDependency.Framework, configuration, outputPath);
                        compilerArgs.Add($"--reference:{projectOutputPath}");
                    }
                }
                else
                {
                    compilerArgs.AddRange(dependency.CompilationAssemblies.Select(r => $"--reference:{r.ResolvedPath}"));
                }
                compilerArgs.AddRange(dependency.SourceReferences);
            }

            if (!AddResources(context.ProjectFile, compilerArgs, intermediateOutputPath))
            {
                return false;
            }

            // Add project source files
            var sourceFiles = context.ProjectFile.Files.SourceFiles;
            compilerArgs.AddRange(sourceFiles);

            var compilerName = context.ProjectFile.CompilerName;
            compilerName = compilerName ?? "csc";

            // Write RSP file
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile.{context.ProjectFile.Name}.rsp");
            File.WriteAllLines(rsp, compilerArgs);

            var result = Command.Create($"dotnet-compile-{compilerName}", $"@\"{rsp}\"")
                                 .OnErrorLine(line =>
                                 {
                                     var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);
                                     if (diagnostic != null)
                                     {
                                         diagnostics.Add(diagnostic);
                                     }
                                     else
                                     {
                                         Reporter.Error.WriteLine(line);
                                     }
                                 })
                                 .OnOutputLine(line =>
                                 {
                                     var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);

                                     if (diagnostic != null)
                                     {
                                         diagnostics.Add(diagnostic);
                                     }
                                     else
                                     {
                                         Reporter.Output.WriteLine(line);
                                     }
                                 })
                                 .Execute();

            var success = result.ExitCode == 0;

            if (success && compilationOptions.EmitEntryPoint.GetValueOrDefault())
            {
                var runtimeContext = ProjectContext.Create(context.ProjectDirectory, context.TargetFramework, new[] { RuntimeIdentifier.Current });
                MakeRunnable(runtimeContext,
                             outputPath,
                             runtimeContext.CreateExporter(configuration));
            }

            return PrintSummary(diagnostics, sw, success);
        }
Example #10
0
        private static int PublishHost(ProjectContext context, string outputPath)
        {
            if (context.TargetFramework.IsDesktop())
            {
                return 0;
            }

            var hostPath = Path.Combine(AppContext.BaseDirectory, Constants.HostExecutableName);
            if (!File.Exists(hostPath))
            {
                Reporter.Error.WriteLine($"Cannot find {Constants.HostExecutableName} in the dotnet directory.".Red());
                return 1;
            }

            var outputExe = Path.Combine(outputPath, context.ProjectFile.Name + Constants.ExeSuffix);

            // Copy the host
            File.Copy(hostPath, outputExe, overwrite: true);
            return 0;
        }
Example #11
0
        private static void TryAddOutputFile(PackageBuilder packageBuilder,
                                             ProjectContext context,
                                             string outputPath,
                                             string filePath)
        {
            var targetPath = Path.Combine("lib", context.TargetFramework.GetTwoDigitShortFolderName(), Path.GetFileName(filePath));
            var sourcePath = Path.Combine(outputPath, filePath);

            if (!File.Exists(sourcePath))
            {
                return;
            }

            packageBuilder.Files.Add(new PhysicalPackageFile
            {
                SourcePath = sourcePath,
                TargetPath = targetPath
            });
        }
Example #12
0
        private static bool Compile(ProjectContext context, string configuration, string outputOptionValue, string intermediateOutputValue, bool buildProjectReferences)
        {
            // Set up Output Paths
            string outputPath = GetOutputPath(context, configuration, outputOptionValue);
            string intermediateOutputPath = GetIntermediateOutputPath(context, configuration, intermediateOutputValue, outputOptionValue);

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

            // Create the library exporter
            var exporter = context.CreateExporter(configuration);

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

            if (buildProjectReferences)
            {
                var projects = new Dictionary<string, ProjectDescription>();

                // Build project references
                foreach (var dependency in dependencies)
                {
                    var projectDependency = dependency.Library as ProjectDescription;

                    if (projectDependency != null && projectDependency.Project.Files.SourceFiles.Any())
                    {
                        projects[projectDependency.Identity.Name] = projectDependency;
                    }
                }

                foreach (var projectDependency in Sort(projects))
                {
                    // Skip compiling project dependencies since we've already figured out the build order
                    var compileResult = Command.Create("dotnet-compile", $"--framework {projectDependency.Framework} --configuration {configuration} --output \"{outputPath}\" --temp-output \"{intermediateOutputPath}\" --no-project-dependencies \"{projectDependency.Project.ProjectDirectory}\"")
                            .ForwardStdOut()
                            .ForwardStdErr()
                            .Execute();

                    if (compileResult.ExitCode != 0)
                    {
                        return false;
                    }
                }

                projects.Clear();
            }

            return CompileProject(context, configuration, outputPath, intermediateOutputPath, dependencies);
        }
Example #13
0
        private static bool CompileNative(ProjectContext context, string configuration, string outputOptionValue, bool buildProjectReferences)
        {
            string managedOutputPath = GetOutputPath(context, configuration, outputOptionValue);
            string outputPath = Path.Combine(GetOutputPath(context, configuration, outputOptionValue), "native");

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

             var outputExtension = ".dll";
            if (context.TargetFramework.IsDesktop() && compilationOptions.EmitEntryPoint.GetValueOrDefault())
            {
                outputExtension = ".exe";
            }

            var managedBinaryPath = Path.Combine(managedOutputPath, context.ProjectFile.Name + outputExtension);
            CleanOrCreateDirectory(outputPath);

            // Do Native Compilation
            var result = Command.Create($"dotnet-compile-native", $"\"{managedBinaryPath}\" \"{outputPath}\"")
                                .ForwardStdErr()
                                .ForwardStdOut()
                                .Execute();

            return result.ExitCode == 0;
        }
Example #14
0
        private static bool Compile(ProjectContext context, string configuration, string outputOptionValue, string intermediateOutputValue, bool buildProjectReferences)
        {
            // Set up Output Paths
            string outputPath = GetOutputPath(context, configuration, outputOptionValue);
            string intermediateOutputPath = GetIntermediateOutputPath(context, configuration, intermediateOutputValue, outputOptionValue);

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

            // Create the library exporter
            var exporter = context.CreateExporter(configuration);

            var diagnostics = new List<DiagnosticMessage>();

            // Collect dependency diagnostics
            diagnostics.AddRange(context.LibraryManager.GetAllDiagnostics());

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

            if (buildProjectReferences)
            {
                var projects = new Dictionary<string, ProjectDescription>();

                // Build project references
                foreach (var dependency in dependencies)
                {
                    var projectDependency = dependency.Library as ProjectDescription;

                    if (projectDependency != null && projectDependency.Project.Files.SourceFiles.Any())
                    {
                        projects[projectDependency.Identity.Name] = projectDependency;
                    }
                }

                foreach (var projectDependency in Sort(projects))
                {
                    // Skip compiling project dependencies since we've already figured out the build order
                    var compileResult = Command.Create("dotnet-compile", $"--framework {projectDependency.Framework} --configuration {configuration} --output \"{outputPath}\" --temp-output \"{intermediateOutputPath}\" --no-project-dependencies \"{projectDependency.Project.ProjectDirectory}\"")
                            .ForwardStdOut()
                            .ForwardStdErr()
                            .Execute();

                    if (compileResult.ExitCode != 0)
                    {
                        return false;
                    }
                }

                projects.Clear();
            }

            Reporter.Output.WriteLine($"Compiling {context.RootProject.Identity.Name.Yellow()} for {context.TargetFramework.DotNetFrameworkName.Yellow()}");

            // Dump dependency data
            // TODO: Turn on only if verbose, we can look at the response
            // file anyways
            // ShowDependencyInfo(dependencies);

            // Get compilation options
            var outputName = GetProjectOutput(context.ProjectFile, context.TargetFramework, configuration, outputPath);

            // Assemble args
            var compilerArgs = new List<string>()
            {
                "-nostdlib",
                "-nologo",
                $"-out:\"{outputName}\""
            };

            // Default suppressions, some versions of mono don't support these
            compilerArgs.Add("-nowarn:CS1701");
            compilerArgs.Add("-nowarn:CS1702");
            compilerArgs.Add("-nowarn:CS1705");

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            // Add compilation options to the args
            ApplyCompilationOptions(compilationOptions, compilerArgs);

            foreach (var dependency in dependencies)
            {
                var projectDependency = dependency.Library as ProjectDescription;

                if (projectDependency != null)
                {
                    if (projectDependency.Project.Files.SourceFiles.Any())
                    {
                        var projectOutputPath = GetProjectOutput(projectDependency.Project, projectDependency.Framework, configuration, outputPath);
                        compilerArgs.Add($"-r:\"{projectOutputPath}\"");
                    }
                }
                else
                {
                    compilerArgs.AddRange(dependency.CompilationAssemblies.Select(r => $"-r:\"{r.ResolvedPath}\""));
                }
                compilerArgs.AddRange(dependency.SourceReferences.Select(s => $"\"{s}\""));
            }

            // Add project source files
            var sourceFiles = context.ProjectFile.Files.SourceFiles;
            compilerArgs.AddRange(sourceFiles.Select(s => $"\"{s}\""));

            if (!AddResources(context.ProjectFile, compilerArgs, intermediateOutputPath))
            {
                return false;
            }

            var compilerName = context.ProjectFile.CompilerName;
            compilerName = compilerName ?? "csc";

            // Write RSP file
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile.{compilerName}.{context.ProjectFile.Name}.rsp");
            File.WriteAllLines(rsp, compilerArgs);

            var result = Command.Create($"dotnet-compile-{compilerName}", $"\"{rsp}\"")
                                 .OnErrorLine(line =>
                                 {
                                     var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);
                                     if (diagnostic != null)
                                     {
                                         diagnostics.Add(diagnostic);
                                     }
                                     else
                                     {
                                         Reporter.Error.WriteLine(line);
                                     }
                                 })
                                 .OnOutputLine(line =>
                                 {
                                     var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);

                                     if (diagnostic != null)
                                     {
                                         diagnostics.Add(diagnostic);
                                     }
                                     else
                                     {
                                         Reporter.Output.WriteLine(line);
                                     }
                                 })
                                 .Execute();

            foreach (var diag in diagnostics)
            {
                PrintDiagnostic(diag);
            }

            var success = result.ExitCode == 0;

            if (success && compilationOptions.EmitEntryPoint.GetValueOrDefault())
            {
                var runtimeContext = ProjectContext.Create(context.ProjectDirectory, context.TargetFramework, new[] { RuntimeIdentifier.Current });
                MakeRunnable(runtimeContext,
                             outputPath,
                             runtimeContext.CreateExporter(configuration));
            }

            PrintSummary(success, diagnostics);

            return success;
        }
Example #15
0
 private static void RunScripts(ProjectContext context, string name, Dictionary<string, string> contextVariables)
 {
     foreach (var script in context.ProjectFile.Scripts.GetOrEmpty(name))
     {
         ScriptExecutor.CreateCommandForScript(context.ProjectFile, script, contextVariables)
             .ForwardStdErr()
             .ForwardStdOut()
             .Execute();
     }
 }
Example #16
0
        private static string GetOutputPath(ProjectContext context, string configuration, string outputOptionValue)
        {
            var outputPath = string.Empty;

            if (string.IsNullOrEmpty(outputOptionValue))
            {
                outputPath = Path.Combine(
                    GetDefaultRootOutputPath(context.ProjectFile, outputOptionValue),
                    Cli.Utils.Constants.BinDirectoryName,
                    configuration,
                    context.TargetFramework.GetTwoDigitShortFolderName());
            }
            else
            {
                outputPath = outputOptionValue;
            }

            return outputPath;
        }
Example #17
0
        private static bool CompileNative(ProjectContext context, string configuration, string outputOptionValue, bool buildProjectReferences, string intermediateOutputValue, string archValue, string ilcArgsValue, bool isCppMode)
        {
            var outputPath = Path.Combine(GetOutputPath(context, configuration, outputOptionValue), "native");
            var intermediateOutputPath = GetIntermediateOutputPath(context, configuration, intermediateOutputValue, outputOptionValue);

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

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            var managedOutput = GetProjectOutput(context.ProjectFile, context.TargetFramework, configuration, outputPath);

            var nativeArgs = new List<string>();

            // Input Assembly
            nativeArgs.Add($"\"{managedOutput}\"");

            // ILC Args
            nativeArgs.Add("--ilcargs");
            nativeArgs.Add($"\"{ilcArgsValue}\"");

            // CodeGen Mode
            if(isCppMode)
            {
                nativeArgs.Add("--mode");
                nativeArgs.Add("cpp");
            }

            // Configuration
            if (configuration != null)
            {
                nativeArgs.Add("--configuration");
                nativeArgs.Add(configuration);
            }

            // Architecture
            if (archValue != null)
            {
                nativeArgs.Add("--arch");
                nativeArgs.Add(archValue);
            }

            // Intermediate Path
            nativeArgs.Add("--temp-output");
            nativeArgs.Add($"\"{intermediateOutputPath}\"");

            // Output Path
            nativeArgs.Add("--output");
            nativeArgs.Add($"\"{outputPath}\"");

            // Dependencies
            var exporter = context.CreateExporter(configuration);
            var dependencies = exporter.GetDependencies().ToList();
            foreach (var dependency in dependencies)
            {
                var projectDependency = dependency.Library as ProjectDescription;

                if (projectDependency != null)
                {
                    if (projectDependency.Project.Files.SourceFiles.Any())
                    {
                        var projectOutputPath = GetProjectOutput(projectDependency.Project, projectDependency.Framework, configuration, outputPath);
                        nativeArgs.Add("-r");
                        nativeArgs.Add($"\"{projectOutputPath}\"");
                    }
                }
                else
                {
                    foreach(var dep in dependency.RuntimeAssemblies)
                    {
                        nativeArgs.Add("-r");
                        nativeArgs.Add($"\"{dep.ResolvedPath}\"");
                    }
                }
            }

            // Write Response File
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile-native.{context.ProjectFile.Name}.rsp");
            File.WriteAllLines(rsp, nativeArgs);

            // TODO Add -r assembly.dll for all Nuget References
            //     Need CoreRT Framework published to nuget

            // Do Native Compilation
            var result = Command.Create($"dotnet-compile-native", $"--rsp \"{rsp}\"")
                                .ForwardStdErr()
                                .ForwardStdOut()
                                .Execute();

            return result.ExitCode == 0;
        }
Example #18
0
        private static bool CompileProject(ProjectContext context, string configuration, string outputPath, string intermediateOutputPath, List<LibraryExport> dependencies)
        {
            Reporter.Output.WriteLine($"Compiling {context.RootProject.Identity.Name.Yellow()} for {context.TargetFramework.DotNetFrameworkName.Yellow()}");
            var sw = Stopwatch.StartNew();

            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 (missingFrameworkDiagnostics.Count > 0)
            {
                // The framework isn't installed so we should short circuit the rest of the compilation
                // so we don't get flooded with errors
                PrintSummary(missingFrameworkDiagnostics, sw);
                return false;
            }

            // Dump dependency data
            ShowDependencyInfo(dependencies);

            // Get compilation options
            var outputName = GetProjectOutput(context.ProjectFile, context.TargetFramework, configuration, outputPath);

            // Assemble args
            var compilerArgs = new List<string>()
            {
                $"--temp-output:{intermediateOutputPath}",
                $"--out:{outputName}"
            };

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

            if (!string.IsNullOrEmpty(compilationOptions.KeyFile))
            {
                // Resolve full path to key file
                compilationOptions.KeyFile = Path.GetFullPath(Path.Combine(context.ProjectFile.ProjectDirectory, compilationOptions.KeyFile));
            }

            // Add compilation options to the args
            compilerArgs.AddRange(compilationOptions.SerializeToArgs());

            foreach (var dependency in dependencies)
            {
                var projectDependency = dependency.Library as ProjectDescription;

                if (projectDependency != null)
                {
                    if (projectDependency.Project.Files.SourceFiles.Any())
                    {
                        var projectOutputPath = GetProjectOutput(projectDependency.Project, projectDependency.Framework, configuration, outputPath);
                        compilerArgs.Add($"--reference:{projectOutputPath}");
                    }
                }
                else
                {
                    compilerArgs.AddRange(dependency.CompilationAssemblies.Select(r => $"--reference:{r.ResolvedPath}"));
                }
                compilerArgs.AddRange(dependency.SourceReferences);
            }

            if (!AddResources(context.ProjectFile, compilerArgs, intermediateOutputPath))
            {
                return false;
            }

            // Add project source files
            var sourceFiles = context.ProjectFile.Files.SourceFiles;
            compilerArgs.AddRange(sourceFiles);

            var compilerName = context.ProjectFile.CompilerName;
            compilerName = compilerName ?? "csc";

            // Write RSP file
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile.{context.ProjectFile.Name}.rsp");
            File.WriteAllLines(rsp, compilerArgs);

            // Run pre-compile event
            var contextVariables = new Dictionary<string, string>()
            {
                { "compile:TargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "compile:Configuration", configuration },
                { "compile:OutputFile", outputName },
                { "compile:OutputDir", outputPath },
                { "compile:ResponseFile", rsp }
            };
            RunScripts(context, ScriptNames.PreCompile, contextVariables);

            var result = Command.Create($"dotnet-compile-{compilerName}", $"@\"{rsp}\"")
                .OnErrorLine(line =>
                {
                    var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);
                    if (diagnostic != null)
                    {
                        diagnostics.Add(diagnostic);
                    }
                    else
                    {
                        Reporter.Error.WriteLine(line);
                    }
                })
                .OnOutputLine(line =>
                {
                    var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);
                    if (diagnostic != null)
                    {
                        diagnostics.Add(diagnostic);
                    }
                    else
                    {
                        Reporter.Output.WriteLine(line);
                    }
                }).Execute();

            // Run post-compile event
            contextVariables["compile:CompilerExitCode"] = result.ExitCode.ToString();
            RunScripts(context, ScriptNames.PostCompile, contextVariables);

            var success = result.ExitCode == 0;

            if (success && compilationOptions.EmitEntryPoint.GetValueOrDefault())
            {
                var runtimeContext = ProjectContext.Create(context.ProjectDirectory, context.TargetFramework, new[] { RuntimeIdentifier.Current });
                MakeRunnable(runtimeContext,
                             outputPath,
                             runtimeContext.CreateExporter(configuration));
            }

            return PrintSummary(diagnostics, sw, success);
        }
Example #19
0
 private static void CopyContents(ProjectContext context, string outputPath)
 {
     var sourceFiles = context.ProjectFile.Files.GetCopyToOutputFiles();
     Copy(sourceFiles, context.ProjectDirectory, outputPath);
 }
Example #20
0
        private static int Publish(ProjectContext context, string outputPath, string configuration)
        {
            Reporter.Output.WriteLine($"Publishing {context.RootProject.Identity.Name.Yellow()} for {context.TargetFramework.DotNetFrameworkName.Yellow()}/{context.RuntimeIdentifier.Yellow()}");

            var options = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

            if (!options.EmitEntryPoint.GetValueOrDefault())
            {
                Reporter.Output.WriteLine($"{context.RootProject.Identity} does not have an entry point defined.".Red());
                return 1;
            }

            // Generate the output path
            if (string.IsNullOrEmpty(outputPath))
            {
                outputPath = Path.Combine(
                    context.ProjectFile.ProjectDirectory,
                    Constants.BinDirectoryName,
                    configuration,
                    context.TargetFramework.GetTwoDigitShortFolderName(),
                    context.RuntimeIdentifier);
            }

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

            // Compile the project (and transitively, all it's dependencies)
            var result = Command.Create("dotnet-compile", $"--framework \"{context.TargetFramework.DotNetFrameworkName}\" --output \"{outputPath}\" --configuration \"{configuration}\" \"{context.ProjectFile.ProjectDirectory}\"")
                .ForwardStdErr()
                .ForwardStdOut()
                .Execute();

            if (result.ExitCode != 0)
            {
                return result.ExitCode;
            }

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

            foreach (var export in exporter.GetAllExports())
            {
                // Skip copying project references
                if (export.Library is ProjectDescription)
                {
                    continue;
                }

                Reporter.Verbose.WriteLine($"Publishing {export.Library.Identity.ToString().Green().Bold()} ...");

                PublishFiles(export.RuntimeAssemblies, outputPath);
                PublishFiles(export.NativeLibraries, outputPath);
            }

            // Publish the application itself
            PublishHost(context, outputPath);

            Reporter.Output.WriteLine($"Published to {outputPath}".Green().Bold());
            return 0;
        }
Example #21
0
        private static bool CompileNative(
            ProjectContext context, 
            string configuration, 
            string outputOptionValue, 
            bool buildProjectReferences, 
            string intermediateOutputValue, 
            string archValue, 
            string ilcArgsValue, 
            string ilcPathValue,
            bool isCppMode)
        {
            var outputPath = GetOutputPath(context, configuration, outputOptionValue);
            var nativeOutputPath = Path.Combine(GetOutputPath(context, configuration, outputOptionValue), "native");
            var intermediateOutputPath =
                GetIntermediateOutputPath(context, configuration, intermediateOutputValue, outputOptionValue);

            Directory.CreateDirectory(nativeOutputPath);
            Directory.CreateDirectory(intermediateOutputPath);

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            var managedOutput =
                GetProjectOutput(context.ProjectFile, context.TargetFramework, configuration, outputPath);

            var nativeArgs = new List<string>();

            // Input Assembly
            nativeArgs.Add($"{managedOutput}");

            // ILC Args
            if (!string.IsNullOrWhiteSpace(ilcArgsValue))
            {
                nativeArgs.Add("--ilcargs");
                nativeArgs.Add($"{ilcArgsValue}");
            }

            // ILC Path
            if (!string.IsNullOrWhiteSpace(ilcPathValue))
            {
                nativeArgs.Add("--ilcpath");
                nativeArgs.Add(ilcPathValue);
            }

            // CodeGen Mode
            if(isCppMode)
            {
                nativeArgs.Add("--mode");
                nativeArgs.Add("cpp");
            }

            // Configuration
            if (configuration != null)
            {
                nativeArgs.Add("--configuration");
                nativeArgs.Add(configuration);
            }

            // Architecture
            if (archValue != null)
            {
                nativeArgs.Add("--arch");
                nativeArgs.Add(archValue);
            }

            // Intermediate Path
            nativeArgs.Add("--temp-output");
            nativeArgs.Add($"{intermediateOutputPath}");

            // Output Path
            nativeArgs.Add("--output");
            nativeArgs.Add($"{nativeOutputPath}");

            // Write Response File
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile-native.{context.ProjectFile.Name}.rsp");
            File.WriteAllLines(rsp, nativeArgs);

            // TODO Add -r assembly.dll for all Nuget References
            //     Need CoreRT Framework published to nuget

            // Do Native Compilation
            var result = Command.Create("dotnet-compile-native", $"--rsp \"{rsp}\"")
                                .ForwardStdErr()
                                .ForwardStdOut()
                                .Execute();

            return result.ExitCode == 0;
        }