Merge pull request #4758 from krwq/i4521

Fix 4521: Add dotnet-add-p2p
This commit is contained in:
Krzysztof Wicher 2016-11-28 13:51:08 -08:00 committed by GitHub
commit f49e29711f
35 changed files with 1589 additions and 4 deletions

View file

@ -0,0 +1,13 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
<!-- intentonally broken -->

View file

@ -0,0 +1,3 @@
public class EmptyItemGroup
{
}

View file

@ -0,0 +1,26 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<!-- Existing but empty item group - do not remove -->
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,4 @@
// Dummy reference - it can be used as an existing reference in any of the projects
public class Lib
{
}

View file

@ -0,0 +1,23 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,3 @@
public class SomeClass
{
}

View file

@ -0,0 +1,21 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,21 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,5 @@
// Dummy reference - it should not be referenced by any other project directly
// it should be used as a reference passed to the dotnet add p2p
public class ValidRef
{
}

View file

@ -0,0 +1,23 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,3 @@
public class WithExistingRefCondOnItem
{
}

View file

@ -0,0 +1,26 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Condition=" '$(TargetFramework)' == 'net451' " Include="..\Lib\Lib.csproj" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,3 @@
public class WithExistingRefCondWhitespaces
{
}

View file

@ -0,0 +1,26 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451'" >
<ProjectReference Include="..\Lib\Lib.csproj" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,3 @@
public class WithRefCondNonUniform
{
}

View file

@ -0,0 +1,27 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">
<SomeItemCausingThisGroupToNotBeUniform Include="foo" />
<ProjectReference Include="..\Lib\Lib.csproj" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,3 @@
public class WithRefNoCondNonUniform
{
}

View file

@ -0,0 +1,27 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<EmbeddedResource Include="**\*.resx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<SomeItemCausingThisGroupToNotBeUniform Include="foo" />
<ProjectReference Include="..\Lib\Lib.csproj" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -12,6 +12,10 @@ namespace Microsoft.DotNet.Cli.Utils
{
}
public GracefulException(string format, params string[] args) : this(string.Format(format, args))
{
}
public GracefulException(string message, Exception innerException) : base(message, innerException)
{
}

View file

@ -27,14 +27,18 @@ namespace Microsoft.DotNet.ProjectJsonMigration
// Different includes
if (item.IntersectIncludes(otherItem).Count() != item.Includes().Count())
{
#if !DISABLE_TRACE
MigrationTrace.Instance.WriteLine($"{nameof(MSBuildExtensions)}.{nameof(IsEquivalentTo)} includes not equivalent.");
#endif
return false;
}
// Different Excludes
if (item.IntersectExcludes(otherItem).Count() != item.Excludes().Count())
{
#if !DISABLE_TRACE
MigrationTrace.Instance.WriteLine($"{nameof(MSBuildExtensions)}.{nameof(IsEquivalentTo)} excludes not equivalent.");
#endif
return false;
}
@ -46,7 +50,9 @@ namespace Microsoft.DotNet.ProjectJsonMigration
// Different remove
if (item.Remove != otherItem.Remove)
{
#if !DISABLE_TRACE
MigrationTrace.Instance.WriteLine($"{nameof(MSBuildExtensions)}.{nameof(IsEquivalentTo)} removes not equivalent.");
#endif
return false;
}
@ -61,13 +67,17 @@ namespace Microsoft.DotNet.ProjectJsonMigration
var otherMetadata = itemToCompare.GetMetadataWithName(metadata.Name);
if (otherMetadata == null)
{
#if !DISABLE_TRACE
MigrationTrace.Instance.WriteLine($"{nameof(MSBuildExtensions)}.{nameof(IsEquivalentTo)} metadata doesn't exist {{ {metadata.Name} {metadata.Value} }}");
#endif
return false;
}
if (!metadata.ValueEquals(otherMetadata))
{
#if !DISABLE_TRACE
MigrationTrace.Instance.WriteLine($"{nameof(MSBuildExtensions)}.{nameof(IsEquivalentTo)} metadata has another value {{ {metadata.Name} {metadata.Value} {otherMetadata.Value} }}");
#endif
return false;
}
}
@ -197,7 +207,9 @@ namespace Microsoft.DotNet.ProjectJsonMigration
if (existingMetadata == default(ProjectMetadataElement))
{
#if !DISABLE_TRACE
MigrationTrace.Instance.WriteLine($"{nameof(AddMetadata)}: Adding metadata to {item.ItemType} item: {{ {metadata.Name}, {metadata.Value} }}");
#endif
item.AddMetadata(metadata.Name, metadata.Value);
}
}

