Remove Microsoft.Extensions.ProjectModel

Resolves #182
This commit is contained in:
Nate McMaster 2016-10-18 09:45:09 -07:00 committed by GitHub
parent 70bafa9753
commit c7ff19c285
34 changed files with 0 additions and 2041 deletions

View File

@ -1,8 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="msbuild" value="https://dotnet.myget.org/F/msbuild/api/v3/index.json" />
<add key="nugetbuild" value="https://www.myget.org/F/nugetbuild/api/v3/index.json" />
<add key="AspNetCore" value="https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json" />
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
</packageSources>

View File

@ -30,14 +30,6 @@
}
}
},
"adx-nonshipping": {
"rules": [],
"packages": {
"Microsoft.Extensions.ProjectModel.Abstractions.Sources": {},
"Microsoft.Extensions.ProjectModel.DotNet.Sources": {},
"Microsoft.Extensions.ProjectModel.MsBuild.Sources": {}
}
},
"Default": {
"rules": [
"DefaultCompositeRule"

View File

@ -22,12 +22,6 @@ k-standard-goals
"-n src/Microsoft.Extensions.Caching.SqlConfig.Tools/Microsoft.Extensions.Caching.SqlConfig.Tools.nuspec " +
"-n src/Microsoft.DotNet.Watcher.Tools/Microsoft.DotNet.Watcher.Tools.nuspec ");
var projectModel = Files.Include("src/Microsoft.Extensions.ProjectModel.*/project.json");
foreach (var proj in projectModel)
{
DotnetPack(proj, BUILD_DIR_LOCAL, E("Configuration"), E("KOREBUILD_DOTNET_PACK_OPTIONS") + " --no-build");
}
foreach (var nupkg in Files.Include(Path.Combine(BUILD_DIR_LOCAL, "*/" + E("Configuration") + "/*.nupkg")))
{
File.Copy(nupkg, Path.Combine(BUILD_DIR_LOCAL, Path.GetFileName(nupkg)), true);

View File

@ -1,34 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.Extensions.ProjectModel.Resolution;
using NuGet.Frameworks;
namespace Microsoft.Extensions.ProjectModel
{
public interface IProjectContext
{
string ProjectName { get; }
string Configuration { get; }
string Platform { get; }
string ProjectFullPath { get; }
string RootNamespace { get; }
bool IsClassLibrary { get; }
NuGetFramework TargetFramework { get; }
string Config { get; }
string DepsJson { get; }
string RuntimeConfigJson { get; }
string PackageLockFile { get; }
string PackagesDirectory { get; }
string TargetDirectory { get; }
string AssemblyName { get; }
string AssemblyFullPath { get; }
IEnumerable<string> CompilationItems { get; }
IEnumerable<string> EmbededItems { get; }
string FindProperty(string propertyName);
IEnumerable<DependencyDescription> PackageDependencies { get;}
IEnumerable<ResolvedReference> CompilationAssemblies { get; }
IEnumerable<string> ProjectReferences { get; }
}
}

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0.25420" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0.25420</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>8a97d718-0681-43c5-a70b-535dbbdf4fa1</ProjectGuid>
<RootNamespace>Microsoft.Extensions.ProjectModel.Abstractions.Sources</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -1,26 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Extensions.ProjectModel.Resolution
{
public class Dependency
{
public Dependency(string name, string version)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
Name = name;
Version = version;
}
public string Name { get; }
public string Version { get; }
}
}

View File

@ -1,51 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Extensions.ProjectModel.Resolution
{
public class DependencyDescription
{
private readonly List<Dependency> _dependencies;
public DependencyDescription(string name, string version, string path, string framework, string type, bool isResolved)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
if (string.IsNullOrEmpty(framework))
{
throw new ArgumentNullException(nameof(framework));
}
Name = name;
Version = version;
TargetFramework = framework;
Resolved = isResolved;
Path = path;
DependencyType dt;
Type = Enum.TryParse(type, ignoreCase: true , result: out dt) ? dt : DependencyType.Unknown;
_dependencies = new List<Dependency>();
}
public string TargetFramework { get; }
public string Name { get; }
public string Path { get; }
public string Version { get; }
public DependencyType Type { get; }
public bool Resolved { get; }
public IEnumerable<Dependency> Dependencies => _dependencies;
public void AddDependency(Dependency dependency)
{
_dependencies.Add(dependency);
}
}
}

View File

@ -1,20 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Extensions.ProjectModel.Resolution
{
public enum DependencyType
{
Target,
Package,
Assembly,
Project,
AnalyzerAssembly,
Unknown
}
}

View File

@ -1,21 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Extensions.ProjectModel.Resolution
{
public class ResolvedReference
{
public ResolvedReference(string name,string resolvedPath)
{
Name = name;
ResolvedPath = resolvedPath;
}
public string ResolvedPath { get; }
public string Name { get; }
}
}

View File

@ -1,7 +0,0 @@
{
"version": "1.0.0-*",
"shared": "**/*.cs",
"frameworks": {
"netstandard1.0": {}
}
}

View File

@ -1,112 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.DotNet.ProjectModel;
using Microsoft.Extensions.ProjectModel.Resolution;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.Extensions.ProjectModel
{
internal class DotNetDependencyProvider
{
private ProjectContext _context;
private List<DependencyDescription> _packageDependencies;
private List<ResolvedReference> _resolvedReferences;
private string _configuration;
private List<string> _projectReferences;
public DotNetDependencyProvider(ProjectContext context, string configuration = Constants.DefaultConfiguration)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
_configuration = configuration;
_context = context;
DiscoverDependencies();
}
public IEnumerable<string> GetProjectReferences()
{
return _projectReferences;
}
public IEnumerable<DependencyDescription> GetPackageDependencies()
{
return _packageDependencies;
}
public IEnumerable<ResolvedReference> GetResolvedReferences()
{
return _resolvedReferences;
}
private void DiscoverDependencies()
{
var exporter = _context.CreateExporter(_configuration);
if (exporter == null)
{
throw new InvalidOperationException($"Couldn't create a library exporter for configuration {_configuration}");
}
var framework = _context.TargetFramework;
if (framework == null)
{
throw new InvalidOperationException("Couldn't resolve dependencies when target framework is not specified.");
}
var exports = exporter.GetDependencies();
_resolvedReferences = new List<ResolvedReference>();
_packageDependencies = new List<DependencyDescription>();
_projectReferences = new List<string>();
foreach (var export in exports)
{
var library = export.Library;
var project = library as ProjectDescription;
if (project != null)
{
_projectReferences.Add(project.Project.ProjectFilePath);
}
else
{
var description = new DependencyDescription(
library.Identity.Name,
library.Identity.Version.ToString(),
export.Library.Path,
framework.DotNetFrameworkName,
library.Identity.Type.Value,
library.Resolved);
foreach (var dependency in export.Library.Dependencies)
{
var dep = new Dependency(dependency.Name, version: string.Empty);
description.AddDependency(dep);
}
var itemSpec = $"{framework.DotNetFrameworkName}/{library.Identity.Name}/{library.Identity.Version.ToString()}";
_packageDependencies.Add(description);
}
// For resolved references we need to include all type of dependencies.
if (library.Resolved)
{
foreach (var asset in export.CompilationAssemblies)
{
var resolvedRef = new ResolvedReference(
name: Path.GetFileNameWithoutExtension(asset.FileName),
resolvedPath: asset.ResolvedPath);
_resolvedReferences.Add(resolvedRef);
}
}
}
}
}
}

