コード例 #1
0
        /// <inheritdoc />
        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");
                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 outputPath = item.GetMetadata("OutputPath");
                if (string.IsNullOrEmpty(outputPath))
                {
                    // No need to further sanitize this path.
                    var filename     = item.GetMetadata("Filename");
                    var isTypeScript = codeGenerator.EndsWith(TypeScriptLanguageName, StringComparison.OrdinalIgnoreCase);
                    outputPath = $"{filename}Client{(isTypeScript ? ".ts" : Extension)}";
                }

                // Place output file in correct directory (relative to project directory).
                if (!Path.IsPathRooted(outputPath) && !string.IsNullOrEmpty(OutputDirectory))
                {
                    outputPath = Path.Combine(OutputDirectory, 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));
                }

                MetadataSerializer.SetMetadata(newItem, "OutputPath", outputPath);

                var className = item.GetMetadata("ClassName");
                if (string.IsNullOrEmpty(className))
                {
                    var outputFilename = Path.GetFileNameWithoutExtension(outputPath);

                    className = CSharpIdentifier.SanitizeIdentifier(outputFilename);
                    MetadataSerializer.SetMetadata(newItem, "ClassName", className);
                }

                var @namespace = item.GetMetadata("Namespace");
                if (string.IsNullOrEmpty(@namespace))
                {
                    MetadataSerializer.SetMetadata(newItem, "Namespace", Namespace);
                }

                // Add metadata which may be used as a property and passed to an inner build.
                newItem.RemoveMetadata("SerializedMetadata");
                newItem.SetMetadata("SerializedMetadata", MetadataSerializer.SerializeMetadata(newItem));
            }

            Outputs = outputs.ToArray();

            return(!Log.HasLoggedErrors);
        }
コード例 #2
0
        /// <inheritdoc />
        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 documentPath = item.GetMetadata("DocumentPath");
                if (string.IsNullOrEmpty(documentPath))
                {
                    var uri     = item.ItemSpec;
                    var builder = new UriBuilder(uri);
                    if (!builder.Uri.IsAbsoluteUri)
                    {
                        Log.LogError($"{nameof(Inputs)} item '{uri}' is not an absolute URI.");
                        return(false);
                    }

                    if (!string.Equals(Uri.UriSchemeHttp, builder.Scheme, StringComparison.OrdinalIgnoreCase) &&
                        !string.Equals(Uri.UriSchemeHttps, builder.Scheme, StringComparison.OrdinalIgnoreCase))
                    {
                        Log.LogError($"{nameof(Inputs)} item '{uri}' does not have scheme {Uri.UriSchemeHttp} or " +
                                     $"{Uri.UriSchemeHttps}.");
                        return(false);
                    }

                    var host = builder.Host
                               .Replace("/", string.Empty)
                               .Replace("[", string.Empty)
                               .Replace("]", string.Empty)
                               .Replace(':', '_');
                    var path = builder.Path
                               .Replace("!", string.Empty)
                               .Replace("'", string.Empty)
                               .Replace("$", string.Empty)
                               .Replace("%", string.Empty)
                               .Replace("&", string.Empty)
                               .Replace("(", string.Empty)
                               .Replace(")", string.Empty)
                               .Replace("*", string.Empty)
                               .Replace("@", string.Empty)
                               .Replace("~", string.Empty)
                               .Replace('/', '_')
                               .Replace(':', '_')
                               .Replace(';', '_')
                               .Replace('+', '_')
                               .Replace('=', '_');

                    documentPath = host + path;
                    if (char.IsLower(documentPath[0]))
                    {
                        documentPath = char.ToUpper(documentPath[0]) + documentPath.Substring(startIndex: 1);
                    }

                    if (!documentPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
                    {
                        documentPath = $"{documentPath}.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 code generators or options.
                    // May also occur when user accidentally duplicates DocumentPath metadata.
                    Log.LogError(Resources.FormatDuplicateUriDocumentPaths(documentPath));
                }
            }

            Outputs = outputs.ToArray();

            return(!Log.HasLoggedErrors);
        }
コード例 #3
0
        /// <inheritdoc />
        public override bool Execute()
        {
            Outputs = new[] { MetadataSerializer.DeserializeMetadata(Input) };

            return(true);
        }
