Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/Cli/dotnet/CommonLocalizableStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -671,4 +671,19 @@ setx PATH "%PATH%;{0}"
<data name="CommandInteractiveOptionDescription" xml:space="preserve">
<value>Allows the command to stop and wait for user input or action (for example to complete authentication).</value>
</data>
</root>
<data name="CouldNotFindFile" xml:space="preserve">
<value>Could not find flie `{0}`.</value>
</data>
<data name="FileAddedToTheProject" xml:space="preserve">
<value>File `{0}` added to the project.</value>
</data>
<data name="ProjectAlreadyHasAfile" xml:space="preserve">
<value>Project already has a file `{0}`.</value>
</data>
<data name="FileRemoved" xml:space="preserve">
<value>File `{0}` removed.</value>
</data>
<data name="FileReferenceCouldNotBeFound" xml:space="preserve">
<value>File reference `{0}` could not be found.</value>
</data>
</root>
69 changes: 69 additions & 0 deletions src/Cli/dotnet/MsbuildProject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ namespace Microsoft.DotNet.Tools
internal class MsbuildProject
{
const string ProjectItemElementType = "ProjectReference";
const string CompileElementType = "Compile";

public ProjectRootElement ProjectRootElement { get; private set; }
public string ProjectDirectory { get; private set; }
Expand Down Expand Up @@ -150,6 +151,45 @@ public int RemoveProjectToProjectReferences(string framework, IEnumerable<string
return totalNumberOfRemovedReferences;
}

public int AddFileReferences(string framework, IEnumerable<string> refs)
{
int numberOfAddedFiles = 0;

ProjectItemGroupElement itemGroup = ProjectRootElement.FindUniformOrCreateItemGroupWithCondition(
CompileElementType,
framework);
foreach (var @ref in refs.Select((r) => PathUtility.GetPathWithBackSlashes(r)))
{
if (ProjectRootElement.HasExistingItemWithCondition(framework, @ref))
{
Reporter.Output.WriteLine(string.Format(
CommonLocalizableStrings.ProjectAlreadyHasAreference,
@ref));
continue;
}

numberOfAddedFiles++;
itemGroup.AppendChild(ProjectRootElement.CreateItemElement(CompileElementType, @ref));

Reporter.Output.WriteLine(string.Format(CommonLocalizableStrings.FileAddedToTheProject, @ref));
}

return numberOfAddedFiles;
}

public int RemoveFileReferences(string framework, IEnumerable<string> refs)
{
int totalNumberOfRemovedFiles = 0;

foreach (var @ref in refs)
{
totalNumberOfRemovedFiles += RemoveFileReferenceAlternatives(framework, @ref);
}

return totalNumberOfRemovedFiles;
}


public IEnumerable<ProjectItemElement> GetProjectToProjectReferences()
{
return ProjectRootElement.GetAllItemsWithElementType(ProjectItemElementType);
Expand Down Expand Up @@ -270,6 +310,35 @@ private int RemoveProjectToProjectReferenceAlternatives(string framework, string
return numberOfRemovedRefs;
}

private int RemoveFileReferenceAlternatives(string framework, string file)
{
int numberOfRemovedFiles = 0;
foreach (var r in GetIncludeAlternativesForRemoval(file))
{
foreach (var existingItem in ProjectRootElement.FindExistingItemsWithCondition(framework, r))
{
ProjectElementContainer itemGroup = existingItem.Parent;
itemGroup.RemoveChild(existingItem);
if (itemGroup.Children.Count == 0)
{
itemGroup.Parent.RemoveChild(itemGroup);
}

numberOfRemovedFiles++;
Reporter.Output.WriteLine(string.Format(CommonLocalizableStrings.FileRemoved, r));
}
}

if (numberOfRemovedFiles == 0)
{
Reporter.Output.WriteLine(string.Format(
CommonLocalizableStrings.FileReferenceCouldNotBeFound,
file));
}

return numberOfRemovedFiles;
}

// Easiest way to explain rationale for this function is on the example. Let's consider following directory structure:
// .../a/b/p.proj <project>
// .../a/d/ref.proj <reference>
Expand Down
3 changes: 2 additions & 1 deletion src/Cli/dotnet/commands/dotnet-add/AddCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public static Command Add() =>
description: CommonLocalizableStrings.ProjectArgumentDescription),
AddPackageParser.AddPackage(),
AddProjectToProjectReferenceParser.AddProjectReference(),
AddFileParser.AddFile(),
CommonOptions.HelpOption());
}
}
}
9 changes: 8 additions & 1 deletion src/Cli/dotnet/commands/dotnet-add/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Add.FileReference;
using Microsoft.DotNet.Tools.Add.PackageReference;
using Microsoft.DotNet.Tools.Add.ProjectToProjectReference;