View file

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.DotNet.Tools
{
internal static class LocalizableStrings
{
// Arguments parsing
public const string RequiredArgumentNotPassed = "Required argument {0} was not passed.";
public const string RequiredArgumentIsInvalid = "Required argument {0} is invalid.";
// Project
public const string CouldNotFindProjectOrDirectory = "Could not find project or directory `{0}`.";
public const string CouldNotFindAnyProjectInDirectory = "Could not find any project in `{0}`.";
public const string MoreThanOneProjectInDirectory = "Found more than one project in `{0}`. Please specify which one to use.";
public const string FoundInvalidProject = "Found a project `{0}` but it is invalid.";
public const string ProjectIsInvalid = "Invalid project `{0}`.";
public const string ProjectDoesNotExist = "Project `{0}` does not exist.";
// Project Reference
public const string ProjectAlreadyHasAreference = "Project already has a reference to `{0}`.";
public const string ReferenceAddedToTheProject = "Reference `{0}` added to the project.";
public const string ReferenceDoesNotExist = "Reference `{0}` does not exist.";
public const string SpecifyAtLeastOneReference = "You must specify at least one reference to add.";
}
}

View file

@ -3,12 +3,12 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Configurer;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.DotNet.Tools.Add;
using Microsoft.DotNet.Tools.Build;
using Microsoft.DotNet.Tools.Clean;
using Microsoft.DotNet.Tools.Help;
@ -31,6 +31,7 @@ namespace Microsoft.DotNet.Cli
{
private static Dictionary<string, Func<string[], int>> s_builtIns = new Dictionary<string, Func<string[], int>>
{
["add"] = AddCommand.Run,
["build"] = BuildCommand.Run,
["clean"] = CleanCommand.Run,
["help"] = HelpCommand.Run,

View file

@ -0,0 +1,84 @@
using Microsoft.Build.Construction;
using Microsoft.DotNet.ProjectJsonMigration;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference
{
internal static class MsbuildProjectExtensions
{
public static bool IsConditionalOnFramework(this ProjectElement el, string framework)
{
string conditionStr;
if (!TryGetFrameworkConditionString(framework, out conditionStr))
{
return el.ConditionChain().Count == 0;
}
var condChain = el.ConditionChain();
return condChain.Count == 1 && condChain.First().Trim() == conditionStr;
}
public static ProjectItemGroupElement LastItemGroup(this ProjectRootElement root)
{
return root.ItemGroupsReversed.FirstOrDefault();
}
public static ProjectItemGroupElement FindUniformOrCreateItemGroupWithCondition(this ProjectRootElement root, string projectItemElementType, string framework)
{
var lastMatchingItemGroup = FindExistingUniformItemGroupWithCondition(root, projectItemElementType, framework);
if (lastMatchingItemGroup != null)
{
return lastMatchingItemGroup;
}
ProjectItemGroupElement ret = root.CreateItemGroupElement();
string condStr;
if (TryGetFrameworkConditionString(framework, out condStr))
{
ret.Condition = condStr;
}
root.InsertAfterChild(ret, root.LastItemGroup());
return ret;
}
public static ProjectItemGroupElement FindExistingUniformItemGroupWithCondition(this ProjectRootElement root, string projectItemElementType, string framework)
{
return root.ItemGroupsReversed.FirstOrDefault((itemGroup) => itemGroup.IsConditionalOnFramework(framework) && itemGroup.IsUniformItemElementType(projectItemElementType));
}
public static bool IsUniformItemElementType(this ProjectItemGroupElement group, string projectItemElementType)
{
return group.Items.All((it) => it.ItemType == projectItemElementType);
}
public static IEnumerable<ProjectItemElement> FindExistingItemsWithCondition(this ProjectRootElement root, string framework, string include)
{
return root.Items.Where((el) => el.IsConditionalOnFramework(framework) && el.HasInclude(include));
}
public static bool HasExistingItemWithCondition(this ProjectRootElement root, string framework, string include)
{
return root.FindExistingItemsWithCondition(framework, include).Count() != 0;
}
public static bool HasInclude(this ProjectItemElement el, string include)
{
return el.Includes().Contains(include);
}
private static bool TryGetFrameworkConditionString(string framework, out string condition)
{
if (string.IsNullOrEmpty(framework))
{
condition = null;
return false;
}
condition = $"'$(TargetFramework)' == '{framework}'";
return true;
}
}
}

View file

@ -0,0 +1,235 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using System;
using System.IO;
using System.Linq;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Tools.Common;
namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference
{
public class AddProjectToProjectReferenceCommand
{
public static int Run(string[] args)
{
DebugHelper.HandleDebugSwitch(ref args);
CommandLineApplication app = new CommandLineApplication(throwOnUnexpectedArg: false)
{
Name = "dotnet add p2p",
FullName = ".NET Add Project to Project (p2p) reference Command",
Description = "Command to add project to project (p2p) reference",
AllowArgumentSeparator = true,
ArgumentSeparatorHelpText = "Project to project references to add"
};
app.HelpOption("-h|--help");
CommandArgument projectArgument = app.Argument(
"<PROJECT>",
"The project file to modify. If a project file is not specified," +
" it searches the current working directory for an MSBuild file that has" +
" a file extension that ends in `proj` and uses that file.");
CommandOption frameworkOption = app.Option(
"-f|--framework <FRAMEWORK>",
"Add reference only when targetting a specific framework",
CommandOptionType.SingleValue);
CommandOption forceOption = app.Option(
"--force",
"Add reference even if it does not exist, do not convert paths to relative",
CommandOptionType.NoValue);
app.OnExecute(() => {
if (string.IsNullOrEmpty(projectArgument.Value))
{
throw new GracefulException(LocalizableStrings.RequiredArgumentNotPassed, "<Project>");
}
ProjectRootElement project;
string projectDir;
if (File.Exists(projectArgument.Value))
{
project = GetProjectFromFileOrThrow(projectArgument.Value);
projectDir = new FileInfo(projectArgument.Value).DirectoryName;
}
else
{
project = GetProjectFromDirectoryOrThrow(projectArgument.Value);
projectDir = projectArgument.Value;
}
projectDir = PathUtility.EnsureTrailingSlash(projectDir);
if (app.RemainingArguments.Count == 0)
{
throw new GracefulException(LocalizableStrings.SpecifyAtLeastOneReference);
}
List<string> references = app.RemainingArguments;
if (!forceOption.HasValue())
{
EnsureAllReferencesExist(references);
ConvertPathsToRelative(projectDir, ref references);
}
int numberOfAddedReferences = AddProjectToProjectReference(
project,
frameworkOption.Value(),
references);
if (numberOfAddedReferences != 0)
{
project.Save();
}
return 0;
});
try
{
return app.Execute(args);
}
catch (GracefulException e)
{
Reporter.Error.WriteLine(e.Message.Red());
app.ShowHelp();
return 1;
}
}
internal static void EnsureAllReferencesExist(List<string> references)
{
var notExisting = new List<string>();
foreach (var r in references)
{
if (!File.Exists(r))
{
notExisting.Add(r);
}
}
if (notExisting.Count > 0)
{
throw new GracefulException(
string.Join(
Environment.NewLine,
notExisting.Select((r) => string.Format(LocalizableStrings.ReferenceDoesNotExist, r))));
}
}
internal static void ConvertPathsToRelative(string root, ref List<string> references)
{
root = PathUtility.EnsureTrailingSlash(Path.GetFullPath(root));
references = references.Select((r) => PathUtility.GetRelativePath(root, Path.GetFullPath(r))).ToList();
}
// There is ProjectRootElement.TryOpen but it does not work as expected
// I.e. it returns null for some valid projects
internal static ProjectRootElement TryOpenProject(string filename)
{
try
{
return ProjectRootElement.Open(filename, new ProjectCollection(), preserveFormatting: true);
}
catch (Microsoft.Build.Exceptions.InvalidProjectFileException)
{
return null;
}
}
internal static ProjectRootElement GetProjectFromFileOrThrow(string filename)
{
if (!File.Exists(filename))
{
throw new GracefulException(LocalizableStrings.ProjectDoesNotExist, filename);
}
var project = TryOpenProject(filename);
if (project == null)
{
throw new GracefulException(LocalizableStrings.ProjectIsInvalid, filename);
}
return project;
}
internal static ProjectRootElement GetProjectFromDirectoryOrThrow(string directory)
{
DirectoryInfo dir;
try
{
dir = new DirectoryInfo(directory);
}
catch (ArgumentException)
{
throw new GracefulException(LocalizableStrings.CouldNotFindProjectOrDirectory, directory);
}
if (!dir.Exists)
{
throw new GracefulException(LocalizableStrings.CouldNotFindProjectOrDirectory, directory);
}
FileInfo[] files = dir.GetFiles("*proj");
if (files.Length == 0)
{
throw new GracefulException(LocalizableStrings.CouldNotFindAnyProjectInDirectory, directory);
}
if (files.Length > 1)
{
throw new GracefulException(LocalizableStrings.MoreThanOneProjectInDirectory, directory);
}
FileInfo projectFile = files.First();
if (!projectFile.Exists)
{
throw new GracefulException(LocalizableStrings.CouldNotFindAnyProjectInDirectory, directory);
}
var ret = TryOpenProject(projectFile.FullName);
if (ret == null)
{
throw new GracefulException(LocalizableStrings.FoundInvalidProject, projectFile.FullName);
}
return ret;
}
private static string NormalizeSlashesForMsbuild(string path)
{
return path.Replace('/', '\\');
}
internal static int AddProjectToProjectReference(ProjectRootElement root, string framework, IEnumerable<string> refs)
{
int numberOfAddedReferences = 0;
const string ProjectItemElementType = "ProjectReference";
ProjectItemGroupElement itemGroup = root.FindUniformOrCreateItemGroupWithCondition(ProjectItemElementType, framework);
foreach (var @ref in refs.Select((r) => NormalizeSlashesForMsbuild(r)))
{
if (root.HasExistingItemWithCondition(framework, @ref))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.ProjectAlreadyHasAreference, @ref));
continue;
}
numberOfAddedReferences++;
itemGroup.AppendChild(root.CreateItemElement(ProjectItemElementType, @ref));
Reporter.Output.WriteLine(string.Format(LocalizableStrings.ReferenceAddedToTheProject, @ref));
}
return numberOfAddedReferences;
}
}
}