コード例 #4
0
        /// <inheritdoc />
        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 documentGenerator = item.GetMetadata("DocumentGenerator");
                if (string.IsNullOrEmpty(documentGenerator))
                {
                    // This case occurs when user overrides the default metadata.
                    Log.LogError(Resources.FormatInvalidEmptyMetadataValue(
                                     "DocumentGenerator",
                                     "ServiceProjectReference",
                                     item.ItemSpec));
                }

                var documentName = item.GetMetadata("DocumentName");
                if (string.IsNullOrEmpty(documentName))
                {
                    documentName = "v1";
                    MetadataSerializer.SetMetadata(newItem, "DocumentName", documentName);
                }

                var documentPath = item.GetMetadata("DocumentPath");
                if (string.IsNullOrEmpty(documentPath))
                {
                    // No need to sanitize the filename since the project file exists.
                    var projectFilename = item.GetMetadata("Filename");

                    // Default document filename matches project filename unless given a non-default document name.
                    if (string.IsNullOrEmpty(documentName))
                    {
                        // This is an odd (but allowed) case that would break the sanitize one-liner below. Also,
                        // ensure chosen name does not match the "v1" case.
                        documentPath = projectFilename + "_.json";
                    }
                    else if (string.Equals("v1", documentName, StringComparison.Ordinal))
                    {
                        documentPath = projectFilename + ".json";
                    }
                    else
                    {
                        // Sanitize the document name because it may contain almost any character, including illegal
                        // filename characters such as '/' and '?'. (Do not treat slashes as folder separators.)
                        var sanitizedDocumentName = string.Join("_", documentName.Split(InvalidFilenameCharacters));
                        while (sanitizedDocumentName.Contains(InvalidFilenameStrings[0]))
                        {
                            sanitizedDocumentName = string.Join(
                                ".",
                                sanitizedDocumentName.Split(InvalidFilenameStrings, StringSplitOptions.None));
                        }

                        documentPath = $"{projectFilename}_{sanitizedDocumentName}";

                        // Possible the document path already ends with .json. Don't duplicate that or a final period.
                        if (!documentPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
                        {
                            if (documentPath.EndsWith(".", StringComparison.Ordinal))
                            {
                                documentPath += "json";
                            }
                            else
                            {
                                documentPath += ".json";
                            }
                        }
                    }
                }

                documentPath = GetFullPath(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));
                }

                MetadataSerializer.SetMetadata(newItem, "DocumentPath", documentPath);

                // 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(!Log.HasLoggedErrors);
        }
コード例 #5
0
        /// <inheritdoc />
        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 uri     = item.ItemSpec;
                var builder = new UriBuilder(uri);
                if (!builder.Uri.IsAbsoluteUri)
                {
                    Log.LogError($"{nameof(Inputs)} item '{uri}' is not an absolute URI.");
                    return(false);
                }

                if (!string.Equals(Uri.UriSchemeHttp, builder.Scheme, StringComparison.OrdinalIgnoreCase) &&
                    !string.Equals(Uri.UriSchemeHttps, builder.Scheme, StringComparison.OrdinalIgnoreCase))
                {
                    Log.LogError($"{nameof(Inputs)} item '{uri}' does not have scheme {Uri.UriSchemeHttp} or " +
                                 $"{Uri.UriSchemeHttps}.");
                    return(false);
                }

                // If not specified, base filename on the URI.
                var documentPath = item.GetMetadata("DocumentPath");
                if (string.IsNullOrEmpty(documentPath))
                {
                    // Default to a fairly long but identifiable and fairly unique filename.
                    var documentPathBuilder = new StringBuilder(builder.Host);
                    if (!string.IsNullOrEmpty(builder.Path) &&
                        !string.Equals("/", builder.Path, StringComparison.Ordinal))
                    {
                        documentPathBuilder.Append(builder.Path);
                    }

                    if (!string.IsNullOrEmpty(builder.Query) &&
                        !string.Equals("?", builder.Query, StringComparison.Ordinal))
                    {
                        documentPathBuilder.Append(builder.Query);
                    }

                    // Sanitize the string because it likely contains illegal filename characters such as '/' and '?'.
                    // (Do not treat slashes as folder separators.)
                    documentPath = documentPathBuilder.ToString();
                    documentPath = string.Join("_", documentPath.Split(InvalidFilenameCharacters));
                    while (documentPath.Contains(InvalidFilenameStrings[0]))
                    {
                        documentPath = string.Join(
                            ".",
                            documentPath.Split(InvalidFilenameStrings, StringSplitOptions.None));
                    }

                    // URI might end with ".json". Don't duplicate that or a final period.
                    if (!documentPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
                    {
                        if (documentPath.EndsWith(".", StringComparison.Ordinal))
                        {
                            documentPath += "json";
                        }
                        else
                        {
                            documentPath += ".json";
                        }
                    }
                }

                documentPath = GetFullPath(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));
                }

                MetadataSerializer.SetMetadata(newItem, "DocumentPath", documentPath);
            }

            Outputs = outputs.ToArray();

            return(!Log.HasLoggedErrors);
        }