View File

@ -1,155 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.DotNet.ProjectModel;
using Microsoft.Extensions.ProjectModel.Resolution;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Frameworks;
namespace Microsoft.Extensions.ProjectModel
{
internal class DotNetProjectContext : IProjectContext
{
private readonly ProjectContext _projectContext;
private readonly OutputPaths _paths;
private readonly Lazy<JObject> _rawProject;
private readonly CommonCompilerOptions _compilerOptions;
private readonly Lazy<DotNetDependencyProvider> _dependencyProvider;
private IEnumerable<DependencyDescription> _packageDependencies;
private IEnumerable<ResolvedReference> _compilationAssemblies;
private IEnumerable<string> _projectReferences;
public DotNetProjectContext(ProjectContext projectContext, string configuration, string outputPath)
{
if (projectContext == null)
{
throw new ArgumentNullException(nameof(projectContext));
}
if (string.IsNullOrEmpty(configuration))
{
throw new ArgumentNullException(nameof(configuration));
}
_rawProject = new Lazy<JObject>(() =>
{
using (var stream = new FileStream(projectContext.ProjectFile.ProjectFilePath, FileMode.Open, FileAccess.Read))
using (var streamReader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(streamReader))
{
return JObject.Load(jsonReader);
}
});
Configuration = configuration;
_projectContext = projectContext;
_paths = projectContext.GetOutputPaths(configuration, buidBasePath: null, outputPath: outputPath);
_compilerOptions = _projectContext.ProjectFile.GetCompilerOptions(TargetFramework, Configuration);
// Workaround https://github.com/dotnet/cli/issues/3164
IsClassLibrary = !(_compilerOptions?.EmitEntryPoint
?? projectContext.ProjectFile.GetCompilerOptions(null, configuration).EmitEntryPoint.GetValueOrDefault());
_dependencyProvider = new Lazy<DotNetDependencyProvider>(() => new DotNetDependencyProvider(_projectContext));
}
public bool IsClassLibrary { get; }
public NuGetFramework TargetFramework => _projectContext.TargetFramework;
public string Config => _paths.RuntimeFiles.Config;
public string DepsJson => _paths.RuntimeFiles.DepsJson;
public string RuntimeConfigJson => _paths.RuntimeFiles.RuntimeConfigJson;
public string PackagesDirectory => _projectContext.PackagesDirectory;
public string PackageLockFile => Path.Combine(Path.GetDirectoryName(ProjectFullPath), "project.lock.json");
public string AssemblyName => string.IsNullOrEmpty(AssemblyFullPath)
? ProjectName
: Path.GetFileNameWithoutExtension(AssemblyFullPath);
public string AssemblyFullPath =>
!IsClassLibrary && (_projectContext.IsPortable || TargetFramework.IsDesktop())
? _paths.RuntimeFiles.Executable
: _paths.RuntimeFiles.Assembly;
public string Configuration { get; }
public string ProjectFullPath => _projectContext.ProjectFile.ProjectFilePath;
public string ProjectName => _projectContext.ProjectFile.Name;
// TODO read from xproj if available
public string RootNamespace => _projectContext.ProjectFile.Name;
public string TargetDirectory => _paths.RuntimeOutputPath;
public string Platform => _compilerOptions?.Platform;
public IEnumerable<string> CompilationItems
=> (_compilerOptions?.CompileInclude == null)
? _projectContext.ProjectFile.Files.SourceFiles
: _compilerOptions.CompileInclude.ResolveFiles();
public IEnumerable<string> EmbededItems
=> (_compilerOptions?.EmbedInclude == null)
? _projectContext.ProjectFile.Files.ResourceFiles.Keys
: _compilerOptions.EmbedInclude.ResolveFiles();
public IEnumerable<DependencyDescription> PackageDependencies
{
get
{
if (_packageDependencies == null)
{
_packageDependencies = _dependencyProvider.Value.GetPackageDependencies();
}
return _packageDependencies;
}
}
public IEnumerable<ResolvedReference> CompilationAssemblies
{
get
{
if (_compilationAssemblies == null)
{
_compilationAssemblies = _dependencyProvider.Value.GetResolvedReferences();
}
return _compilationAssemblies;
}
}
public IEnumerable<string> ProjectReferences
{
get
{
if (_projectReferences == null)
{
_projectReferences = _dependencyProvider.Value.GetProjectReferences();
}
return _projectReferences;
}
}
/// <summary>
/// Returns string values of top-level keys in the project.json file
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
public string FindProperty(string propertyName) => FindProperty<string>(propertyName);
public TProperty FindProperty<TProperty>(string propertyName)
{
foreach (var item in _rawProject.Value)
{
if (item.Key.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
{
return item.Value.Value<TProperty>();
}
}
return default(TProperty);
}
}
}

View File

@ -1,25 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.DotNet.ProjectModel.Files;
namespace Microsoft.Extensions.ProjectModel
{
internal static class IncludeContextExtensions
{
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);
}
}
}

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0.25420" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0.25420</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>1f643a36-a1fc-4502-9d03-75837f20e1a4</ProjectGuid>
<RootNamespace>Microsoft.Extensions.ProjectModel.DotNet.Sources</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -1,7 +0,0 @@
{
"version": "1.0.0-*",
"shared": "**/*.cs",
"frameworks": {
"netstandard1.0": {}
}
}

View File

@ -1,11 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.Extensions.ProjectModel.Internal
{
internal class DotNetCoreSdk
{
public string BasePath { get; set; }
public string Version { get; set; }
}
}

View File