View file

@ -0,0 +1,100 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using System;
using System.IO;
using System.Linq;
using Microsoft.Build.Construction;
using Microsoft.DotNet.ProjectJsonMigration;
using NuGet.Frameworks;
using Microsoft.DotNet.Tools.Add.ProjectToProjectReference;
namespace Microsoft.DotNet.Tools.Add
{
public class AddCommand
{
public const string HelpText = @".NET Add Command
Usage: dotnet add [options] <object> <command> [[--] <arg>...]]
Options:
-h|--help Show help information
Arguments:
<object> The object of the operation. If a project file is not specified, it defaults to the current directory.
<command> Command to be executed on <object>.
Args:
Any extra arguments passed to the command. Use `dotnet add <command> --help` to get help about these arguments.
Commands:
p2p Add project to project (p2p) reference to a project";
private static Dictionary<string, Func<string[], int>> s_builtIns = new Dictionary<string, Func<string[], int>>
{
["p2p"] = AddProjectToProjectReferenceCommand.Run,
};
public static int Run(string[] args)
{
DebugHelper.HandleDebugSwitch(ref args);
if (args.Length == 0 || args[0] == "--help" || args[0] == "-h")
{
Reporter.Output.WriteLine(HelpText);
return 0;
}
string commandObject;
string command;
if (IsValidCommandName(args[0]))
{
command = args[0];
commandObject = GetCurrentDirectoryWithDirSeparator();
args = args.Skip(1).Prepend(commandObject).ToArray();
}
else if (args.Length == 1)
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RequiredArgumentNotPassed, "<command>").Red());
Reporter.Output.WriteLine(HelpText);
return 1;
}
else
{
commandObject = args[0];
command = args[1];
args = args.Skip(2).Prepend(commandObject).ToArray();
}
Func<string[], int> builtin;
if (s_builtIns.TryGetValue(command, out builtin))
{
return builtin(args);
}
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RequiredArgumentIsInvalid, "<command>").Red());
Reporter.Output.WriteLine(HelpText);
return 1;
}
private static bool IsValidCommandName(string s)
{
return s_builtIns.ContainsKey(s);
}
private static string GetCurrentDirectoryWithDirSeparator()
{
string ret = Directory.GetCurrentDirectory();
if (ret[ret.Length - 1] != Path.DirectorySeparatorChar)
{
ret += Path.DirectorySeparatorChar;
}
return ret;
}
}
}

