private List <FileSystemPath> ExtractReferenceLocations([NotNull] IT4File file) { file.AssertContainsNoIncludeContext(); var directives = file.GetThisAndIncludedFilesRecursive() .SelectMany(it => it.Blocks) .OfType <IT4AssemblyDirective>(); var errors = new FrugalLocalList <T4FailureRawData>(); var directDependencies = directives.SelectNotNull( directive => { var resolved = AssemblyReferenceResolver.Resolve(directive); if (resolved == null) { errors.Add(CreateError(directive)); } return(resolved); } ).AsList(); if (!errors.IsEmpty) { throw new T4OutputGenerationException(errors); } AddBaseReferences(directDependencies, file); return(directDependencies); }
public void AssemblyReferenceResolver_BuildTaskNotSetShouldThrowException() { var processExecutorMock = new Mock <IProcessExecutor>(MockBehavior.Strict); var metadataReferenceProviderMock = new Mock <IMetadataReferenceProvider>(MockBehavior.Strict); processExecutorMock.Setup(x => x.Start( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >())) .Returns(new ProcessResult() { ExitCode = 1, Output = @"C:\ProjectFolder\ExampleProject\ExampleProject.Test.csproj : error MSB4057: The target ""PrintReferences"" does not exist in the project." }); string project = @"C:\ProjectFolder\ExampleProject\ExampleProject.Test.csproj"; var target = new AssemblyReferenceResolver(processExecutorMock.Object, metadataReferenceProviderMock.Object); // The resolver should throw an exception when the target task was not found var exception = Assert.Throws <ApplicationException>(() => target.ResolveReferences( Path.GetDirectoryName(project), Path.GetFileName(project), "" ).ToList()); exception.Message.ShouldContain("PrintReferences"); }
public void InitialBuildProcess_FoundPathsShouldBeReturnedAsPortableExecutionReferences() { var processExecutorMock = new Mock <IProcessExecutor>(MockBehavior.Strict); var metadataReferenceProviderMock = new Mock <IMetadataReferenceProvider>(MockBehavior.Strict); processExecutorMock.Setup(x => x.Start( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >())) .Returns(new ProcessResult() { ExitCode = 0, Output = @" AnotherExampleProject -> C/Repos/ExampleTestProject/ExampleTestProject/Bin/Debug/netcoreapp2.0/AnotherExampleProject.dll ExampleProject -> C/Repos/ExampleProject/ExampleProject/Bin/Debug/netcoreapp2.0/ExampleProject.dll C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\Microsoft.CSharp.dll;C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.formatters.json\2.0.2\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Formatters.Json.dll" }); metadataReferenceProviderMock.Setup(x => x.CreateFromFile(It.IsAny <string>())).Returns(() => null); string project = @"C:\ProjectFolder\ExampleProject\ExampleProject.Test.csproj"; var target = new AssemblyReferenceResolver(processExecutorMock.Object, metadataReferenceProviderMock.Object); var result = target.ResolveReferences(Path.GetDirectoryName(project), Path.GetFileName(project), "ExampleProject"); // two references should be found in the above output result.Count().ShouldBe(3); metadataReferenceProviderMock.Verify(x => x.CreateFromFile(It.IsAny <string>()), Times.Exactly(3)); }
public MetadataSystem(MetadataReader reader) { _reader = reader; _entryPoint = new Lazy <MethodDefinition>(() => GetMethodDefinition(_reader.EntryPoint.RID)); _assembly = new Lazy <AssemblyDefinition>(() => AssemblyDefinitionResolver.Resolve(_reader.AssemblyTable.Row, this)); _module = new Lazy <ModuleDefinition>(() => ModuleDefinitionResolver.Resolve(_reader.ModuleTable.Row, this)); _assemblyRefs = new Lazy <AssemblyReference[]>(() => _reader.AssemblyRefTable .Select((row, id) => AssemblyReferenceResolver.Resolve((uint)(id + 1), row, this)) .ToArray(_reader.AssemblyRefTable.Length)); _types = new Lazy <TypeDefinition[]>(() => _reader.TypeDefTable .Select((row, id) => TypeDefinitionResolver.Resolve((uint)(id + 1), row, this)) .ToArray(_reader.TypeDefTable.Length)); _methods = new Lazy <MethodDefinition[]>(() => _types.Value.SelectMany(type => type.Methods) .ToArray(_reader.MethodTable.Length)); _fields = new Lazy <FieldDefinition[]>(() => _types.Value.SelectMany(type => type.Fields) .ToArray(_reader.FieldTable.Length)); _typeRefLookup = new Lazy <ILookup <MetadataToken, TypeReference> >(() => _reader.TypeRefTable.ToLookup(row => row.ResolutionScope, row => TypeReferenceResolver.Resolve(row, this))); _memberRefLookup = new Lazy <ILookup <MetadataToken, IMemberReference> >(() => _reader.MemberRefTable.ToLookup(row => row.Class, row => MemberReferenceResolver.Resolve(row, this))); _attributeLookup = new Lazy <ILookup <MetadataToken, CustomAttribute> >(() => _reader.CustomAttributeTable.ToLookup(row => row.Parent, row => CustomAttributeResolver.Resolve(row, this))); _typeRefs = new Lazy <TypeReference[]>(() => _typeRefLookup.Value.SelectMany(items => items) .ToArray(_reader.TypeRefTable.Length)); _memberRefs = new Lazy <IMemberReference[]>(() => _memberRefLookup.Value.SelectMany(items => items) .ToArray(_reader.MemberRefTable.Length)); _attributes = new Lazy <CustomAttribute[]>(() => _attributeLookup.Value.SelectMany(items => items) .ToArray(_reader.CustomAttributeTable.Length)); _enclosingTypeMapping = new Lazy <Dictionary <MetadataToken, ITypeInfo> >(() => _reader.NestedClassTable.ToDictionary( row => row.NestedClass, row => GetTypeInfo(row.EnclosingClass))); }
public void CompileTempPE(string pszOutputFileName, int sourceCount, string[] fileNames, string[] fileContents, int optionCount, string[] optionNames, object[] optionValues) { var baseDirectory = Path.GetDirectoryName(pszOutputFileName); var parsedArguments = ParseCommandLineArguments(baseDirectory, optionNames, optionValues); Contract.ThrowIfFalse(fileNames.Length == fileContents.Length); var trees = new List <SyntaxTree>(capacity: sourceCount); for (int i = 0; i < fileNames.Length; i++) { // create a parse tree w/o encoding - the tree won't be used to emit PDBs trees.Add(SyntaxFactory.ParseSyntaxTree(fileContents[i], parsedArguments.ParseOptions, fileNames[i])); } // TODO (tomat): Revisit compilation options: App.config, strong name, search paths, etc? (bug #869604) // TODO (tomat): move resolver initialization (With* methods below) to CommandLineParser.Parse var metadataProvider = _workspace.Services.GetService <IMetadataService>().GetProvider(); var metadataResolver = new AssemblyReferenceResolver(MetadataFileReferenceResolver.Default, metadataProvider); var compilation = CSharpCompilation.Create( Path.GetFileName(pszOutputFileName), trees, parsedArguments.ResolveMetadataReferences(metadataResolver), parsedArguments.CompilationOptions .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) .WithMetadataReferenceResolver(metadataResolver)); var result = compilation.Emit(pszOutputFileName); Contract.ThrowIfFalse(result.Success); }
public void AssemblyReferenceResolver_ShouldSkipProjectUnderTest() { var foundReferences = new List <string>(); var processExecutorMock = new Mock <IProcessExecutor>(MockBehavior.Strict); var metadataReferenceProviderMock = new Mock <IMetadataReferenceProvider>(MockBehavior.Strict); processExecutorMock.SetupProcessMockToReturn(@" MGA.Contracts -> C:\Mrak\IS-MarkW\Product\MGA.Contracts\MGA.Contracts\bin\Debug\netcoreapp2.0\MGA.Contracts.dll MGA.MaandstaatKeuringsFrontend.Domain -> C:\Mrak\IS-MarkW\Product\MGA.MaandstaatKeuringsFrontend\MGA.MaandstaatKeuringsFrontend.Domain\bin\Debug\netcoreapp2.0\MGA.MaandstaatKeuringsFrontend.Domain.dll MGA.MaandstaatKeuringsFrontend.DomainServices -> C:\Mrak\IS-MarkW\Product\MGA.MaandstaatKeuringsFrontend\MGA.MaandstaatKeuringsFrontend.DomainServices\bin\Debug\netcoreapp2.0\MGA.MaandstaatKeuringsFrontend.DomainServices.dll MGA.MaandstaatKeuringsFrontend.DAL -> C:\Mrak\IS-MarkW\Product\MGA.MaandstaatKeuringsFrontend\MGA.MaandstaatKeuringsFrontend.DAL\bin\Debug\netcoreapp2.0\MGA.MaandstaatKeuringsFrontend.DAL.dll MGA.MaandstaatKeuringsFrontend.Infrastructure -> C:\Mrak\IS-MarkW\Product\MGA.MaandstaatKeuringsFrontend\MGA.MaandstaatKeuringsFrontend.Infrastructure\bin\Debug\netcoreapp2.0\MGA.MaandstaatKeuringsFrontend.Infrastructure.dll MGA.MaandstaatKeuringsFrontend.Facade -> C:\Mrak\IS-MarkW\Product\MGA.MaandstaatKeuringsFrontend\MGA.MaandstaatKeuringsFrontend.Facade\bin\Debug\netcoreapp2.0\MGA.MaandstaatKeuringsFrontend.Facade.dll C:\Mrak\IS-MarkW\Product\MGA.Contracts\MGA.Contracts\bin\Debug\netcoreapp2.0\MGA.Contracts.dll;C:\Mrak\IS-MarkW\Product\MGA.MaandstaatKeuringsFrontend\MGA.MaandstaatKeuringsFrontend.Facade\bin\Debug\netcoreapp2.0\MGA.MaandstaatKeuringsFrontend.Facade.dll;"); metadataReferenceProviderMock.Setup(x => x.CreateFromFile(It.IsAny <string>())) .Returns(() => null) .Callback((string reference) => foundReferences.Add(reference)); string project = Path.Combine("C:", "ProjectFolder", "ExampleProject", "ExampleProject.Test.csproj"); var target = new AssemblyReferenceResolver(processExecutorMock.Object, metadataReferenceProviderMock.Object); var result = target.ResolveReferences(Path.GetDirectoryName(project), Path.GetFileName(project), "MGA.MaandstaatKeuringsFrontend.Facade").ToList(); // the project under test should be skipped, even when it is in the nuget packages list foundReferences.ShouldNotContain( Path.Combine("C:", "Mrak", "IS-MarkW", "Product", "MGA.MaandstaatKeuringsFrontend", "MGA.MaandstaatKeuringsFrontend.Facade", "bin", "Debug", "netcoreapp2.0", "MGA.MaandstaatKeuringsFrontend.Facade.dll")); }
protected override void DoRun(IT4AttributeValue element, IHighlightingConsumer consumer) { var attribute = DirectiveAttributeNavigator.GetByValue(element); if (!(DirectiveNavigator.GetByAttribute(attribute) is IT4AssemblyDirective assemblyDirective)) { return; } var path = AssemblyReferenceResolver.Resolve(assemblyDirective); if (path != null) { if (ProjectReferenceResolver.TryResolveProject(path) != null) { return; } if (path.ExistsFile) { return; } } var pathNode = assemblyDirective.GetAttributeValueToken(T4DirectiveInfoManager.Assembly.NameAttribute.Name); if (pathNode == null) { return; } consumer.AddHighlighting(new UnresolvedAssemblyError(pathNode)); }
public void ShouldAnalyzeProjectDependencies() { var foundReferences = new List <string>(); var processExecutorMock = new Mock <IProcessExecutor>(MockBehavior.Strict); var metadataReferenceProviderMock = new Mock <IMetadataReferenceProvider>(MockBehavior.Strict); processExecutorMock.SetupProcessMockToReturn(@" ExampleProject.Contracts -> C:\Repos\ExampleProject\ExampleProject\bin\Debug\netcoreapp2.0\ExampleProject.Contracts.dll ExampleProject -> C:\Repos\ExampleProject\ExampleProject\bin\Debug\netcoreapp2.0\ExampleProject.dll C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\Microsoft.CSharp.dll;C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.formatters.json\2.0.2\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Formatters.Json.dll"); metadataReferenceProviderMock.Setup(x => x.CreateFromFile(It.IsAny <string>())) .Returns(() => null) .Callback((string reference) => foundReferences.Add(reference)); string project = Path.Combine("C:", "ProjectFolder", "ExampleProject", "ExampleProject.Test.csproj"); var target = new AssemblyReferenceResolver(processExecutorMock.Object, metadataReferenceProviderMock.Object); var result = target.ResolveReferences(Path.GetDirectoryName(project), Path.GetFileName(project), "ExampleProject").ToList(); processExecutorMock.Verify(x => x.Start( Path.GetDirectoryName(project), "dotnet", "msbuild ExampleProject.Test.csproj /nologo /t:PrintReferences", null, It.IsAny <int>()), Times.Once); foundReferences.ShouldBeSubsetOf(new List <string>() { Path.Combine($@"C:{Path.DirectorySeparatorChar}Repos", "ExampleProject", "ExampleProject", "bin", "Debug", "netcoreapp2.0", "ExampleProject.Contracts.dll"), Path.Combine($@"C:{Path.DirectorySeparatorChar}Program Files", "dotnet", "sdk", "NuGetFallbackFolder", "microsoft.netcore.app", "2.0.0", "ref", "netcoreapp2.0", "Microsoft.CSharp.dll"), Path.Combine($@"C:{Path.DirectorySeparatorChar}Program Files", "dotnet", "sdk", "NuGetFallbackFolder", "microsoft.aspnetcore.mvc.formatters.json", "2.0.2", "lib", "netstandard2.0", "Microsoft.AspNetCore.Mvc.Formatters.Json.dll") }); }
public IEnumerable <T4AssemblyReferenceInfo> ExtractReferenceLocationsTransitive(IT4File file) { file.AssertContainsNoIncludeContext(); var sourceFile = file.PhysicalPsiSourceFile.NotNull(); var projectFile = sourceFile.ToProjectFile().NotNull(); var directives = file.GetThisAndIncludedFilesRecursive() .SelectMany(it => it.Blocks) .OfType <IT4AssemblyDirective>(); var errors = new FrugalLocalList <T4FailureRawData>(); var directDependencies = directives.SelectNotNull( directive => { var resolved = AssemblyReferenceResolver.Resolve(directive); if (resolved == null) { errors.Add(T4FailureRawData.FromElement(directive, "Unresolved assembly reference")); } return(resolved); } ).AsList(); if (!errors.IsEmpty) { throw new T4OutputGenerationException(errors); } AddBaseReferences(directDependencies, file); return(LowLevelReferenceExtractionManager.ResolveTransitiveDependencies( directDependencies, projectFile.SelectResolveContext() )); }
private static CSharpCompilationOptions CreateCSharpCompilationOptions() { string moduleName = null; string mainTypeName = null; string scriptClassName = null; IEnumerable <string> usings = null; OptimizationLevel optimizationLevel = OptimizationLevel.Debug; bool checkOverflow = false; bool allowUnsafe = false; string cryptoKeyContainer = null; string cryptoKeyFile = null; bool? delaySign = null; Platform platform = 0; ReportDiagnostic generalDiagnosticOption = 0; int warningLevel = 0; IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null; bool concurrentBuild = false; bool extendedCustomDebugInformation = true; XmlReferenceResolver xmlReferenceResolver = new XmlFileResolver(null); SourceReferenceResolver sourceReferenceResolver = new SourceFileResolver(ImmutableArray <string> .Empty, null); MetadataReferenceResolver metadataReferenceResolver = new AssemblyReferenceResolver(new MetadataFileReferenceResolver(ImmutableArray <string> .Empty, null), MetadataFileReferenceProvider.Default); AssemblyIdentityComparer assemblyIdentityComparer = AssemblyIdentityComparer.Default; // Currently uses reference equality StrongNameProvider strongNameProvider = new DesktopStrongNameProvider(); MetadataImportOptions metadataImportOptions = 0; ImmutableArray <string> features = ImmutableArray <string> .Empty; return(new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, extendedCustomDebugInformation, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features)); }
public void AssemblyReferenceResolver_PathShouldEndWithdllExtension() { var target = new AssemblyReferenceResolver(null, null); // The string should be split at " -> " and not at "-" var result = target.GetAssemblyPathsFromOutput(@"U:\source\IS-StefanK\InfoSupport.BestuurdersCoach\InfoSupport.BestuurdersCoach.MessageBus\bin\Debug\netstandard2.0\InfoSupport.BestuurdersCoach.MessageBus.exe"); result.ShouldBeEmpty(); }
private ScriptOptions( ImmutableArray <MetadataReference> references, ImmutableArray <string> namespaces, AssemblyReferenceResolver referenceResolver, bool isInteractive) { _references = references; _namespaces = namespaces; _referenceResolver = referenceResolver; _isInteractive = isInteractive; }
public void AssemblyReferenceResolver_PathWithDashShouldBeAllowed() { var target = new AssemblyReferenceResolver(null, null); // The string should be split at " -> " and not at "-" var result = target.GetReferencePathsFromOutput(new Collection <string>() { @"InfoSupport.BestuurdersCoach.MessageBus -> U:\source\IS-StefanK\InfoSupport.BestuurdersCoach\InfoSupport.BestuurdersCoach.MessageBus\bin\Debug\netstandard2.0\InfoSupport.BestuurdersCoach.MessageBus.dll" }); result.Single().ShouldBe(@"U:\source\IS-StefanK\InfoSupport.BestuurdersCoach\InfoSupport.BestuurdersCoach.MessageBus\bin\Debug\netstandard2.0\InfoSupport.BestuurdersCoach.MessageBus.dll"); }
public void AssemblyReferenceResolver_PathShouldEndWithdllExtension() { var target = new AssemblyReferenceResolver(null, null); // The path should not end with .exe var result = target.GetAssemblyPathsFromOutput( Path.Combine("U:", "source", "IS-StefanK", "InfoSupport.BestuurdersCoach", "InfoSupport.BestuurdersCoach.MessageBus", "bin", "Debug", "netstandard2.0", "InfoSupport.BestuurdersCoach.MessageBus.exe")); result.ShouldBeEmpty(); }
private async Task ReloadAsync() { Mouse.OverrideCursor = Cursors.Wait; { var resolver = new AssemblyReferenceResolver(); var references = await resolver.ResolveReferences(AssemblyPath); references = references.OrderBy(x => x.Location).ToArray(); Application.Current.Dispatcher.Invoke(() => ReferencedAssemblies = references); } Mouse.OverrideCursor = null; }
/// <summary> /// Creates a new <see cref="ScriptOptions"/> with the base directory changed. /// </summary> /// <remarks> /// If null is specified relative paths won't be resolved. /// </remarks> public ScriptOptions WithBaseDirectory(string baseDirectory) { if (BaseDirectory == baseDirectory) { return(this); } // TODO: var resolver = new AssemblyReferenceResolver( _referenceResolver.PathResolver.WithBaseDirectory(baseDirectory), _referenceResolver.Provider); return(With(resolver: resolver)); }
/// <summary> /// Creates a new <see cref="ScriptOptions"/> with the search paths changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="searchPaths"/> is null or contains a null reference.</exception> public ScriptOptions WithSearchPaths(IEnumerable <string> searchPaths) { if (searchPaths != null && SearchPaths.SequenceEqual(searchPaths)) { return(this); } // TODO: var resolver = new AssemblyReferenceResolver( _referenceResolver.PathResolver.WithSearchPaths(ToImmutableArrayChecked(searchPaths, nameof(searchPaths))), _referenceResolver.Provider); return(With(resolver: resolver)); }
public void AssemblyReferenceResolver_PathWithDashShouldBeAllowed() { var target = new AssemblyReferenceResolver(null, null); var path = Path.Combine("U:", "source", "IS-StefanK", "InfoSupport.BestuurdersCoach", "InfoSupport.BestuurdersCoach.MessageBus", "bin", "Debug", "netstandard2.0", "InfoSupport.BestuurdersCoach.MessageBus.dll"); // The string should be split at " -> " and not at "-" var result = target.GetReferencePathsFromOutput(new Collection <string>() { $@"InfoSupport.BestuurdersCoach.MessageBus -> {path}" }); result.Single().ShouldBe(path); }
/// <summary> /// Creates a new <see cref="ScriptOptions"/> with the search paths changed. /// </summary> public ScriptOptions WithSearchPaths(IEnumerable <string> searchPaths) { if (this.SearchPaths.SequenceEqual(searchPaths)) { return(this); } else { // TODO: var resolver = new AssemblyReferenceResolver( _referenceResolver.PathResolver.WithSearchPaths(searchPaths.AsImmutableOrEmpty()), _referenceResolver.Provider); return(With(resolver: resolver)); } }
public void AssemblyReferenceResolver_PathWithDashShouldBeAllowed() { var target = new AssemblyReferenceResolver(null, null); // The string should be split at " -> " and not at "-" var result = target.GetReferencePathsFromOutput(new Collection <string>() { @"InfoSupport.BestuurdersCoach.MessageBus -> U:\source\IS-StefanK\InfoSupport.BestuurdersCoach\InfoSupport.BestuurdersCoach.MessageBus\bin\Debug\netstandard2.0\InfoSupport.BestuurdersCoach.MessageBus.dll" .Replace('\\', Path.DirectorySeparatorChar) }); result.Single().ShouldBe( Path.Combine($@"U:{Path.DirectorySeparatorChar}source", "IS-StefanK", "InfoSupport.BestuurdersCoach", "InfoSupport.BestuurdersCoach.MessageBus", "bin", "Debug", "netstandard2.0", "InfoSupport.BestuurdersCoach.MessageBus.dll")); }
private FileSystemPath ResolveBaseReference( [NotNull] IT4File file, [NotNull] string assemblyName ) { var resolved = AssemblyReferenceResolver.Resolve(assemblyName, file.LogicalPsiSourceFile); if (resolved != null) { return(resolved); } var node = FindSuitableNodeForErrorReporting(file); string message = $"Could not find standard assembly: {assemblyName}"; throw new T4OutputGenerationException(T4FailureRawData.FromElement(node, message)); }
private bool TryAddReference(IT4PathWithMacros pathWithMacros) { var path = AssemblyReferenceResolver.Resolve(pathWithMacros); if (path == null) { return(false); } if (MyAssemblyReferences.ContainsKey(path)) { return(false); } if (MyProjectReferences.ContainsKey(path)) { return(false); } return(TryAddProjectReference(path) || TryAddAssemblyReference(path)); }
private bool TryAddReference([NotNull] T4ResolvedPath pathWithMacros) { var path = AssemblyReferenceResolver.ResolveWithoutCaching(pathWithMacros); if (path == null) { return(false); } if (MyAssemblyReferences.ContainsKey(path)) { return(false); } if (MyProjectReferences.ContainsKey(path)) { return(false); } return(TryAddProjectReference(path) || TryAddAssemblyReference(path)); }
public void AssemblyReferenceResolver_BuildTaskNotSetShouldThrowException() { var processExecutorMock = new Mock <IProcessExecutor>(MockBehavior.Strict); var metadataReferenceProviderMock = new Mock <IMetadataReferenceProvider>(MockBehavior.Strict); processExecutorMock.SetupProcessMockToReturn(@"C:\ProjectFolder\ExampleProject\ExampleProject.Test.csproj : error MSB4057: The target ""PrintReferences"" does not exist in the project.", 1); string project = Path.Combine("C:", "ProjectFolder", "ExampleProject", "ExampleProject.Test.csproj"); var target = new AssemblyReferenceResolver(processExecutorMock.Object, metadataReferenceProviderMock.Object); // The resolver should throw an exception when the target task was not found var exception = Assert.Throws <StrykerInputException>(() => target.ResolveReferences( Path.GetDirectoryName(project), Path.GetFileName(project), "" ).ToList()); exception.Message.ShouldContain("PrintReferences"); }
public void FoundPathsShouldBeReturnedAsPortableExecutionReferences() { var processExecutorMock = new Mock <IProcessExecutor>(MockBehavior.Strict); var metadataReferenceProviderMock = new Mock <IMetadataReferenceProvider>(MockBehavior.Strict); processExecutorMock.SetupProcessMockToReturn(@" AnotherExampleProject -> C:\Repos\ExampleTestProject\ExampleTestProject\Bin\Debug\netcoreapp2.0\AnotherExampleProject.dll ExampleProject -> C:\Repos\ExampleProject\ExampleProject\Bin\Debug\netcoreapp2.0\ExampleProject.dll C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\Microsoft.CSharp.dll;C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.formatters.json\2.0.2\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Formatters.Json.dll"); metadataReferenceProviderMock.Setup(x => x.CreateFromFile(It.IsAny <string>())).Returns(() => null); string project = Path.Combine("C:", "ProjectFolder", "ExampleProject", "ExampleProject.Test.csproj"); var target = new AssemblyReferenceResolver(processExecutorMock.Object, metadataReferenceProviderMock.Object); var result = target.ResolveReferences(Path.GetDirectoryName(project), Path.GetFileName(project), "ExampleProject"); // three references should be found in the above output result.Count().ShouldBe(3); metadataReferenceProviderMock.Verify(x => x.CreateFromFile(It.IsAny <string>()), Times.Exactly(3)); }
public void AssemblyReferenceResolver_ShouldAnalyzeProjectDependencies() { var foundReferences = new List <string>(); var processExecutorMock = new Mock <IProcessExecutor>(MockBehavior.Strict); var metadataReferenceProviderMock = new Mock <IMetadataReferenceProvider>(MockBehavior.Strict); processExecutorMock.Setup(x => x.Start( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), null)) .Returns(new ProcessResult() { ExitCode = 0, Output = @" ExampleProject.Contracts -> C:\Repos\ExampleProject\ExampleProject\bin\Debug\netcoreapp2.0\ExampleProject.Contracts.dll ExampleProject -> C:\Repos\ExampleProject\ExampleProject\bin\Debug\netcoreapp2.0\ExampleProject.dll C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\Microsoft.CSharp.dll;C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.formatters.json\2.0.2\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Formatters.Json.dll" }); metadataReferenceProviderMock.Setup(x => x.CreateFromFile(It.IsAny <string>())) .Returns(() => null) .Callback((string reference) => foundReferences.Add(reference)); string project = "C:/ProjectFolder/ExampleProject/ExampleProject.Test.csproj"; var target = new AssemblyReferenceResolver(processExecutorMock.Object, metadataReferenceProviderMock.Object); var result = target.ResolveReferences(Path.GetDirectoryName(project), Path.GetFileName(project), "ExampleProject").ToList(); processExecutorMock.Verify(x => x.Start( Path.GetDirectoryName(project), "dotnet", "msbuild ExampleProject.Test.csproj /nologo /t:PrintReferences", null), Times.Once); foundReferences.ShouldBeSubsetOf(new List <string>() { @"C:\Repos\ExampleProject\ExampleProject\bin\Debug\netcoreapp2.0\ExampleProject.Contracts.dll", @"C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\Microsoft.CSharp.dll", @"C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.formatters.json\2.0.2\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Formatters.Json.dll" }); }
protected override void DoRun(IT4AttributeValue element, IHighlightingConsumer consumer) { var attribute = DirectiveAttributeNavigator.GetByValue(element); if (!(DirectiveNavigator.GetByAttribute(attribute) is IT4AssemblyDirective assemblyDirective)) { return; } var project = ProjectReferenceResolver.TryResolveProject(assemblyDirective.Path.ResolvePath()); if (project != null) { return; } var path = AssemblyReferenceResolver.Resolve(assemblyDirective); if (path != null && path.ExistsFile) { return; } consumer.AddHighlighting(new UnresolvedAssemblyWarning(assemblyDirective.Name)); }
private bool TryRemoveReference([NotNull] T4ResolvedPath pathWithMacros) { var path = AssemblyReferenceResolver.ResolveWithoutCaching(pathWithMacros); if (path == null) { return(false); } if (MyAssemblyReferences.TryGetValue(path, out var cookie)) { MyAssemblyReferences.Remove(path); cookie.Dispose(); return(true); } if (MyProjectReferences.ContainsKey(path)) { MyProjectReferences.Remove(path); return(true); } return(false); }
private FileSystemPath AddReference( [NotNull] IT4File file, [NotNull] string assemblyName ) => AssemblyReferenceResolver.Resolve(assemblyName, file.LogicalPsiSourceFile);
protected override CSharpCompilationOptions CreateCompilationOptions() { IDictionary <string, ReportDiagnostic> warningOptions = null; // Get options from the ruleset file, if any, first. That way project-specific // options can override them. ReportDiagnostic?ruleSetGeneralDiagnosticOption = null; if (this.ruleSet != null) { ruleSetGeneralDiagnosticOption = this.ruleSet.GetGeneralDiagnosticOption(); warningOptions = new Dictionary <string, ReportDiagnostic>(this.ruleSet.GetSpecificDiagnosticOptions()); } else { warningOptions = new Dictionary <string, ReportDiagnostic>(); } UpdateRuleSetError(ruleSet); UpdateWarning(warningOptions, CompilerOptions.OPTID_WARNASERRORLIST, ReportDiagnostic.Error); UpdateWarning(warningOptions, CompilerOptions.OPTID_WARNNOTASERRORLIST, ReportDiagnostic.Warn); // Add the warning suppressions second, since the if a warning appears in both lists the // suppression takes priority UpdateWarning(warningOptions, CompilerOptions.OPTID_NOWARNLIST, ReportDiagnostic.Suppress); Platform platform; if (!Enum.TryParse(GetStringOption(CompilerOptions.OPTID_PLATFORM, ""), ignoreCase: true, result: out platform)) { platform = Platform.AnyCpu; } int warningLevel; if (!int.TryParse(GetStringOption(CompilerOptions.OPTID_WARNINGLEVEL, defaultValue: ""), out warningLevel)) { warningLevel = 4; } string projectDirectory = this.ContainingDirectoryPathOpt; // TODO: #r support, should it include bin path? var referenceSearchPaths = ImmutableArray <string> .Empty; // TODO: #load support var sourceSearchPaths = ImmutableArray <string> .Empty; ReportDiagnostic generalDiagnosticOption; var warningsAreErrors = GetNullableBooleanOption(CompilerOptions.OPTID_WARNINGSAREERRORS); if (warningsAreErrors.HasValue) { generalDiagnosticOption = warningsAreErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default; } else if (ruleSetGeneralDiagnosticOption.HasValue) { generalDiagnosticOption = ruleSetGeneralDiagnosticOption.Value; } else { generalDiagnosticOption = ReportDiagnostic.Default; } MetadataReferenceResolver referenceResolver; if (this.Workspace != null) { referenceResolver = new AssemblyReferenceResolver( new MetadataFileReferenceResolver(referenceSearchPaths, projectDirectory), this.Workspace.CurrentSolution.Services.MetadataService.GetProvider()); } else { // can only happen in tests referenceResolver = null; } // TODO: appConfigPath: GetFilePathOption(CompilerOptions.OPTID_FUSIONCONFIG), bug #869604 return(new CSharpCompilationOptions( allowUnsafe: GetBooleanOption(CompilerOptions.OPTID_UNSAFE), checkOverflow: GetBooleanOption(CompilerOptions.OPTID_CHECKED), concurrentBuild: false, cryptoKeyContainer: GetStringOption(CompilerOptions.OPTID_KEYNAME, defaultValue: null), cryptoKeyFile: GetFilePathRelativeOption(CompilerOptions.OPTID_KEYFILE), delaySign: GetNullableBooleanOption(CompilerOptions.OPTID_DELAYSIGN), generalDiagnosticOption: generalDiagnosticOption, mainTypeName: _mainTypeName, moduleName: GetStringOption(CompilerOptions.OPTID_MODULEASSEMBLY, defaultValue: null), optimizationLevel: GetBooleanOption(CompilerOptions.OPTID_OPTIMIZATIONS) ? OptimizationLevel.Release : OptimizationLevel.Debug, outputKind: _outputKind, platform: platform, specificDiagnosticOptions: warningOptions, warningLevel: warningLevel, xmlReferenceResolver: new XmlFileResolver(projectDirectory), sourceReferenceResolver: new SourceFileResolver(sourceSearchPaths, projectDirectory), metadataReferenceResolver: referenceResolver, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default, strongNameProvider: new DesktopStrongNameProvider(GetStrongNameKeyPaths()))); }