@ -1,129 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;
using Newtonsoft.Json;
using NuGet.Versioning;
namespace Microsoft.Extensions.ProjectModel.Internal
{
internal class DotNetCoreSdkResolver
{
private readonly string _installationDir;
/// <summary>
/// Represents a resolver that uses the currently executing <see cref="Muxer"/> to find the .NET Core SDK installation
/// </summary>
public static readonly DotNetCoreSdkResolver DefaultResolver = new DotNetCoreSdkResolver(Path.GetDirectoryName(new Muxer().MuxerPath));
/// <summary>
/// Instantiates a resolver that locates the SDK
/// </summary>
/// <param name="installationDir">The directory containing dotnet muxer, aka DOTNET_HOME</param>
public DotNetCoreSdkResolver(string installationDir)
{
_installationDir = installationDir;
}
/// <summary>
/// Find the latest SDK installation (uses SemVer 1.0 to determine what is "latest")
/// </summary>
/// <returns>Path to SDK root directory</returns>
public DotNetCoreSdk ResolveLatest()
{
var latest = FindInstalled()
.Select(d => new { path = d, version = SemanticVersion.Parse(Path.GetFileName(d)) })
.OrderByDescending(sdk => sdk.version)
.FirstOrDefault();
if (latest == null)
{
throw CreateSdkNotInstalledException();
}
return new DotNetCoreSdk
{
BasePath = latest.path,
Version = latest.version.ToFullString()
};
}
public DotNetCoreSdk ResolveProjectSdk(string projectDir)
{
var sdkVersion = ResolveGlobalJsonSdkVersion(projectDir);
if (string.IsNullOrEmpty(sdkVersion))
{
return ResolveLatest();
}
var sdk = FindInstalled()
.Where(p => Path.GetFileName(p).Equals(sdkVersion, StringComparison.OrdinalIgnoreCase))
.Select(d => new { path = d, version = SemanticVersion.Parse(Path.GetFileName(d)) })
.FirstOrDefault();
if (sdk == null)
{
throw CreateSdkNotInstalledException();
}
return new DotNetCoreSdk
{
BasePath = sdk.path,
Version = sdk.version.ToFullString()
};
}
private Exception CreateSdkNotInstalledException()
{
return new DirectoryNotFoundException($"Could not find an installation of the .NET Core SDK in '{_installationDir}'");
}
private IEnumerable<string> FindInstalled()
=> Directory.EnumerateDirectories(Path.Combine(_installationDir, "sdk"));
private string ResolveGlobalJsonSdkVersion(string start)
{
var dir = new DirectoryInfo(start);
FileInfo fileInfo = null;
while (dir != null)
{
var candidate = Path.Combine(dir.FullName, "global.json");
if (File.Exists(candidate))
{
fileInfo = new FileInfo(candidate);
break;
}
dir = dir.Parent;
}
if (fileInfo == null)
{
return null;
}
try
{
var contents = File.ReadAllText(fileInfo.FullName);
var globalJson = JsonConvert.DeserializeObject<GlobalJsonStub>(contents);
return globalJson?.sdk?.version;
}
catch (JsonException)
{
// TODO log
return null;
}
}
private class GlobalJsonStub
{
public GlobalJsonSdkStub sdk { get; set; }
public class GlobalJsonSdkStub
{
public string version { get; set; }
}
}
}
}

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0.25420" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0.25420</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>7362ae32-7753-4e7c-86d0-dca86af413fa</ProjectGuid>
<RootNamespace>Microsoft.Extensions.ProjectModel.MsBuild.Sources</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -1,39 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.Extensions.ProjectModel.Internal;
namespace Microsoft.Extensions.ProjectModel
{
/// <summary>
/// Represents the msbuild context used to parse a project model
/// </summary>
internal class MsBuildContext
{
public string MsBuildExecutableFullPath { get; private set; }
public string ExtensionsPath { get; private set; }
public static MsBuildContext FromCurrentDotNetSdk()
{
var sdk = DotNetCoreSdkResolver.DefaultResolver.ResolveLatest();
return FromDotNetSdk(sdk);
}
public static MsBuildContext FromDotNetSdk(DotNetCoreSdk sdk)
{
if (sdk == null)
{
throw new ArgumentNullException(nameof(sdk));
}
return new MsBuildContext
{
// might change... See https://github.com/Microsoft/msbuild/issues/1136
MsBuildExecutableFullPath = Path.Combine(sdk.BasePath, "MSBuild.exe"),
ExtensionsPath = sdk.BasePath
};
}
}
}

View File

@ -1,14 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
namespace Microsoft.Build.Execution
{
internal static class MsBuildExtensions
{
public static string FindProperty(this ProjectInstance projectInstance, string propertyName, StringComparison comparer)
=> projectInstance.Properties.FirstOrDefault(p => p.Name.Equals(propertyName, comparer))?.EvaluatedValue;
}
}

View File

@ -1,131 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Build.Execution;
using NuGet.Frameworks;
using System.Linq;
using Microsoft.Extensions.ProjectModel.Resolution;
namespace Microsoft.Extensions.ProjectModel
{
internal class MsBuildProjectContext : IProjectContext
{
private const string CompileItemName = "Compile";
private const string EmbedItemName = "EmbeddedResource";
private const string FullPathMetadataName = "FullPath";
private readonly MsBuildProjectDependencyProvider _dependencyProvider;
private IEnumerable<DependencyDescription> _packageDependencies;
private IEnumerable<ResolvedReference> _compilationAssemblies;
private IEnumerable<string> _projectReferences;
protected ProjectInstance Project { get; }
protected string Name { get; }
public MsBuildProjectContext(string name, string configuration, ProjectInstance project)
{
Project = project;
Configuration = configuration;
Name = name;
_dependencyProvider = new MsBuildProjectDependencyProvider(Project);
}
public string FindProperty(string propertyName)
{
return Project.GetProperty(propertyName)?.EvaluatedValue;
}
public string ProjectName => FindProperty("ProjectName") ?? Name;
public string Configuration { get; }
public NuGetFramework TargetFramework
{
get
{
var tfm = FindProperty("NuGetTargetMoniker") ?? FindProperty("TargetFramework");
if (tfm == null)
{
return null;
}
return NuGetFramework.Parse(tfm);
}
}
public bool IsClassLibrary => FindProperty("OutputType").Equals("Library", StringComparison.OrdinalIgnoreCase);
// TODO get from actual properties according to TFM
public string Config => AssemblyFullPath + ".config";
public string DepsJson => Path.Combine(TargetDirectory, Path.GetFileNameWithoutExtension(AssemblyFullPath) + ".deps.json");
public string RuntimeConfigJson => Path.Combine(TargetDirectory, Path.GetFileNameWithoutExtension(AssemblyFullPath) + ".runtimeconfig.json");
public string PackagesDirectory => FindProperty("NuGetPackageRoot");
public string PackageLockFile
{
get
{
var restoreOutputPath = FindProperty("RestoreOutputPath");
if (string.IsNullOrEmpty(restoreOutputPath))
{
restoreOutputPath = Path.Combine(Path.GetDirectoryName(ProjectFullPath), "obj");
}
return Path.Combine(restoreOutputPath, "project.assets.json");
}
}
public string AssemblyName => string.IsNullOrEmpty(AssemblyFullPath)
? ProjectName
: Path.GetFileNameWithoutExtension(AssemblyFullPath);
public string AssemblyFullPath => FindProperty("TargetPath");
public string Platform => FindProperty("Platform");
public string ProjectFullPath => Project.FullPath;
public string RootNamespace => FindProperty("RootNamespace") ?? ProjectName;
public string TargetDirectory => FindProperty("TargetDir");
public IEnumerable<string> CompilationItems
=> Project.GetItems(CompileItemName).Select(i => i.GetMetadataValue(FullPathMetadataName));
public IEnumerable<string> EmbededItems
=> Project.GetItems(EmbedItemName).Select(i => i.GetMetadataValue(FullPathMetadataName));
public IEnumerable<DependencyDescription> PackageDependencies
{
get
{
if (_packageDependencies == null)
{
_packageDependencies = _dependencyProvider.GetPackageDependencies();
}
return _packageDependencies;
}
}
public IEnumerable<ResolvedReference> CompilationAssemblies
{
get
{
if (_compilationAssemblies == null)
{
_compilationAssemblies = _dependencyProvider.GetResolvedReferences();
}
return _compilationAssemblies;
}
}
public IEnumerable<string> ProjectReferences
{
get
{
if (_projectReferences == null)
{
_projectReferences = _dependencyProvider.GetProjectReferences();
}
return _projectReferences;
}
}
}
}