View file

@ -35,6 +35,9 @@ Commands:
pack Creates a NuGet package
migrate Migrates a project.json based project to a msbuild based project
Project modification commands:
add Add items to the project
Advanced Commands:
nuget Provides additional NuGet commands
msbuild msbuilds a project and all of its dependencies

View file

@ -1,6 +1,6 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<VersionPrefix>1.0.0-preview4</VersionPrefix>
<TargetFramework>netcoreapp1.0</TargetFramework>
@ -9,7 +9,7 @@
<AssemblyOriginatorKeyFile>../../tools/Key.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">$(PackageTargetFallback);dotnet5.4</PackageTargetFallback>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">$(PackageTargetFallback);dotnet5.4</PackageTargetFallback>
</PropertyGroup>
<ItemGroup>
@ -87,6 +87,6 @@
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DefineConstants>$(DefineConstants);RELEASE</DefineConstants>
</PropertyGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,29 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Tools.Test.Utilities
{
public sealed class AddP2PCommand : TestCommand
{
private string _projectName = null;
public AddP2PCommand()
: base("dotnet")
{
}
public override CommandResult Execute(string args = "")
{
args = $"add {_projectName} p2p {args}";
return base.ExecuteWithCapturedOutput(args);
}
public AddP2PCommand WithProject(string projectName)
{
_projectName = projectName;
return this;
}
}
}