Expand All @@ -32,6 +33,12 @@ public class AddCommand : DotNetTopLevelCommandBase
add => new AddPackageReferenceCommand(
add["package"],
add.Value<string>(),
ParseResult),

["file"] =
add => new AddFileReferenceCommand(
add["file"],
add.Value<string>(),
ParseResult)
};

Expand All @@ -41,4 +48,4 @@ public static int Run(string[] args)
return command.RunCommand(args);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// 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.CommandLine;
using LocalizableStrings = Microsoft.DotNet.Tools.Add.FileReference.LocalizableStrings;

namespace Microsoft.DotNet.Cli
{
internal static class AddFileParser
{
public static Command AddFile()
{
return Create.Command(
"file",
LocalizableStrings.AppFullName,
Accept.OneOrMoreArguments()
.With(name: LocalizableStrings.FilePathArgumentName,
description: LocalizableStrings.FilePathArgumentDescription),
CommonOptions.HelpOption(),
Create.Option("-f|--framework", LocalizableStrings.CmdFrameworkDescription,
Accept.ExactlyOneArgument()
.WithSuggestionsFrom(_ => Suggest.TargetFrameworksFromProjectFile())
.With(name: Tools.Add.PackageReference.LocalizableStrings.CmdFramework)),
CommonOptions.InteractiveOption());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema

Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AppDescription" xml:space="preserve">
<value>Command to add file</value>
</data>
<data name="AppFullName" xml:space="preserve">
<value>Add a file to the project.</value>
</data>
<data name="CmdFrameworkDescription" xml:space="preserve">
<value>Add the reference only when targeting a specific framework.</value>
</data>
<data name="FilePathArgumentDescription" xml:space="preserve">
<value>The files to add.</value>
</data>
<data name="FilePathArgumentName" xml:space="preserve">
<value>FILE</value>
</data>
</root>
84 changes: 84 additions & 0 deletions src/Cli/dotnet/commands/dotnet-add/dotnet-add-file/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// 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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using NuGet.Frameworks;

namespace Microsoft.DotNet.Tools.Add.FileReference
{
internal class AddFileReferenceCommand : CommandBase
{
private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;

public AddFileReferenceCommand(
AppliedOption appliedCommand,
string fileOrDirectory,
ParseResult parseResult) : base(parseResult)
{
if (appliedCommand == null)
{
throw new ArgumentNullException(nameof(appliedCommand));
}
if (fileOrDirectory == null)
{
throw new ArgumentNullException(nameof(fileOrDirectory));
}

_appliedCommand = appliedCommand;
_fileOrDirectory = fileOrDirectory;
}

public override int Execute()
{
var projects = new ProjectCollection();
bool interactive = CommonOptionResult.GetInteractive(_appliedCommand);
MsbuildProject msbuildProj = MsbuildProject.FromFileOrDirectory(
projects,
_fileOrDirectory,
interactive);

var frameworkString = _appliedCommand.ValueOrDefault<string>("framework");
var refs = _appliedCommand.Arguments;

if (frameworkString != null)
{
var framework = NuGetFramework.Parse(frameworkString);
if (!msbuildProj.IsTargetingFramework(framework)) {
Reporter.Error.WriteLine(string.Format(
CommonLocalizableStrings.ProjectDoesNotTargetFramework,
msbuildProj.ProjectRootElement.FullPath,
frameworkString));
return 1;
}
}

PathUtility.EnsureAllPathsExist(refs, CommonLocalizableStrings.CouldNotFindProjectOrDirectory, true);

var relativePathReferences = refs.Select((r) =>
Path.GetRelativePath(
msbuildProj.ProjectDirectory,
System.IO.Path.GetFullPath(r))).ToList();

int numberOfAddedReferences = msbuildProj.AddFileReferences(
frameworkString,
relativePathReferences);

if (numberOfAddedReferences != 0)
{
msbuildProj.ProjectRootElement.Save();
}

return 0;
}
}
}
Loading