View File

@ -1,285 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders.Physical;
using Microsoft.Extensions.ProjectModel.Internal;
using NuGet.Frameworks;
using System.Linq;
namespace Microsoft.Extensions.ProjectModel
{
internal class MsBuildProjectContextBuilder
{
protected string _configuration;
protected IFileInfo _fileInfo;
protected string[] _buildTargets;
protected Dictionary<string, string> _globalProperties = new Dictionary<string, string>();
private MsBuildContext _msbuildContext;
public MsBuildProjectContextBuilder()
{
Initialize();
}
public virtual MsBuildProjectContextBuilder Clone()
{
var builder = new MsBuildProjectContextBuilder()
.WithProperties(_globalProperties)
.WithBuildTargets(_buildTargets);
if (_msbuildContext != null)
{
builder.UseMsBuild(_msbuildContext);
}
if (_fileInfo != null)
{
builder.WithProjectFile(_fileInfo);
}
if (_configuration != null)
{
builder.WithConfiguration(_configuration);
}
return builder;
}
public MsBuildProjectContextBuilder WithBuildTargets(string[] targets)
{
if (targets == null)
{
throw new ArgumentNullException(nameof(targets));
}
_buildTargets = targets;
return this;
}
public MsBuildProjectContextBuilder WithConfiguration(string configuration)
{
_configuration = configuration;
WithProperty("Configuration", configuration);
return this;
}
public MsBuildProjectContextBuilder AsDesignTimeBuild()
{
// don't to expensive things
WithProperty("DesignTimeBuild", "true");
WithProperty("_ResolveReferenceDependencies", "true");
WithProperty("BuildProjectReferences", "false");
return this;
}
// should be needed in most cases, but can be used to override
public MsBuildProjectContextBuilder UseMsBuild(MsBuildContext context)
{
_msbuildContext = context;
/*
Workaround https://github.com/Microsoft/msbuild/issues/999
Error: System.TypeInitializationException : The type initializer for 'BuildEnvironmentHelperSingleton' threw an exception.
Could not determine a valid location to MSBuild. Try running this process from the Developer Command Prompt for Visual Studio.
*/
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", context.MsBuildExecutableFullPath);
WithProperty("MSBuildExtensionsPath", context.ExtensionsPath);
return this;
}
public MsBuildProjectContextBuilder WithProperties(IDictionary<string, string> properties)
{
foreach (var prop in properties)
{
_globalProperties[prop.Key] = prop.Value;
}
return this;
}
public MsBuildProjectContextBuilder WithProperty(string property, string value)
{
_globalProperties[property] = value;
return this;
}
public MsBuildProjectContextBuilder WithProjectFile(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
var fileInfo = new PhysicalFileInfo(new FileInfo(filePath));
return WithProjectFile(fileInfo);
}
public MsBuildProjectContextBuilder WithProjectFile(IFileInfo fileInfo)
{
if (_msbuildContext == null)
{
var projectDir = Path.GetDirectoryName(fileInfo.PhysicalPath);
var sdk = DotNetCoreSdkResolver.DefaultResolver.ResolveProjectSdk(projectDir);
UseMsBuild(MsBuildContext.FromDotNetSdk(sdk));
}
_fileInfo = fileInfo;
return this;
}
public MsBuildProjectContextBuilder WithTargetFramework(NuGetFramework framework)
=> WithTargetFramework(framework.GetShortFolderName());
public MsBuildProjectContextBuilder WithTargetFramework(string framework)
=> WithProperty("TargetFramework", framework);
public virtual MsBuildProjectContext Build(bool ignoreBuildErrors = false)
{
var projectCollection = CreateProjectCollection();
var project = CreateProject(_fileInfo, _configuration, _globalProperties, projectCollection);
if (project.GetProperty("TargetFramework") == null)
{
var frameworks = GetAvailableTargetFrameworks(project).ToList();
if (frameworks.Count > 1)
{
throw new InvalidOperationException($"Multiple frameworks are available. Either use {nameof(WithTargetFramework)} or {nameof(BuildAllTargetFrameworks)}");
}
if (frameworks.Count == 0)
{
throw new InvalidOperationException($"No frameworks are available. Either use {nameof(WithTargetFramework)} or {nameof(BuildAllTargetFrameworks)}");
}
project.SetGlobalProperty("TargetFramework", frameworks.Single());
}
var projectInstance = CreateProjectInstance(project, _buildTargets, ignoreBuildErrors);
var name = Path.GetFileNameWithoutExtension(_fileInfo.Name);
return new MsBuildProjectContext(name, _configuration, projectInstance);
}
public IEnumerable<MsBuildProjectContext> BuildAllTargetFrameworks()
{
var projectCollection = CreateProjectCollection();
var project = CreateProject(_fileInfo, _configuration, _globalProperties, projectCollection);
foreach (var framework in GetAvailableTargetFrameworks(project))
{
var builder = Clone();
builder.WithTargetFramework(framework);
yield return builder.Build();
}
}
protected virtual void Initialize()
{
WithBuildTargets(new[] { "ResolveReferences", "ResolvePackageDependenciesDesignTime" });
WithProperty("_ResolveReferenceDependencies", "true");
}
protected virtual ProjectCollection CreateProjectCollection() => new ProjectCollection();
protected virtual Project CreateProject(IFileInfo fileInfo,
string configuration,
IDictionary<string, string> globalProps,
ProjectCollection projectCollection)
{
using (var stream = fileInfo.CreateReadStream())
{
var xmlReader = XmlReader.Create(stream);
var xml = ProjectRootElement.Create(xmlReader, projectCollection, preserveFormatting: true);
xml.FullPath = fileInfo.PhysicalPath;
return new Project(xml, globalProps, toolsVersion: null, projectCollection: projectCollection);
}
}
protected virtual ProjectInstance CreateProjectInstance(Project project, string[] targets, bool ignoreErrors)
{
var projectInstance = project.CreateProjectInstance();
if (targets.Length == 0)
{
return projectInstance;
}
var logger = new InMemoryLogger();
projectInstance.Build(targets, new[] { logger });
if (!ignoreErrors && logger.Errors.Count > 0)
{
throw CreateBuildFailedException(project.FullPath, logger.Errors);
}
return projectInstance;
}
private Exception CreateBuildFailedException(string filePath, IList<BuildErrorEventArgs> errors)
{
var sb = new StringBuilder();
sb.AppendLine($"Building '{filePath}' failed.");
for (var i = 0; i < errors.Count; i++)
{
sb.Append(i).Append(" :").AppendLine(errors[i].Message);
}
throw new InvalidOperationException(sb.ToString());
}
private IEnumerable<string> GetAvailableTargetFrameworks(Project project)
{
var frameworks = project.GetProperty("TargetFrameworks")?.EvaluatedValue;
if (string.IsNullOrEmpty(frameworks))
{
return Enumerable.Empty<string>();
}
return frameworks.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
private class InMemoryLogger : ILogger
{
private readonly Stack<Action> _onShutdown = new Stack<Action>();
internal IList<BuildErrorEventArgs> Errors = new List<BuildErrorEventArgs>();
public string Parameters { get; set; }
public LoggerVerbosity Verbosity { get; set; }
public void Initialize(IEventSource eventSource)
{
eventSource.ErrorRaised += OnError;
_onShutdown.Push(() =>
{
eventSource.ErrorRaised -= OnError;
});
}
private void OnError(object sender, BuildErrorEventArgs e)
{
Errors.Add(e);
}
public void Shutdown()
{
while (_onShutdown.Count > 0)
{
_onShutdown.Pop()?.Invoke();
}
}
}
}
}

View File

@ -1,138 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Execution;
using Microsoft.Extensions.ProjectModel.Resolution;
namespace Microsoft.Extensions.ProjectModel
{
internal class MsBuildProjectDependencyProvider
{
private const string PackageDependencyItemType = "_DependenciesDesignTime";
private const string ResolvedReferenceItemType = "ReferencePath";
private readonly ProjectInstance _projectInstance;
public MsBuildProjectDependencyProvider(ProjectInstance projectInstance)
{
if (projectInstance == null)
{
throw new ArgumentNullException(nameof(projectInstance));
}
_projectInstance = projectInstance;
}
public IEnumerable<string> GetProjectReferences()
{
var projectPaths = _projectInstance
.GetItems("ProjectReference")
.Select(reference => reference.EvaluatedInclude);
return projectPaths
.Select(path => Path.IsPathRooted(path)
? path
: Path.Combine(_projectInstance.Directory, path));
}
public IEnumerable<DependencyDescription> GetPackageDependencies()
{
var packageItems = _projectInstance.GetItems(PackageDependencyItemType);
var packageInfo = new Dictionary<string, DependencyDescription>(StringComparer.OrdinalIgnoreCase);
if (packageItems != null)
{
foreach (var packageItem in packageItems)
{
var packageDependency = CreateDependencyDescriptionFromItem(packageItem);
if (packageDependency != null)
{
packageInfo[packageItem.EvaluatedInclude] = packageDependency;
}
}
// 2nd pass to populate dependencies;
PopulateDependencies(packageInfo, packageItems);
}
return packageInfo.Values;
}
public IEnumerable<ResolvedReference> GetResolvedReferences()
{
var refItems = _projectInstance.GetItems(ResolvedReferenceItemType);
var resolvedReferences = refItems
?.Select(refItem => CreateResolvedReferenceFromProjectItem(refItem))
.Where(resolvedReference => resolvedReference != null);
return resolvedReferences;
}
private static ResolvedReference CreateResolvedReferenceFromProjectItem(ProjectItemInstance item)
{
var resolvedPath = item.EvaluatedInclude;
if (string.IsNullOrEmpty(resolvedPath))
{
return null;
}
var name = Path.GetFileNameWithoutExtension(resolvedPath);
return new ResolvedReference(name, resolvedPath);
}
private static DependencyDescription CreateDependencyDescriptionFromItem(ProjectItemInstance item)
{
// For type == Target, we do not get Name in the metadata. This is a special node where the dependencies are
// the direct dependencies of the project.
var itemSpec = item.EvaluatedInclude;
var name = item.HasMetadata("Name") ? item.GetMetadataValue("Name") : itemSpec;
if (string.IsNullOrEmpty(name))
{
return null;
}
var version = item.GetMetadataValue("Version");
var path = item.GetMetadataValue("Path");
var type = item.GetMetadataValue("Type");
var resolved = item.GetMetadataValue("Resolved");
bool isResolved;
isResolved = bool.TryParse(resolved, out isResolved) ? isResolved : false;
var framework = itemSpec.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).First();
return new DependencyDescription(name, version, path, framework, type, isResolved);
}
private static void PopulateDependencies(Dictionary<string, DependencyDescription> dependencies, ICollection<ProjectItemInstance> items)
{
foreach (var item in items)
{
var depSpecs = item.GetMetadataValue("Dependencies")
?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
DependencyDescription currentDescription = null;
if (depSpecs == null || !dependencies.TryGetValue(item.EvaluatedInclude, out currentDescription))
{
return;
}
var prefix = item.EvaluatedInclude.Split('/').FirstOrDefault();
foreach (var depSpec in depSpecs)
{
var spec = $"{prefix}/{depSpec}";
DependencyDescription dependency = null;
if (dependencies.TryGetValue(spec, out dependency))
{
var dep = new Dependency(dependency.Name, dependency.Version);
currentDescription.AddDependency(dep);
}
}
}
}
}
}