View file

@ -0,0 +1,629 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.Build.Construction;
using Microsoft.DotNet.Tools.Test.Utilities;
using System;
using System.IO;
using Xunit;
namespace Microsoft.DotNet.Cli.Add.P2P.Tests
{
public class GivenDotnetAddP2P : TestBase
{
const string FrameworkNet451Arg = "-f net451";
const string ConditionFrameworkNet451 = "== 'net451'";
const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0";
const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'";
private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "")
{
return new TestSetup(
TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName)
.CreateInstance(callingMethod: callingMethod, identifier: identifier)
.WithSourceFiles()
.Root
.FullName);
}
private ProjDir NewDir([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
return new ProjDir(TestAssetsManager.CreateTestDirectory(callingMethod: callingMethod, identifier: identifier).Path);
}
private ProjDir NewLib([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var dir = NewDir(callingMethod: callingMethod, identifier: identifier);
try
{
new NewCommand()
.WithWorkingDirectory(dir.Path)
.ExecuteWithCapturedOutput("-t Lib")
.Should().Pass();
}
catch (System.ComponentModel.Win32Exception e)
{
throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{dir.Path}`\nException:\n{e}");
}
return dir;
}
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new AddP2PCommand().Execute(helpArg);
cmd.Should().Pass();
cmd.StdOut.Should().Contain("Usage");
}
[Theory]
[InlineData("idontexist.csproj")]
[InlineData("ihave?inv@lid/char\\acters")]
public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName)
{
var setup = Setup();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Contain("Could not find");
cmd.StdOut.Should().Contain("Usage");
}
[Fact]
public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage()
{
string projName = "Broken/Broken.csproj";
var setup = Setup();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Contain("Invalid project");
cmd.StdOut.Should().Contain("Usage");
}
[Fact]
public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(Path.Combine(setup.TestRoot, "MoreThanOne"))
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Contain("more than one");
cmd.StdOut.Should().Contain("Usage");
}
[Fact]
public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Contain("not find any");
cmd.StdOut.Should().Contain("Usage");
}
[Fact]
public void ItAddsRefWithoutCondAndPrintsStatus()
{
var lib = NewLib();
var setup = Setup();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void ItAddsRefWithCondAndPrintsStatus()
{
var lib = NewLib();
var setup = Setup();
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithoutCondIsPresentItAddsDifferentRefWithoutCond()
{
var lib = NewLib();
var setup = Setup();
new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.LibCsprojPath}\"")
.Should().Pass();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithCondIsPresentItAddsDifferentRefWithCond()
{
var lib = NewLib();
var setup = Setup();
new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\"")
.Should().Pass();
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithCondIsPresentItAddsRefWithDifferentCond()
{
var lib = NewLib();
var setup = Setup();
new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNetCoreApp10Arg} \"{setup.ValidRefCsprojPath}\"")
.Should().Pass();
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithConditionIsPresentItAddsDifferentRefWithoutCond()
{
var lib = NewLib();
var setup = Setup();
new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\"")
.Should().Pass();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithNoCondAlreadyExistsItDoesntDuplicate()
{
var lib = NewLib();
var setup = Setup();
new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"")
.Should().Pass();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("already has a reference");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithCondOnItemAlreadyExistsItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithExistingRefCondOnItem"));
string contentBefore = proj.CsProjContent();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("already has a reference");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithCondOnItemGroupAlreadyExistsItDoesntDuplicate()
{
var lib = NewLib();
var setup = Setup();
new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"")
.Should().Pass();
var csprojContentBefore = lib.CsProjContent();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("already has a reference");
lib.CsProjContent().Should().BeEquivalentTo(csprojContentBefore);
}
[Fact]
public void WhenRefWithCondWithWhitespaceOnItemGroupExistsItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithExistingRefCondWhitespaces"));
string contentBefore = proj.CsProjContent();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjName)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("already has a reference");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithoutCondAlreadyExistsInNonUniformItemGroupItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefNoCondNonUniform"));
string contentBefore = proj.CsProjContent();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjName)
.Execute($"\"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("already has a reference");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithoutCondAlreadyExistsInNonUniformItemGroupItAddsDifferentRefInDifferentGroup()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefNoCondNonUniform"));
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithCondAlreadyExistsInNonUniformItemGroupItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefCondNonUniform"));
string contentBefore = proj.CsProjContent();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjName)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("already has a reference");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithCondAlreadyExistsInNonUniformItemGroupItAddsDifferentRefInDifferentGroup()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefCondNonUniform"));
int condBefore = proj.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenEmptyItemGroupPresentItAddsRefInIt()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "EmptyItemGroup"));
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void ItAddsMultipleRefsNoCondToTheSameItemGroup()
{
var lib = NewLib();
var setup = Setup();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.LibCsprojPath}\" \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project").And.NotContain("already has a reference");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.LibCsprojName).Should().Be(1);
}
[Fact]
public void ItAddsMultipleRefsWithCondToTheSameItemGroup()
{
var lib = NewLib();
var setup = Setup();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\" \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project").And.NotContain("already has a reference");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.LibCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenProjectNameIsNotPassedItFindsItAndAddsReference()
{
var lib = NewLib();
var setup = Setup();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(lib.Path)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void ItAddsRefBetweenImports()
{
var lib = NewLib();
var setup = Setup();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
int state = 0;
foreach (var el in lib.CsProj().AllChildren)
{
var import = el as ProjectImportElement;
var projRef = el as ProjectItemElement;
switch (state)
{
case 0:
if (import != null && import.Project.EndsWith(".props"))
{
state++;
}
break;
case 1:
if (projRef != null && projRef.ItemType == "ProjectReference" && projRef.Include.Contains(setup.ValidRefCsprojName))
{
state++;
}
break;
case 2:
if (import != null && import.Project.EndsWith(".targets"))
{
state++;
}
break;
}
}
state.Should().Be(3);
}
[Fact]
public void WhenPassedReferenceDoesNotExistItShowsAnError()
{
var lib = NewLib();
var contentBefore = lib.CsProjContent();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute("\"IDoNotExist.csproj\"");
cmd.Should().Fail();
cmd.StdErr.Should().Contain("does not exist");
lib.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenPassedMultipleRefsAndOneOfthemDoesNotExistItCancelsWholeOperation()
{
var lib = NewLib();
var setup = Setup();
var contentBefore = lib.CsProjContent();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\" \"IDoNotExist.csproj\"");
cmd.Should().Fail();
cmd.StdErr.Should().Contain("does not exist");
cmd.StdErr.Should().NotMatchRegex("(.*does not exist.*){2,}");
lib.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenPassedReferenceDoesNotExistAndForceSwitchIsPassedItAddsIt()
{
var lib = NewLib();
const string nonExisting = "IDoNotExist.csproj";
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"--force \"{nonExisting}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(nonExisting).Should().Be(1);
}
[Fact]
public void WhenPassedReferenceIsUsingSlashesItNormalizesItToBackslashes()
{
var lib = NewLib();
var setup = Setup();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"--force \"{setup.ValidRefCsprojPath.Replace('\\', '/')}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojPath.Replace('/', '\\')).Should().Be(1);
}
[Fact]
public void WhenReferenceIsRelativeAndProjectIsNotInCurrentDirectoryReferencePathIsFixed()
{
var setup = Setup();
var proj = new ProjDir(setup.LibDir);
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(setup.LibCsprojPath)
.Execute($"\"{setup.ValidRefCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojRelToOtherProjPath.Replace('/', '\\')).Should().Be(1);
}
[Fact]
public void WhenReferenceIsRelativeAndProjectIsNotInCurrentDirectoryAndForceSwitchIsPassedItDoesNotChangeIt()
{
var setup = Setup();
var proj = new ProjDir(setup.LibDir);
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddP2PCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(setup.LibCsprojPath)
.Execute($"--force \"{setup.ValidRefCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Contain("added to the project");
cmd.StdErr.Should().BeEmpty();
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojRelPath.Replace('/', '\\')).Should().Be(1);
}
}
}

View file

@ -0,0 +1 @@
https://github.com/Microsoft/msbuild/issues/927

View file

@ -0,0 +1 @@
https://github.com/Microsoft/msbuild/issues/927

View file

@ -0,0 +1,34 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
namespace Microsoft.DotNet.Cli.Add.P2P.Tests
{
internal class ProjDir
{
public ProjDir(string path)
{
Path = path;
Name = new DirectoryInfo(Path).Name;
}
public string Path { get; private set; }
public string Name { get; private set; }
public string CsProjName => $"{Name}.csproj";
public string CsProjPath => System.IO.Path.Combine(Path, CsProjName);
public string CsProjContent()
{
return File.ReadAllText(CsProjPath);
}
public ProjectRootElement CsProj()
{
// Passing new collection to prevent using cached version
return ProjectRootElement.Open(CsProjPath, new ProjectCollection());
}
}
}

View file

@ -0,0 +1,70 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Construction;
using Microsoft.DotNet.ProjectJsonMigration;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.DotNet.Cli.Add.P2P.Tests
{
internal static class ProjectRootElementExtensions
{
public static int NumberOfItemGroupsWithConditionContaining(
this ProjectRootElement root,
string patternInCondition)
{
return root.ItemGroups.Count((itemGroup) => itemGroup.Condition.Contains(patternInCondition));
}
public static int NumberOfItemGroupsWithoutCondition(this ProjectRootElement root)
{
return root.ItemGroups.Count((ig) => string.IsNullOrEmpty(ig.Condition));
}
public static IEnumerable<ProjectElement> ItemsWithIncludeAndConditionContaining(
this ProjectRootElement root,
string itemType,
string includePattern,
string patternInCondition)
{
return root.Items.Where((it) =>
{
if (it.ItemType != itemType || !it.Include.Contains(includePattern))
{
return false;
}
var condChain = it.ConditionChain();
return condChain.Count == 1 && condChain.First().Contains(patternInCondition);
});
}
public static int NumberOfProjectReferencesWithIncludeAndConditionContaining(
this ProjectRootElement root,
string includePattern,
string patternInCondition)
{
return root.ItemsWithIncludeAndConditionContaining(
"ProjectReference",
includePattern,
patternInCondition)
.Count();
}
public static IEnumerable<ProjectElement> ItemsWithIncludeContaining(
this ProjectRootElement root,
string itemType,
string includePattern)
{
return root.Items.Where((it) => it.ItemType == itemType && it.Include.Contains(includePattern));
}
public static int NumberOfProjectReferencesWithIncludeContaining(
this ProjectRootElement root,
string includePattern)
{
return root.ItemsWithIncludeContaining("ProjectReference", includePattern).Count();
}
}
}

View file

@ -0,0 +1,32 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
namespace Microsoft.DotNet.Cli.Add.P2P.Tests
{
internal class TestSetup
{
public const string TestGroup = "NonRestoredTestProjects";
public const string ProjectName = "DotnetAddP2PProjects";
public string TestRoot { get; private set; }
private const string ValidRef = "ValidRef";
public string ValidRefCsprojName => $"{ValidRef}.csproj";
public string ValidRefCsprojRelPath => Path.Combine(ValidRef, ValidRefCsprojName);
public string ValidRefCsprojPath => Path.Combine(TestRoot, ValidRefCsprojRelPath);
public string ValidRefCsprojRelToOtherProjPath => Path.Combine("..", ValidRefCsprojRelPath);
private const string Lib = "Lib";
public string LibDir => Path.Combine(TestRoot, Lib);
public string LibCsprojName => $"{Lib}.csproj";
public string LibCsprojPath => Path.Combine(TestRoot, Lib, LibCsprojName);
public string LibCsprojRelPath => Path.Combine("..", Lib, LibCsprojName);
public TestSetup(string testRoot)
{
TestRoot = testRoot;
}
}
}

View file

@ -0,0 +1,63 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />
<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<AssemblyName>dotnet-add-p2p.Tests</AssemblyName>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">$(PackageTargetFallback);dotnet5.4;portable-net451+win8</PackageTargetFallback>
<DefineConstants>$(DefineConstants);DISABLE_TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<Compile Include="..\..\src\Microsoft.DotNet.ProjectJsonMigration\MSBuildExtensions.cs">
<Link>src\Microsoft.DotNet.ProjectJsonMigration\MSBuildExtensions.cs</Link>
</Compile>
<EmbeddedResource Include="**\*.resx" />
<EmbeddedResource Include="compiler\resources\**\*" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Microsoft.DotNet.Tools.Tests.Utilities\Microsoft.DotNet.Tools.Tests.Utilities.csproj" />
<ProjectReference Include="..\..\src\Microsoft.DotNet.TestFramework\Microsoft.DotNet.TestFramework.csproj">
<FromP2P>true</FromP2P>
</ProjectReference>
<ProjectReference Include="..\..\src\Microsoft.DotNet.Cli.Utils\Microsoft.DotNet.Cli.Utils.csproj">
<FromP2P>true</FromP2P>
</ProjectReference>
<ProjectReference Include="..\..\src\Microsoft.DotNet.InternalAbstractions\Microsoft.DotNet.InternalAbstractions.csproj">
<FromP2P>true</FromP2P>
</ProjectReference>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net46' ">
<Reference Include="System.Runtime">
<FromP2P>true</FromP2P>
</Reference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk">
<Version>1.0.0-alpha-20161104-2</Version>
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk">
<Version>15.0.0-preview-20161024-02</Version>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio">
<Version>2.2.0-beta4-build1194</Version>
</PackageReference>
<PackageReference Include="Microsoft.NETCore.App">
<Version>1.0.1</Version>
</PackageReference>
<PackageReference Include="System.Runtime.Serialization.Primitives">
<Version>4.1.1</Version>
</PackageReference>
<PackageReference Include="xunit">
<Version>2.2.0-beta4-build3444</Version>
</PackageReference>
<PackageReference Include="Microsoft.Build">
<Version>15.1.0-preview-000370-00</Version>
</PackageReference>
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DefineConstants>$(DefineConstants);RELEASE</DefineConstants>
</PropertyGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>