private void EnsureToolJsonDepsFileExists( LibraryRange toolLibrary, LockFile toolLockFile, string depsPath) { if (!File.Exists(depsPath)) { var projectContext = new ProjectContextBuilder() .WithLockFile(toolLockFile) .WithTargetFramework(s_toolPackageFramework.ToString()) .Build(); var exporter = projectContext.CreateExporter(Constants.DefaultConfiguration); var dependencyContext = new DependencyContextBuilder() .Build(null, null, exporter.GetAllExports(), true, s_toolPackageFramework, string.Empty); using (var fileStream = File.Create(depsPath)) { var dependencyContextWriter = new DependencyContextWriter(); dependencyContextWriter.Write(dependencyContext, fileStream); } } }
public void BuildAllTargetsProperlyDeduplicatesTargets() { // Load all project contexts for the test project var contexts = new ProjectContextBuilder() .WithProjectDirectory(Path.Combine(TestAssetsManager.AssetsRoot, "TestProjectContextBuildAllDedupe")) .BuildAllTargets() .ToList(); // This is a portable app, so even though RIDs are specified, BuildAllTargets should only produce one output. Assert.Equal(1, contexts.Count); }
public void NoDuplicatesWithProjectAndReferenceAssemblyWithSameName() { var instance = TestAssetsManager.CreateTestInstance("DuplicatedReferenceAssembly") .WithLockFiles(); var context = new ProjectContextBuilder().WithProjectDirectory(Path.Combine(instance.TestRoot, "TestApp")) .WithTargetFramework("net461") .Build(); // Will fail with dupes if any context.LibraryManager.GetLibraries().ToDictionary(l => l.Identity.Name, StringComparer.OrdinalIgnoreCase); }
public void SingleMicrosoftCSharpReference() { // https://github.com/dotnet/cli/issues/1602 var instance = TestAssetsManager.CreateTestInstance("TestMicrosoftCSharpReference") .WithLockFiles(); var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot) .WithTargetFramework("dnx451") .Build(); Assert.Equal(4, context.RootProject.Dependencies.Count()); }
public void NoDuplicateReferencesWhenFrameworkMissing() { var instance = TestAssetsManager.CreateTestInstance("TestMicrosoftCSharpReferenceMissingFramework") .WithLockFiles(); var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot) .WithTargetFramework("net99") .Build(); // Will fail with dupes if any context.LibraryManager.GetLibraries().ToDictionary(l => l.Identity.Name, StringComparer.OrdinalIgnoreCase); }
public void NetCore50ShouldNotResolveFrameworkAssemblies() { var instance = TestAssetsManager.CreateTestInstance("TestMicrosoftCSharpReferenceMissingFramework") .WithLockFiles(); var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot) .WithTargetFramework("netcore50") .Build(); var diagnostics = context.LibraryManager.GetAllDiagnostics(); Assert.False(diagnostics.Any(d => d.ErrorCode == ErrorCodes.DOTNET1011)); }
// Need to unit test this, so public public void GenerateDepsJsonFile( LockFile toolLockFile, string depsPath) { Reporter.Verbose.WriteLine($"Generating deps.json at: {depsPath}"); var projectContext = new ProjectContextBuilder() .WithLockFile(toolLockFile) .WithTargetFramework(s_toolPackageFramework.ToString()) .Build(); var exporter = projectContext.CreateExporter(Constants.DefaultConfiguration); var dependencyContext = new DependencyContextBuilder() .Build(null, null, exporter.GetAllExports(), true, s_toolPackageFramework, string.Empty); var tempDepsFile = Path.GetTempFileName(); using (var fileStream = File.Open(tempDepsFile, FileMode.Open, FileAccess.Write)) { var dependencyContextWriter = new DependencyContextWriter(); dependencyContextWriter.Write(dependencyContext, fileStream); } try { File.Copy(tempDepsFile, depsPath); } catch (Exception e) { Reporter.Verbose.WriteLine($"unable to generate deps.json, it may have been already generated: {e.Message}"); } finally { try { File.Delete(tempDepsFile); } catch (Exception e2) { Reporter.Verbose.WriteLine($"unable to delete temporary deps.json file: {e2.Message}"); } } }
public void TestDuplicateDefaultDesktopReferences(string sampleName, bool withLockFile) { var instance = TestAssetsManager.CreateTestInstance(sampleName); if (withLockFile) { instance = instance.WithLockFiles(); } var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot) .WithTargetFramework("net451") .Build(); Assert.Equal(4, context.RootProject.Dependencies.Count()); }
public void GetLibraryExportsWithoutLockFile() { var root = Temp.CreateDirectory().CopyDirectory(Path.Combine(_testProjectsRoot, "TestAppWithLibrary")); foreach (var lockfile in Directory.GetFiles(root.Path, "project.lock.json")) { File.Delete(lockfile); } var builder = new ProjectContextBuilder().WithProjectDirectory(Path.Combine(root.Path, "TestApp")); foreach (var context in builder.BuildAllTargets()) { var exporter = context.CreateExporter("Debug"); var exports = exporter.GetAllExports(); Assert.NotEmpty(exports); } }
public void GetLibraryExportsWithoutLockFile() { var testInstance = TestAssetsManager.CreateTestInstance("TestAppWithLibrary"); foreach (var lockfile in Directory.GetFiles(testInstance.Path, "project.lock.json")) { File.Delete(lockfile); } var builder = new ProjectContextBuilder().WithProjectDirectory(Path.Combine(testInstance.Path, "TestApp")); foreach (var context in builder.BuildAllTargets()) { var exporter = context.CreateExporter("Debug"); var exports = exporter.GetAllExports(); Assert.NotEmpty(exports); } }
public void CloneTest() { // Initialize a test instance that we're going to clone. Make sure all properties are initialized here. var initialBuilder = new ProjectContextBuilder() .WithProject(new Project()) .WithLockFile(new LockFile("abc")) .WithTargetFramework(FrameworkConstants.CommonFrameworks.NetStandard10) .WithRuntimeIdentifiers(new[] { "win7-x64", "osx.10.10-x64" }) .WithRootDirectory("C:\\The\\Root") .WithProjectDirectory("/where/the/project/at") .WithPackagesDirectory("D:\\My\\Awesome\\NuGet\\Packages") .WithReferenceAssembliesPath("/these/are/the/reference/assemblies") .WithProjectResolver(_ => new Project()) .WithLockFileResolver(_ => new LockFile("def")) .WithProjectReaderSettings(new ProjectReaderSettings()); // Clone the builder var clonedBuilder = initialBuilder.Clone(); // Compare all the properties. This is a shallow clone, so they should all be exactly ReferenceEqual foreach (var prop in typeof(ProjectContextBuilder).GetTypeInfo().DeclaredProperties) { KnownProperties.Remove(prop.Name).Should().BeTrue(because: $"{prop.Name} should be listed in the known properties to ensure it is properly tested."); if (prop.PropertyType.GetTypeInfo().IsValueType) { // Can't use reference equality on value types prop.GetValue(clonedBuilder).Should().Be(prop.GetValue(initialBuilder), because: $"clone should have duplicated the {prop.Name} property"); } else { prop.GetValue(clonedBuilder).Should().BeSameAs(prop.GetValue(initialBuilder), because: $"clone should have duplicated the {prop.Name} property"); } } KnownProperties.Should().BeEmpty(because: "all properties should have been checked by the CloneTest"); }
public void NoDuplicatesWithProjectAndReferenceAssemblyWithSameName() { var instance = TestAssetsManager.CreateTestInstance("DuplicatedReferenceAssembly") .WithLockFiles(); var context = new ProjectContextBuilder().WithProjectDirectory(Path.Combine(instance.TestRoot, "TestApp")) .WithTargetFramework("net461") .Build(); // Will fail with dupes if any context.LibraryManager.GetLibraries().ToDictionary(l => l.Identity.Name); }
/// <summary> /// Create Roslyn worksapces from a given project path /// </summary> public static IEnumerable <Microsoft.CodeAnalysis.Workspace> Create(string projectPath) { var builder = new ProjectContextBuilder().WithProjectDirectory(projectPath); return(builder.BuildAllTargets().Select(context => context.CreateRoslynWorkspace())); }
public static bool TryPackageOnlyTagHelperResolution( CommandArgument assemblyNamesArgument, CommandOption protocolOption, CommandOption buildBasePathOption, CommandOption configurationOption, Project project, NuGetFramework framework, out int exitCode) { exitCode = 0; if (framework.IsDesktop()) { return(false); } var runtimeIdentifiers = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers(); var projectContext = new ProjectContextBuilder() .WithProject(project) .WithTargetFramework(framework) .WithRuntimeIdentifiers(runtimeIdentifiers) .Build(); var configuration = configurationOption.Value() ?? Constants.DefaultConfiguration; var projectRuntimeOutputPath = projectContext.GetOutputPaths(configuration, buildBasePathOption.Value())?.RuntimeOutputPath; var projectAssemblyName = project.GetCompilerOptions(framework, configuration).OutputName; var projectOutputAssembly = Path.Combine(projectRuntimeOutputPath, projectAssemblyName + ".dll"); if (File.Exists(projectOutputAssembly)) { // There's already build output. Dispatch to build output; this ensures dependencies have been resolved. return(false); } var projectLibraries = projectContext.LibraryManager.GetLibraries(); var libraryLookup = projectLibraries.ToDictionary( library => library.Identity.Name, library => library, StringComparer.Ordinal); foreach (var assemblyName in assemblyNamesArgument.Values) { if (!IsPackageOnly(assemblyName, libraryLookup)) { return(false); } } var loadContext = projectContext.CreateLoadContext( projectContext.RuntimeIdentifier, configuration: "Debug", outputPath: null); var runner = new PackageOnlyResolveTagHelpersRunCommand(loadContext) { AssemblyNamesArgument = assemblyNamesArgument, ProtocolOption = protocolOption }; exitCode = runner.OnExecute(); return(true); }
public void NoDuplicateReferencesWhenFrameworkMissing() { var instance = TestAssetsManager.CreateTestInstance("TestMicrosoftCSharpReferenceMissingFramework") .WithLockFiles(); var context = new ProjectContextBuilder().WithProjectDirectory(instance.TestRoot) .WithTargetFramework("net99") .Build(); // Will fail with dupes if any context.LibraryManager.GetLibraries().ToDictionary(l => l.Identity.Name); }
/// <summary> /// The execution is done in 2 phases. /// Phase 1 :: /// 1. Determine if the tool is running as a project dependency or not. /// 2. Try getting the project context for the project (use netcoreapp1.0 as the tfm if not running as dependency command or else use the tfm passed in) /// 3. If not running as dependency command and project context cannot be built using netcoreapp1.0, invoke project dependency command with the first tfm found in the project.json /// /// Phase 2 :: /// 1. After successfully getting the Project context, invoke the CodeGenCommandExecutor. /// </summary> private static void Execute(string[] args) { var app = new CommandLineApplication(false) { Name = APPNAME, Description = APP_DESC }; // Define app Options; app.HelpOption("-h|--help"); var projectPath = app.Option("-p|--project", "Path to project.json", CommandOptionType.SingleValue); var packagesPath = app.Option("-n|--nuget-package-dir", "Path to check for Nuget packages", CommandOptionType.SingleValue); var appConfiguration = app.Option("-c|--configuration", "Configuration for the project (Possible values: Debug/ Release)", CommandOptionType.SingleValue); var framework = app.Option("-tfm|--target-framework", "Target Framework to use. (Short folder name of the tfm. eg. net451)", CommandOptionType.SingleValue); var buildBasePath = app.Option("-b|--build-base-path", "", CommandOptionType.SingleValue); var dependencyCommand = app.Option("--no-dispatch", "", CommandOptionType.NoValue); app.OnExecute(() => { string project = projectPath.Value(); if (string.IsNullOrEmpty(project)) { project = Directory.GetCurrentDirectory(); } var configuration = appConfiguration.Value() ?? Constants.DefaultConfiguration; var projectFile = ProjectReader.GetProject(project); var frameworksInProject = projectFile.GetTargetFrameworks().Select(f => f.FrameworkName); var nugetFramework = FrameworkConstants.CommonFrameworks.NetCoreApp10; if (_isDispatcher) { // Invoke the tool from the project's build directory. return(BuildAndDispatchDependencyCommand( args, frameworksInProject.FirstOrDefault(), project, buildBasePath.Value(), configuration)); } else { if (!TryGetNugetFramework(framework.Value(), out nugetFramework)) { throw new ArgumentException($"Could not understand the NuGetFramework information. Framework short folder name passed in was: {framework.Value()}"); } var nearestNugetFramework = NuGetFrameworkUtility.GetNearest( frameworksInProject, nugetFramework, f => new NuGetFramework(f)); if (nearestNugetFramework == null) { // This should never happen as long as we dispatch correctly. var msg = "Could not find a compatible framework to execute." + Environment.NewLine + $"Available frameworks in project:{string.Join($"{Environment.NewLine} -", frameworksInProject.Select(f => f.GetShortFolderName()))}"; throw new InvalidOperationException(msg); } ProjectContext context = new ProjectContextBuilder() .WithProject(projectFile) .WithTargetFramework(nearestNugetFramework) .Build(); Debug.Assert(context != null); var codeGenArgs = ToolCommandLineHelper.FilterExecutorArguments(args); CodeGenCommandExecutor executor = new CodeGenCommandExecutor( context, codeGenArgs, configuration, packagesPath.Value(), _logger); return(executor.Execute()); } }); app.Execute(args); }