View File

@ -1,72 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
// TODO if this becomes a true API instead of .Sources package, put strings into resource file
namespace Microsoft.Extensions.ProjectModel
{
internal class MsBuildProjectFinder
{
private readonly string _directory;
public MsBuildProjectFinder(string directory)
{
if (string.IsNullOrEmpty(directory))
{
throw new ArgumentException("Value cannot be null or empty", nameof(directory));
}
_directory = directory;
}
public string FindMsBuildProject(string project = null)
{
var projectPath = project ?? _directory;
if (!Path.IsPathRooted(projectPath))
{
projectPath = Path.Combine(_directory, projectPath);
}
if (Directory.Exists(projectPath))
{
var projects = FindProjectFiles(projectPath).ToList();
if (projects.Count > 1)
{
throw MultipleProjectsFound(projectPath);
}
if (projects.Count == 0)
{
throw NoProjectsFound(projectPath);
}
return projects[0];
}
if (!File.Exists(projectPath))
{
throw FileDoesNotExist(projectPath);
}
return projectPath;
}
protected virtual Exception FileDoesNotExist(string filePath)
=> new InvalidOperationException($"No file was found at '{filePath}'.");
protected virtual Exception MultipleProjectsFound(string directory)
=> new InvalidOperationException($"Multiple MSBuild project files found in '{directory}'.");
protected virtual Exception NoProjectsFound(string directory)
=> new InvalidOperationException($"Could not find a MSBuild project file in '{directory}'.");
protected virtual IEnumerable<string> FindProjectFiles(string directory)
=> Directory.EnumerateFileSystemEntries(directory, "*.*proj", SearchOption.TopDirectoryOnly);
}
}

View File

