Correct metadata additions and add errors about metadata

- related to #8419 and (more generally) #7947
- add errors for missing required metadata
- add errors for duplicate `%(DocumentPath)` and `%(OutputPath)` metadata
- remove `[Required]` for task inputs that may be `null` or empty
- correct `%(DocumentPath)`s generated in `GetProjectReferenceMetadata` task
  - use this task
This commit is contained in:
Doug Bunting 2018-09-19 10:10:19 -07:00
parent 87e304334d
commit fb9393febf
No known key found for this signature in database
GPG Key ID: 888B4EB7822B32E9
6 changed files with 331 additions and 30 deletions

View File

@ -10,7 +10,8 @@ using Microsoft.Build.Utilities;
namespace Microsoft.Extensions.ApiDescription.Client
{
/// <summary>
/// Adds or corrects Namespace and OutputPath metadata in ServiceFileReference items.
/// Adds or corrects ClassName, Namespace and OutputPath metadata in ServiceFileReference items. Also stores final
/// metadata as SerializedMetadata.
/// </summary>
public class GetFileReferenceMetadata : Task
{
@ -23,7 +24,6 @@ namespace Microsoft.Extensions.ApiDescription.Client
/// <summary>
/// Default directory for OutputPath values.
/// </summary>
[Required]
public string OutputDirectory { get; set; }
/// <summary>
@ -49,14 +49,47 @@ namespace Microsoft.Extensions.ApiDescription.Client
public override bool Execute()
{
var outputs = new List<ITaskItem>(Inputs.Length);
var destinations = new HashSet<string>();
foreach (var item in Inputs)
{
var newItem = new TaskItem(item);
outputs.Add(newItem);
var codeGenerator = item.GetMetadata("CodeGenerator");
var isTypeScript = codeGenerator.EndsWith("TypeScript", StringComparison.OrdinalIgnoreCase);
if (string.IsNullOrEmpty("CodeGenerator"))
{
// This case occurs when user forgets to specify the required metadata. We have no default here.
string type;
if (!string.IsNullOrEmpty(item.GetMetadata("SourceProject")))
{
type = "ServiceProjectReference";
}
else if (!string.IsNullOrEmpty(item.GetMetadata("SourceUri")))
{
type = "ServiceUriReference";
}
else
{
type = "ServiceFileReference";
}
Log.LogError(Resources.FormatInvalidEmptyMetadataValue("CodeGenerator", type, item.ItemSpec));
}
var className = item.GetMetadata("ClassName");
if (string.IsNullOrEmpty(className))
{
var filename = item.GetMetadata("Filename");
className = $"{filename}Client";
if (char.IsLower(className[0]))
{
className = char.ToUpper(className[0]) + className.Substring(startIndex: 1);
}
MetadataSerializer.SetMetadata(newItem, "ClassName", className);
}
var isTypeScript = codeGenerator.EndsWith("TypeScript", StringComparison.OrdinalIgnoreCase);
var @namespace = item.GetMetadata("Namespace");
if (string.IsNullOrEmpty(@namespace))
{
@ -67,20 +100,26 @@ namespace Microsoft.Extensions.ApiDescription.Client
var outputPath = item.GetMetadata("OutputPath");
if (string.IsNullOrEmpty(outputPath))
{
var className = item.GetMetadata("ClassName");
outputPath = $"{className}{(isTypeScript ? ".ts" : ".cs")}";
}
outputPath = GetFullPath(outputPath);
MetadataSerializer.SetMetadata(newItem, "OutputPath", outputPath);
if (!destinations.Add(outputPath))
{
// This case may occur when user is experimenting e.g. with multiple code generators or options.
// May also occur when user accidentally duplicates OutputPath metadata.
Log.LogError(Resources.FormatDuplicateFileOutputPaths(outputPath));
}
// Add metadata which may be used as a property and passed to an inner build.
newItem.SetMetadata("SerializedMetadata", MetadataSerializer.SerializeMetadata(newItem));
}
Outputs = outputs.ToArray();
return true;
return !Log.HasLoggedErrors;
}
private string GetFullPath(string path)

View File

@ -1,7 +1,6 @@
// 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.Framework;
@ -10,14 +9,14 @@ using Microsoft.Build.Utilities;
namespace Microsoft.Extensions.ApiDescription.Client
{
/// <summary>
/// Adds or corrects DocumentPath and project-related metadata in ServiceProjectReference items.
/// Adds or corrects DocumentPath and project-related metadata in ServiceProjectReference items. Also stores final
/// metadata as SerializedMetadata.
/// </summary>
public class GetProjectReferenceMetadata : Task
{
/// <summary>
/// Default directory for DocumentPath values.
/// </summary>
[Required]
public string DocumentDirectory { get; set; }
/// <summary>
@ -37,30 +36,53 @@ namespace Microsoft.Extensions.ApiDescription.Client
public override bool Execute()
{
var outputs = new List<ITaskItem>(Inputs.Length);
var destinations = new HashSet<string>();
foreach (var item in Inputs)
{
var newItem = new TaskItem(item);
outputs.Add(newItem);
var codeGenerator = item.GetMetadata("CodeGenerator");
var isTypeScript = codeGenerator.EndsWith("TypeScript", StringComparison.OrdinalIgnoreCase);
var outputPath = item.GetMetadata("OutputPath");
if (string.IsNullOrEmpty(outputPath))
var documentGenerator = item.GetMetadata("DocumentGenerator");
if (string.IsNullOrEmpty(documentGenerator))
{
var className = item.GetMetadata("ClassName");
outputPath = className + (isTypeScript ? ".ts" : ".cs");
// This case occurs when user overrides the default metadata.
Log.LogError(Resources.FormatInvalidEmptyMetadataValue(
"DocumentGenerator",
"ServiceProjectReference",
item.ItemSpec));
}
var documentPath = item.GetMetadata("DocumentPath");
if (string.IsNullOrEmpty(documentPath))
{
var filename = item.GetMetadata("Filename");
var documentName = item.GetMetadata("DocumentName");
if (string.IsNullOrEmpty(documentName))
{
documentName = "v1";
}
documentPath = $"{filename}.{documentName}.json";
}
documentPath = GetFullPath(documentPath);
MetadataSerializer.SetMetadata(newItem, "DocumentPath", documentPath);
if (!destinations.Add(documentPath))
{
// This case may occur when user is experimenting e.g. with multiple generators or options.
// May also occur when user accidentally duplicates DocumentPath metadata.
Log.LogError(Resources.FormatDuplicateProjectDocumentPaths(documentPath));
}
// Add metadata which may be used as a property and passed to an inner build.
newItem.SetMetadata("SerializedMetadata", MetadataSerializer.SerializeMetadata(newItem));
outputPath = GetFullPath(outputPath);
newItem.SetMetadata("OutputPath", outputPath);
}
Outputs = outputs.ToArray();
return true;
return !Log.HasLoggedErrors;
}
private string GetFullPath(string path)

View File

@ -17,7 +17,6 @@ namespace Microsoft.Extensions.ApiDescription.Client
/// <summary>
/// Default directory for DocumentPath metadata values.
/// </summary>
[Required]
public string DocumentDirectory { get; set; }
/// <summary>
@ -36,6 +35,7 @@ namespace Microsoft.Extensions.ApiDescription.Client
public override bool Execute()
{
var outputs = new List<ITaskItem>(Inputs.Length);
var destinations = new HashSet<string>();
foreach (var item in Inputs)
{
var newItem = new TaskItem(item);
@ -96,11 +96,18 @@ namespace Microsoft.Extensions.ApiDescription.Client
documentPath = GetFullPath(documentPath);
MetadataSerializer.SetMetadata(newItem, "DocumentPath", documentPath);
if (!destinations.Add(documentPath))
{
// This case may occur when user is experimenting e.g. with multiple code generators or options.
// May also occur when user accidentally duplicates DocumentPath metadata.
Log.LogError(Resources.FormatDuplicateUriDocumentPaths(documentPath));
}
}
Outputs = outputs.ToArray();
return true;
return !Log.HasLoggedErrors;
}
private string GetFullPath(string path)

View File

@ -0,0 +1,86 @@
// <auto-generated />
namespace Microsoft.Extensions.ApiDescription.Client
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.Extensions.ApiDescription.Client.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// Multiple items have OutputPath='{0}'. All ServiceFileReference, ServiceProjectReference and ServiceUriReference items must have unique OutputPath metadata.
/// </summary>
internal static string DuplicateFileOutputPaths
{
get => GetString("DuplicateFileOutputPaths");
}
/// <summary>
/// Multiple items have OutputPath='{0}'. All ServiceFileReference, ServiceProjectReference and ServiceUriReference items must have unique OutputPath metadata.
/// </summary>
internal static string FormatDuplicateFileOutputPaths(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("DuplicateFileOutputPaths"), p0);
/// <summary>
/// Mutliple ServiceProjectReference items have DocumentPath='{0}'. ServiceProjectReference items must have unique DocumentPath metadata.
/// </summary>
internal static string DuplicateProjectDocumentPaths
{
get => GetString("DuplicateProjectDocumentPaths");
}
/// <summary>
/// Mutliple ServiceProjectReference items have DocumentPath='{0}'. ServiceProjectReference items must have unique DocumentPath metadata.
/// </summary>
internal static string FormatDuplicateProjectDocumentPaths(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("DuplicateProjectDocumentPaths"), p0);
/// <summary>
/// Mutliple ServiceUriReference items have DocumentPath='{0}'. ServiceUriReference items must have unique DocumentPath metadata.
/// </summary>
internal static string DuplicateUriDocumentPaths
{
get => GetString("DuplicateUriDocumentPaths");
}
/// <summary>
/// Mutliple ServiceUriReference items have DocumentPath='{0}'. ServiceUriReference items must have unique DocumentPath metadata.
/// </summary>
internal static string FormatDuplicateUriDocumentPaths(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("DuplicateUriDocumentPaths"), p0);
/// <summary>
/// Invalid {0} metadata value for {1} item '{2}'. {0} metadata must not be set to the empty string.
/// </summary>
internal static string InvalidEmptyMetadataValue
{
get => GetString("InvalidEmptyMetadataValue");
}
/// <summary>
/// Invalid {0} metadata value for {1} item '{2}'. {0} metadata must not be set to the empty string.
/// </summary>
internal static string FormatInvalidEmptyMetadataValue(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("InvalidEmptyMetadataValue"), p0, p1, p2);
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -0,0 +1,134 @@
<?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="DuplicateFileOutputPaths" xml:space="preserve">
<value>Multiple items have OutputPath='{0}'. All ServiceFileReference, ServiceProjectReference and ServiceUriReference items must have unique OutputPath metadata.</value>
<comment>ServiceProjectReference and ServiceUriReference items become ServiceFileReference items and all ServiceFileReference items must have unique OutputPath metadata.</comment>
</data>
<data name="DuplicateProjectDocumentPaths" xml:space="preserve">
<value>Mutliple ServiceProjectReference items have DocumentPath='{0}'. ServiceProjectReference items must have unique DocumentPath metadata.</value>
</data>
<data name="DuplicateUriDocumentPaths" xml:space="preserve">
<value>Mutliple ServiceUriReference items have DocumentPath='{0}'. ServiceUriReference items must have unique DocumentPath metadata.</value>
<comment>Ignore corner case of ServiceProjectReference and ServiceUriReference items having the same DocumentPath.</comment>
</data>
<data name="InvalidEmptyMetadataValue" xml:space="preserve">
<value>Invalid {0} metadata value for {1} item '{2}'. {0} metadata must not be set to the empty string.</value>
</data>
</root>

View File

@ -5,6 +5,7 @@
<ServiceProjectReferenceGeneratorDependsOn>
_ServiceProjectReferenceGenerator_GetTargetFramework;
_ServiceProjectReferenceGenerator_GetProjectTargetPath;
_ServiceProjectReferenceGenerator_GetMetadata;
_ServiceProjectReferenceGenerator_Build;
_ServiceProjectReferenceGenerator_Core;
_ServiceProjectReferenceGenerator_SetMetadata
@ -14,7 +15,6 @@
_ServiceUriReferenceGenerator_Core
</ServiceUriReferenceGeneratorDependsOn>
<ServiceFileReferenceGeneratorDependsOn>
_CheckServiceReferences;
ServiceProjectReferenceGenerator;
ServiceUriReferenceGenerator;
_ServiceFileReferenceGenerator_GetMetadata;
@ -23,15 +23,6 @@
</ServiceFileReferenceGeneratorDependsOn>
</PropertyGroup>
<Target Name="_CheckServiceReferences">
<Error Condition="'@(ServiceProjectReference)' != '' AND '%(CodeGenerator)' == ''"
Text="ServiceProjectReference items '@(ServiceProjectReference)' lack CodeGenerator metadata." />
<Error Condition="'@(ServiceUriReference)' != '' AND '%(CodeGenerator)' == ''"
Text="ServiceUriReference items '@(ServiceUriReference)' lack CodeGenerator metadata." />
<Error Condition="'@(ServiceFileReference)' != '' AND '%(CodeGenerator)' == ''"
Text="ServiceFileReference items '@(ServiceFileReference)' lack CodeGenerator metadata." />
</Target>
<!-- ServiceProjectReference support -->
<!-- Metadata setup phase 1: Ensure items have TargetFramework metadata. Call GetTargetFrameworks in the target project. -->
@ -116,6 +107,28 @@
</PropertyGroup>
</Target>
<!-- Metadata setup phase 3: Ensure items have DocumentPath metadata. -->
<Target Name="_ServiceProjectReferenceGenerator_GetMetadata" Condition="'@(ServiceProjectReference)' != ''">
<ItemGroup>
<_Temporary Remove="@(_Temporary)" />
</ItemGroup>
<GetProjectReferenceMetadata Inputs="@(ServiceProjectReference)" DocumentDirectory="$(ServiceProjectReferenceDirectory)">
<Output TaskParameter="Outputs" ItemName="_Temporary" />
</GetProjectReferenceMetadata>
<ItemGroup>
<ServiceProjectReference Remove="@(ServiceProjectReference)" />
<ServiceProjectReference Include="@(_Temporary)" />
</ItemGroup>
<ItemGroup>
<_Temporary Remove="@(_Temporary)" />
</ItemGroup>
<Message Importance="high" Text="%0A_ServiceProjectReferenceGenerator_GetMetadata:" />
<Message Importance="high" Text=" @(ServiceProjectReference): %(DocumentPath)" />
</Target>
<Target Name="_ServiceProjectReferenceGenerator_Build"
Condition="'$(BuildProjectReferences)' == 'true'"
Inputs="@(ServiceProjectReference)"