@ -1,7 +0,0 @@
{
"version": "1.0.0-*",
"shared": "**/*.cs",
"frameworks": {
"netstandard1.0": {}
}
}

View File

@ -1,119 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.ProjectModel;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Extensions.ProjectModel.DotNet
{
public class DotNetDependencyProviderTests
{
private const string globalJson = @"
{
""projects"": [ ""demo"", ""demoLib""]
}";
private const string projectJson = @"
{
""buildOptions"": {
},
""dependencies"": {
""Microsoft.AspNetCore.Mvc"": ""1.0.0-*"",
""demoLib"": ""1.0.0-*"",
},
""frameworks"": {
""netcoreapp1.0"": {
""dependencies"": {
""Microsoft.NETCore.App"": {
""version"": ""1.0.0"",
""type"": ""platform""
}
}
}
},
}
";
private const string libProjectJson = @"
{
""buildOptions"": {
},
""dependencies"": {
""Microsoft.AspNetCore.Mvc"": ""1.0.0-*"",
},
""frameworks"": {
""netcoreapp1.0"": {
""dependencies"": {
""Microsoft.NETCore.App"": {
""version"": ""1.0.0"",
""type"": ""platform""
}
}
}
},
}
";
private readonly ITestOutputHelper _output;
public DotNetDependencyProviderTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void BuildProjectDependencies()
{
using (var fileProvider = new TemporaryFileProvider())
{
Directory.CreateDirectory(Path.Combine(fileProvider.Root, "demo"));
Directory.CreateDirectory(Path.Combine(fileProvider.Root, "demoLib"));
fileProvider.Add($"global.json", globalJson);
fileProvider.Add($"demo/project.json", projectJson);
fileProvider.Add($"demo/First.cs", "namespace demo { class First{} }");
fileProvider.Add($"demoLib/project.json", libProjectJson);
fileProvider.Add($"demoLib/Second.cs", "namespace demoLib { class First{} }");
var muxer = new Muxer().MuxerPath;
var result = Command
.Create(muxer, new[] { "restore", fileProvider.Root })
.OnErrorLine(l => _output.WriteLine(l))
.OnOutputLine(l => _output.WriteLine(l))
.Execute();
Assert.Equal(0, result.ExitCode);
var oldContext = ProjectContext
.CreateContextForEachFramework(Path.Combine(fileProvider.Root, "demo", "project.json"))
.First();
var context = new DotNetProjectContext(oldContext, "Debug", Path.Combine(fileProvider.Root, "demo", "bin"));
var assembly = context
.CompilationAssemblies
.Where(asm => asm.Name.Equals("Microsoft.AspNetCore.Mvc", StringComparison.OrdinalIgnoreCase))
.First();
Assert.True(File.Exists(assembly.ResolvedPath));
Assert.True(assembly.ResolvedPath.EndsWith("Microsoft.AspNetCore.Mvc.dll", StringComparison.OrdinalIgnoreCase));
var mvcPackage = context
.PackageDependencies
.Where(package => package.Name.Equals("Microsoft.AspNetCore.Mvc", StringComparison.OrdinalIgnoreCase))
.First();
Assert.True(Directory.Exists(mvcPackage.Path));
Assert.True(mvcPackage.Path.EndsWith($"Microsoft.AspNetCore.Mvc{Path.DirectorySeparatorChar}1.0.0", StringComparison.OrdinalIgnoreCase), mvcPackage.Path);
Assert.True(context.ProjectReferences.First().Equals(Path.Combine(fileProvider.Root, "demoLib", "project.json")));
}
}
}
}

View File

@ -1,21 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0.25420" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0.25420</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>1a66a831-4f06-46d9-b483-70a4e75a2f7f</ProjectGuid>
<RootNamespace>Microsoft.Extensions.ProjectModel</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -1,57 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.Extensions.ProjectModel.Internal;
using Xunit;
namespace Microsoft.Extensions.ProjectModel
{
public class DotNetCoreSdkResolverTest : IDisposable
{
private readonly string _fakeInstallDir;
public DotNetCoreSdkResolverTest()
{
_fakeInstallDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_fakeInstallDir);
Directory.CreateDirectory(Path.Combine(_fakeInstallDir, "sdk"));
}
[Fact]
public void ResolveLatest()
{
var project = Path.Combine(_fakeInstallDir, "project");
Directory.CreateDirectory(project);
Directory.CreateDirectory(Path.Combine(_fakeInstallDir, "sdk", "1.0.1"));
Directory.CreateDirectory(Path.Combine(_fakeInstallDir, "sdk", "1.0.0"));
Directory.CreateDirectory(Path.Combine(_fakeInstallDir, "sdk", "1.0.0-beta1"));
var sdk = new DotNetCoreSdkResolver(_fakeInstallDir).ResolveLatest();
Assert.Equal("1.0.1", sdk.Version);
Assert.Equal(Path.Combine(_fakeInstallDir, "sdk", "1.0.1"), sdk.BasePath);
}
[Fact]
public void ResolveProjectSdk()
{
var project = Path.Combine(_fakeInstallDir, "project");
Directory.CreateDirectory(project);
Directory.CreateDirectory(Path.Combine(_fakeInstallDir, "sdk", "1.0.0"));
Directory.CreateDirectory(Path.Combine(_fakeInstallDir, "sdk", "1.0.0-abc-123"));
Directory.CreateDirectory(Path.Combine(_fakeInstallDir, "sdk", "1.0.0-xyz-123"));
File.WriteAllText(Path.Combine(_fakeInstallDir, "global.json"), @"{
""sdk"": {
""version"": ""1.0.0-abc-123""
}
}");
var sdk = new DotNetCoreSdkResolver(_fakeInstallDir).ResolveProjectSdk(project);
Assert.Equal("1.0.0-abc-123", sdk.Version);
Assert.Equal(Path.Combine(_fakeInstallDir, "sdk", "1.0.0-abc-123"), sdk.BasePath);
}
public void Dispose()
{
Directory.Delete(_fakeInstallDir, recursive: true);
}
}
}

View File

@ -1,139 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.Extensions.ProjectModel.Tests;
using NuGet.Frameworks;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Extensions.ProjectModel
{
public class MsBuildProjectContextBuilderTest : IClassFixture<MsBuildFixture>, IDisposable
{
private const string SkipReason = "CI doesn't yet have a new enough version of .NET Core SDK";
private readonly MsBuildFixture _fixture;
private readonly ITestOutputHelper _output;
private readonly TemporaryFileProvider _files;
public MsBuildProjectContextBuilderTest(MsBuildFixture fixture, ITestOutputHelper output)
{
_fixture = fixture;
_output = output;
_files = new TemporaryFileProvider();
}
public void Dispose()
{
_files.Dispose();
}
[Fact(Skip = SkipReason)]
public void BuildsAllTargetFrameworks()
{
_files.Add("test.proj", @"
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<PropertyGroup>
<TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
</PropertyGroup>
</Project>
");
var contexts = new MsBuildProjectContextBuilder()
.WithBuildTargets(Array.Empty<string>())
.WithProjectFile(_files.GetFileInfo("test.proj"))
.BuildAllTargetFrameworks()
.ToList();
Assert.Collection(contexts,
context =>
{
Assert.Equal(FrameworkConstants.CommonFrameworks.Net451, context.TargetFramework);
},
context =>
{
Assert.Equal(FrameworkConstants.CommonFrameworks.NetStandard13, context.TargetFramework);
});
}
[Fact(Skip = SkipReason)]
public void ExecutesDesignTimeBuild()
{
// TODO remove when SDK becomes available on other feeds
_files.Add("NuGet.config", @"
<configuration>
<packageSources>
<clear />
<add key=""dotnet-core"" value=""https://dotnet.myget.org/F/dotnet-core/api/v3/index.json"" />
<add key=""dotnet-buildtools"" value=""https://dotnet.myget.org/F/dotnet-buildtools/api/v3/index.json"" />
<add key=""nugetbuild"" value=""https://www.myget.org/F/nugetbuild/api/v3/index.json"" />
</packageSources>
</configuration>");
_files.Add("test.csproj", @"
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" />
<PropertyGroup>
<RootNamespace>Microsoft.TestProject</RootNamespace>
<ProjectName>TestProject</ProjectName>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp1.0</TargetFrameworks>
<OutputPath>bin\$(Configuration)</OutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Include=""**\*.cs"" Exclude=""Excluded.cs"" />
</ItemGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.NETCore.Sdk"">
<Version>1.0.0-*</Version>
</PackageReference>
<PackageReference Include=""Microsoft.NETCore.App"">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>
");
_files.Add("One.cs", "public class Abc {}");
_files.Add("Two.cs", "public class Abc2 {}");
_files.Add("Excluded.cs", "public class Abc {}");
var testContext = _fixture.GetMsBuildContext();
var muxer = Path.Combine(testContext.ExtensionsPath, "../..", "dotnet.exe");
var result = Command
.Create(muxer, new[] { "restore3", Path.Combine(_files.Root, "test.csproj") })
.OnErrorLine(l => _output.WriteLine(l))
.OnOutputLine(l => _output.WriteLine(l))
.Execute();
Assert.Equal(0, result.ExitCode);
var expectedCompileItems = new[] { "One.cs", "Two.cs" }.Select(p => Path.Combine(_files.Root, p)).ToArray();
var context = new MsBuildProjectContextBuilder()
.AsDesignTimeBuild()
.UseMsBuild(testContext)
.WithConfiguration("Debug")
.WithProjectFile(_files.GetFileInfo("test.csproj"))
.Build();
Assert.False(_files.GetFileInfo("bin").Exists);
Assert.False(_files.GetFileInfo("obj").Exists);
Assert.Equal(expectedCompileItems, context.CompilationItems.OrderBy(i => i).ToArray());
Assert.Equal(Path.Combine(_files.Root, "bin", "Debug", "netcoreapp1.0", "test.dll"), context.AssemblyFullPath);
Assert.True(context.IsClassLibrary, "Expecting IsClassLibrary == true");
Assert.Equal("TestProject", context.ProjectName);
Assert.Equal(FrameworkConstants.CommonFrameworks.NetCoreApp10, context.TargetFramework);
Assert.Equal("Microsoft.TestProject", context.RootNamespace);
}
}
}

View File

@ -1,164 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.IO;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.Extensions.ProjectModel.Tests;
using NuGet.Frameworks;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Extensions.ProjectModel.MsBuild
{
public class MsBuildProjectDependencyProviderTests : IClassFixture<MsBuildFixture>
{
private const string SkipReason = "CI doesn't yet have a new enough version of .NET Core SDK";
private const string NugetConfigTxt = @"
<configuration>
<packageSources>
<clear />
<add key=""NuGet"" value=""https://api.nuget.org/v3/index.json"" />
<add key=""dotnet-core"" value=""https://dotnet.myget.org/F/dotnet-core/api/v3/index.json"" />
<add key=""dotnet-buildtools"" value=""https://dotnet.myget.org/F/dotnet-buildtools/api/v3/index.json"" />
<add key=""nugetbuild"" value=""https://www.myget.org/F/nugetbuild/api/v3/index.json"" />
</packageSources>
</configuration>";
private const string RootProjectTxt = @"
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" />
<PropertyGroup>
<RootNamespace>Microsoft.TestProject</RootNamespace>
<ProjectName>TestProject</ProjectName>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp1.0</TargetFrameworks>
<OutputPath>bin\$(Configuration)</OutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Include=""**\*.cs"" Exclude=""Excluded.cs"" />
</ItemGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.AspNetCore.Mvc"">
<Version>1.0.0-*</Version>
</PackageReference>
<PackageReference Include=""Microsoft.NETCore.Sdk"">
<Version>1.0.0-*</Version>
</PackageReference>
<PackageReference Include=""Microsoft.NETCore.App"">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include=""..\Library1\Library1.csproj"" />
</ItemGroup>
<ItemGroup>
<Reference Include = ""xyz.dll"" />
</ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>
";
private const string LibraryProjectTxt = @"
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" />
<PropertyGroup>
<RootNamespace>Microsoft.Library</RootNamespace>
<ProjectName>Library1</ProjectName>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp1.0</TargetFrameworks>
<OutputPath>bin\$(Configuration)</OutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Include=""**\*.cs"" Exclude=""Excluded.cs"" />
</ItemGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.NETCore.Sdk"">
<Version>1.0.0-*</Version>
</PackageReference>
<PackageReference Include=""Microsoft.NETCore.App"">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>
";
private readonly MsBuildFixture _fixture;
private readonly ITestOutputHelper _output;
public MsBuildProjectDependencyProviderTests(MsBuildFixture fixture, ITestOutputHelper output)
{
_fixture = fixture;
_output = output;
}
[Fact(Skip = SkipReason)]
public void BuildDependenciesForProject()
{
using (var fileProvider = new TemporaryFileProvider())
{
Directory.CreateDirectory(Path.Combine(fileProvider.Root, "Root"));
Directory.CreateDirectory(Path.Combine(fileProvider.Root, "Library1"));
// TODO remove when SDK becomes available on other feeds
fileProvider.Add("NuGet.config", NugetConfigTxt);
// Add Root Project
fileProvider.Add($"Root/test.csproj", RootProjectTxt);
fileProvider.Add($"Root/One.cs", "public class Abc {}");
fileProvider.Add($"Root/Two.cs", "public class Abc2 {}");
fileProvider.Add($"Root/Excluded.cs", "public class Abc {}");
// Add Class Library project
fileProvider.Add($"Library1/Library1.csproj", LibraryProjectTxt);
fileProvider.Add($"Library1/Three.cs", "public class Abc3 {}");
var testContext = _fixture.GetMsBuildContext();
var muxer = Path.Combine(testContext.ExtensionsPath, "../..", "dotnet.exe");
var result = Command
.Create(muxer, new[] { "restore3", Path.Combine(fileProvider.Root, "Library1", "Library1.csproj") })
.OnErrorLine(l => _output.WriteLine(l))
.OnOutputLine(l => _output.WriteLine(l))
.Execute();
Assert.Equal(0, result.ExitCode);
result = Command
.Create(muxer, new[] { "restore3", Path.Combine(fileProvider.Root, "Root", "test.csproj") })
.OnErrorLine(l => _output.WriteLine(l))
.OnOutputLine(l => _output.WriteLine(l))
.Execute();
Assert.Equal(0, result.ExitCode);
var builder = new MsBuildProjectContextBuilder()
.AsDesignTimeBuild()
.UseMsBuild(testContext)
.WithTargetFramework(FrameworkConstants.CommonFrameworks.NetCoreApp10)
.WithConfiguration("Debug")
.WithProjectFile(fileProvider.GetFileInfo(Path.Combine("Root", "test.csproj")));
var context = builder.Build();
var lib1Dll = Assert.Single(context.CompilationAssemblies, a => a.Name.Equals("Library1", StringComparison.OrdinalIgnoreCase));
Assert.False(File.Exists(lib1Dll.ResolvedPath), $"Design time build. Shouldn't produce a file to {lib1Dll.ResolvedPath}");
// This reference doesn't resolve so should not be available here.
Assert.DoesNotContain("xyz", context.CompilationAssemblies.Select(a => a.Name), StringComparer.OrdinalIgnoreCase);
var packageDependencies = context.PackageDependencies;
var mvcPackage = Assert.Single(context.PackageDependencies, p => p.Name.Equals("Microsoft.AspNetCore.Mvc", StringComparison.OrdinalIgnoreCase));
Assert.Contains("Microsoft.Extensions.DependencyInjection", mvcPackage.Dependencies.Select(d => d.Name), StringComparer.OrdinalIgnoreCase);
Assert.Equal(Path.Combine(fileProvider.Root, "Root", "..", "Library1", "Library1.csproj"), context.ProjectReferences.First());
}
}
}
}

View File

@ -1,73 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Xunit;
namespace Microsoft.Extensions.ProjectModel.MsBuild
{
public class MsBuildProjectFinderTest
{
[Theory]
[InlineData(".csproj")]
[InlineData(".vbproj")]
[InlineData(".fsproj")]
public void FindsSingleProject(string extension)
{
using (var files = new TemporaryFileProvider())
{
var filename = "TestProject" + extension;
files.Add(filename, "");
var finder = new MsBuildProjectFinder(files.Root);
Assert.Equal(Path.Combine(files.Root, filename), finder.FindMsBuildProject());
}
}
[Fact]
public void ThrowsWhenNoFile()
{
using (var files = new TemporaryFileProvider())
{
var finder = new MsBuildProjectFinder(files.Root);
Assert.Throws<InvalidOperationException>(() => finder.FindMsBuildProject());
}
}
[Fact]
public void ThrowsWhenMultipleFile()
{
using (var files = new TemporaryFileProvider())
{
files.Add("Test1.csproj", "");
files.Add("Test2.csproj", "");
var finder = new MsBuildProjectFinder(files.Root);
Assert.Throws<InvalidOperationException>(() => finder.FindMsBuildProject());
}
}
[Fact]
public void ThrowsWhenFileDoesNotExist()
{
using (var files = new TemporaryFileProvider())
{
var finder = new MsBuildProjectFinder(files.Root);
Assert.Throws<InvalidOperationException>(() => finder.FindMsBuildProject("test.csproj"));
}
}
[Fact]
public void ThrowsWhenRootDoesNotExist()
{
var files = new TemporaryFileProvider();
var finder = new MsBuildProjectFinder(files.Root);
files.Dispose();
Assert.Throws<InvalidOperationException>(() => finder.FindMsBuildProject());
}
}
}

View File

@ -1,29 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Text;
using Microsoft.Extensions.FileProviders;
namespace Microsoft.Extensions.ProjectModel
{
internal class TemporaryFileProvider : PhysicalFileProvider
{
public TemporaryFileProvider()
:base(Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "tmpfiles", Guid.NewGuid().ToString())).FullName)
{
}
public void Add(string filename, string contents)
{
File.WriteAllText(Path.Combine(this.Root, filename), contents, Encoding.UTF8);
}
public new void Dispose()
{
base.Dispose();
Directory.Delete(Root, recursive: true);
}
}
}

View File

@ -1,42 +0,0 @@
{
"buildOptions": {
"warningsAsErrors": true,
"keyFile": "../../tools/Key.snk",
"compile": {
"include": "../Shared/*.cs"
}
},
"dependencies": {
"NuGet.ProjectModel": "3.6.0-*",
"NuGet.Frameworks": "3.6.0-*",
"Microsoft.DotNet.Cli.Utils": "1.0.0-preview2-003121",
"Microsoft.DotNet.ProjectModel": "1.0.0-rc3-003121",
"Microsoft.Build.Runtime": "15.1.319-preview5",
"Microsoft.Extensions.FileProviders.Physical": "1.1.0-*",
"Microsoft.Extensions.ProjectModel.Abstractions.Sources": {
"type": "build",
"version": "1.0.0-*"
},
"Microsoft.Extensions.ProjectModel.DotNet.Sources": {
"type": "build",
"version": "1.0.0-*"
},
"Microsoft.Extensions.ProjectModel.MsBuild.Sources": {
"type": "build",
"version": "1.0.0-*"
},
"dotnet-test-xunit": "2.2.0-*",
"xunit": "2.2.0-*"
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.1.0-*",
"type": "platform"
}
}
}
},
"testRunner": "xunit"
}

View File

@ -1,40 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.Extensions.ProjectModel.Internal;
using NuGet.Versioning;
namespace Microsoft.Extensions.ProjectModel.Tests
{
public class MsBuildFixture
{
// TODO remove this when preview3 stabilizies
private readonly SemanticVersion _minMsBuildVersion = SemanticVersion.Parse("1.0.0-preview3-003748");
// TODO remove when our CI updates to using MSBuild or when Microsoft/msbuild#4213 is resolved
internal MsBuildContext GetMsBuildContext()
{
// for CI
var sdk = DotNetCoreSdkResolver.DefaultResolver.ResolveLatest();
// for dev work in VS
if (SemanticVersion.Parse(sdk.Version) < _minMsBuildVersion)
{
var home = Environment.GetEnvironmentVariable("USERPROFILE")
?? Environment.GetEnvironmentVariable("HOME");
var dotnetHome = Path.Combine(home, ".dotnet");
var resovler = new DotNetCoreSdkResolver(dotnetHome);
sdk = resovler.ResolveLatest();
}
if (SemanticVersion.Parse(sdk.Version) < _minMsBuildVersion)
{
throw new InvalidOperationException($"Version of .NET Core SDK found in '{sdk.BasePath}' is not new enough for these tests.");
}
return MsBuildContext.FromDotNetSdk(sdk);
}
}
}